title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Computer Programming - Functions
A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing. You have already seen various functions like printf() and main(). These are called built-in functions provided by the language itself, but we can write our own functions as well and this tutorial will teach you how to write and use those functions in C programming language. Good thing about functions is that they are famous with several names. Different programming languages name them differently, for example, functions, methods, sub-routines, procedures, etc. If you come across any such terminology, then just imagine about the same concept, which we are going to discuss in this tutorial. Let's start with a program where we will define two arrays of numbers and then from each array, we will find the biggest number. Given below are the steps to find out the maximum number from a given set of numbers − 1. Get a list of numbers L1, L2, L3....LN 2. Assume L1 is the largest, Set max = L1 3. Take next number Li from the list and do the following 4. If max is less than Li 5. Set max = Li 6. If Li is last number from the list then 7. Print value stored in max and come out 8. Else prepeat same process starting from step 3 Let's translate the above program in C programming language − #include <stdio.h> int main() { int set1[5] = {10, 20, 30, 40, 50}; int set2[5] = {101, 201, 301, 401, 501}; int i, max; /* Process first set of numbers available in set1[] */ max = set1[0]; i = 1; while( i < 5 ) { if( max < set1[i] ) { max = set1[i]; } i = i + 1; } printf("Max in first set = %d\n", max ); /* Now process second set of numbers available in set2[] */ max = set2[0]; i = 1; while( i < 5 ) { if( max < set2[i] ) { max = set2[i]; } i = i + 1; } printf("Max in second set = %d\n", max ); } When the above code is compiled and executed, it produces the following result − Max in first set = 50 Max in second set = 501 If you are clear about the above example, then it will become easy to understand why we need a function. In the above example, there are only two sets of numbers, set1 and set2, but consider a situation where we have 10 or more similar sets of numbers to find out the maximum numbers from each set. In such a situation, we will have to repeat, processing 10 or more times and ultimately, the program will become too large with repeated code. To handle such situation, we write our functions where we try to keep the source code which will be used again and again in our programming. Now, let's see how to define a function in C programming language and then in the subsequent sections, we will explain how to use them. The general form of a function definition in C programming language is as follows − return_type function_name( parameter list ) { body of the function return [expression]; } A function definition in C programming consists of a function header and a function body. Here are all the parts of a function − Return Type − A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void. Return Type − A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void. Function Name − This is the actual name of the function. The function name and the parameter list together constitute the function signature. Function Name − This is the actual name of the function. The function name and the parameter list together constitute the function signature. Parameter List − A parameter is like a placeholder. When a function is invoked, you pass a value as a parameter. This value is referred to as the actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters. Parameter List − A parameter is like a placeholder. When a function is invoked, you pass a value as a parameter. This value is referred to as the actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters. Function Body − The function body contains a collection of statements that defines what the function does. Function Body − The function body contains a collection of statements that defines what the function does. While creating a C function, you give a definition of what the function has to do. To use a function, you will have to call that function to perform a defined task. Now, let's write the above example with the help of a function − #include <stdio.h> int getMax( int set[] ) { int i, max; max = set[0]; i = 1; while( i < 5 ) { if( max < set[i] ) { max = set[i]; } i = i + 1; } return max; } main() { int set1[5] = {10, 20, 30, 40, 50}; int set2[5] = {101, 201, 301, 401, 501}; int max; /* Process first set of numbers available in set1[] */ max = getMax(set1); printf("Max in first set = %d\n", max ); /* Now process second set of numbers available in set2[] */ max = getMax(set2); printf("Max in second set = %d\n", max ); } When the above code is compiled and executed, it produces the following result − Max in first set = 50 Max in second set = 501 If you are clear about functions in C programming, then it is easy to understand them in Java as well. Java programming names them as methods, but the rest of the concepts remain more or less same. Following is the equivalent program written in Java. You can try to execute it to see the output − public class DemoJava { public static void main(String []args) { int[] set1 = {10, 20, 30, 40, 50}; int[] set2 = {101, 201, 301, 401, 501}; int max; /* Process first set of numbers available in set1[] */ max = getMax(set1); System.out.format("Max in first set = %d\n", max ); /* Now process second set of numbers available in set2[] */ max = getMax(set2); System.out.format("Max in second set = %d\n", max ); } public static int getMax( int set[] ) { int i, max; max = set[0]; i = 1; while( i < 5 ) { if( max < set[i] ) { max = set[i]; } i = i + 1; } return max; } } When the above program is executed, it produces the following result − Max in first set = 50 Max in second set = 501 Once again, if you know the concept of functions in C and Java programming, then Python is not much different. Given below is the basic syntax of defining a function in Python − def function_name( parameter list ): body of the function return [expression] Using this syntax of function in Python, the above example can be written as follows − def getMax( set ): max = set[0] i = 1 while( i < 5 ): if( max < set[i] ): max = set[i] i = i + 1 return max set1 = [10, 20, 30, 40, 50] set2 = [101, 201, 301, 401, 501] # Process first set of numbers available in set1[] max = getMax(set1) print "Max in first set = ", max # Now process second set of numbers available in set2[] max = getMax(set2) print "Max in second set = ", max When the above code is executed, it produces the following result − Max in first set = 50 Max in second set = 501 107 Lectures 13.5 hours Arnab Chakraborty 106 Lectures 8 hours Arnab Chakraborty 99 Lectures 6 hours Arnab Chakraborty 46 Lectures 2.5 hours Shweta 70 Lectures 9 hours Abhilash Nelson 52 Lectures 7 hours Abhishek And Pukhraj Print Add Notes Bookmark this page
[ { "code": null, "e": 2607, "s": 2140, "text": "A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing. You have already seen various functions like printf() and main(). These are called built-in functions provided by the language itself, but we can write our own functions as well and this tutorial will teach you how to write and use those functions in C programming language." }, { "code": null, "e": 2928, "s": 2607, "text": "Good thing about functions is that they are famous with several names. Different programming languages name them differently, for example, functions, methods, sub-routines, procedures, etc. If you come across any such terminology, then just imagine about the same concept, which we are going to discuss in this tutorial." }, { "code": null, "e": 3144, "s": 2928, "text": "Let's start with a program where we will define two arrays of numbers and then from each array, we will find the biggest number. Given below are the steps to find out the maximum number from a given set of numbers −" }, { "code": null, "e": 3482, "s": 3144, "text": "1. Get a list of numbers L1, L2, L3....LN\n2. Assume L1 is the largest, Set max = L1\n3. Take next number Li from the list and do the following\n4. If max is less than Li\n5. Set max = Li\n6. If Li is last number from the list then\n7. Print value stored in max and come out\n8. Else prepeat same process starting from step 3\n" }, { "code": null, "e": 3544, "s": 3482, "text": "Let's translate the above program in C programming language −" }, { "code": null, "e": 4170, "s": 3544, "text": "#include <stdio.h>\n\nint main() {\n int set1[5] = {10, 20, 30, 40, 50};\n int set2[5] = {101, 201, 301, 401, 501};\n int i, max;\n \n /* Process first set of numbers available in set1[] */\n max = set1[0];\n i = 1; \n while( i < 5 ) {\n if( max < set1[i] ) {\n max = set1[i];\n }\n i = i + 1;\n }\n \n printf(\"Max in first set = %d\\n\", max );\n \n /* Now process second set of numbers available in set2[] */\n max = set2[0];\n i = 1; \n while( i < 5 ) {\n if( max < set2[i] ) {\n max = set2[i];\n }\n i = i + 1;\n }\n printf(\"Max in second set = %d\\n\", max );\n}" }, { "code": null, "e": 4251, "s": 4170, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 4298, "s": 4251, "text": "Max in first set = 50\nMax in second set = 501\n" }, { "code": null, "e": 4881, "s": 4298, "text": "If you are clear about the above example, then it will become easy to understand why we need a function. In the above example, there are only two sets of numbers, set1 and set2, but consider a situation where we have 10 or more similar sets of numbers to find out the maximum numbers from each set. In such a situation, we will have to repeat, processing 10 or more times and ultimately, the program will become too large with repeated code. To handle such situation, we write our functions where we try to keep the source code which will be used again and again in our programming." }, { "code": null, "e": 5017, "s": 4881, "text": "Now, let's see how to define a function in C programming language and then in the subsequent sections, we will explain how to use them." }, { "code": null, "e": 5101, "s": 5017, "text": "The general form of a function definition in C programming language is as follows −" }, { "code": null, "e": 5201, "s": 5101, "text": "return_type function_name( parameter list ) {\n body of the function\n \n return [expression];\n}" }, { "code": null, "e": 5330, "s": 5201, "text": "A function definition in C programming consists of a function header and a function body. Here are all the parts of a function −" }, { "code": null, "e": 5567, "s": 5330, "text": "Return Type − A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void." }, { "code": null, "e": 5804, "s": 5567, "text": "Return Type − A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void." }, { "code": null, "e": 5946, "s": 5804, "text": "Function Name − This is the actual name of the function. The function name and the parameter list together constitute the function signature." }, { "code": null, "e": 6088, "s": 5946, "text": "Function Name − This is the actual name of the function. The function name and the parameter list together constitute the function signature." }, { "code": null, "e": 6426, "s": 6088, "text": "Parameter List − A parameter is like a placeholder. When a function is invoked, you pass a value as a parameter. This value is referred to as the actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters." }, { "code": null, "e": 6764, "s": 6426, "text": "Parameter List − A parameter is like a placeholder. When a function is invoked, you pass a value as a parameter. This value is referred to as the actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters." }, { "code": null, "e": 6871, "s": 6764, "text": "Function Body − The function body contains a collection of statements that defines what the function does." }, { "code": null, "e": 6978, "s": 6871, "text": "Function Body − The function body contains a collection of statements that defines what the function does." }, { "code": null, "e": 7143, "s": 6978, "text": "While creating a C function, you give a definition of what the function has to do. To use a function, you will have to call that function to perform a defined task." }, { "code": null, "e": 7208, "s": 7143, "text": "Now, let's write the above example with the help of a function −" }, { "code": null, "e": 7790, "s": 7208, "text": "#include <stdio.h>\n\nint getMax( int set[] ) {\n int i, max;\n \n max = set[0];\n i = 1; \n while( i < 5 ) {\n if( max < set[i] ) {\n max = set[i];\n }\n i = i + 1;\n }\n return max;\n}\nmain() {\n int set1[5] = {10, 20, 30, 40, 50};\n int set2[5] = {101, 201, 301, 401, 501};\n int max;\n\n /* Process first set of numbers available in set1[] */\n max = getMax(set1);\n printf(\"Max in first set = %d\\n\", max );\n \n /* Now process second set of numbers available in set2[] */\n max = getMax(set2);\n printf(\"Max in second set = %d\\n\", max );\n}" }, { "code": null, "e": 7871, "s": 7790, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 7918, "s": 7871, "text": "Max in first set = 50\nMax in second set = 501\n" }, { "code": null, "e": 8116, "s": 7918, "text": "If you are clear about functions in C programming, then it is easy to understand them in Java as well. Java programming names them as methods, but the rest of the concepts remain more or less same." }, { "code": null, "e": 8215, "s": 8116, "text": "Following is the equivalent program written in Java. You can try to execute it to see the output −" }, { "code": null, "e": 8937, "s": 8215, "text": "public class DemoJava {\n public static void main(String []args) {\n int[] set1 = {10, 20, 30, 40, 50};\n int[] set2 = {101, 201, 301, 401, 501};\n int max;\n\n /* Process first set of numbers available in set1[] */\n max = getMax(set1);\n System.out.format(\"Max in first set = %d\\n\", max );\n\n /* Now process second set of numbers available in set2[] */\n max = getMax(set2);\n System.out.format(\"Max in second set = %d\\n\", max );\n }\n public static int getMax( int set[] ) {\n int i, max;\n max = set[0];\n i = 1; \n \n while( i < 5 ) {\n if( max < set[i] ) {\n max = set[i];\n }\n i = i + 1;\n }\n return max;\n }\n}" }, { "code": null, "e": 9008, "s": 8937, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 9055, "s": 9008, "text": "Max in first set = 50\nMax in second set = 501\n" }, { "code": null, "e": 9233, "s": 9055, "text": "Once again, if you know the concept of functions in C and Java programming, then Python is not much different. Given below is the basic syntax of defining a function in Python −" }, { "code": null, "e": 9322, "s": 9233, "text": "def function_name( parameter list ):\n body of the function\n \n return [expression]\n" }, { "code": null, "e": 9409, "s": 9322, "text": "Using this syntax of function in Python, the above example can be written as follows −" }, { "code": null, "e": 9845, "s": 9409, "text": "def getMax( set ):\n max = set[0]\n i = 1 \n \n while( i < 5 ):\n if( max < set[i] ):\n max = set[i]\n \n i = i + 1\n return max\n\nset1 = [10, 20, 30, 40, 50]\nset2 = [101, 201, 301, 401, 501]\n\n# Process first set of numbers available in set1[]\nmax = getMax(set1)\nprint \"Max in first set = \", max\n \n# Now process second set of numbers available in set2[]\nmax = getMax(set2)\nprint \"Max in second set = \", max" }, { "code": null, "e": 9913, "s": 9845, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 9962, "s": 9913, "text": "Max in first set = 50\nMax in second set = 501\n" }, { "code": null, "e": 9999, "s": 9962, "text": "\n 107 Lectures \n 13.5 hours \n" }, { "code": null, "e": 10018, "s": 9999, "text": " Arnab Chakraborty" }, { "code": null, "e": 10052, "s": 10018, "text": "\n 106 Lectures \n 8 hours \n" }, { "code": null, "e": 10071, "s": 10052, "text": " Arnab Chakraborty" }, { "code": null, "e": 10104, "s": 10071, "text": "\n 99 Lectures \n 6 hours \n" }, { "code": null, "e": 10123, "s": 10104, "text": " Arnab Chakraborty" }, { "code": null, "e": 10158, "s": 10123, "text": "\n 46 Lectures \n 2.5 hours \n" }, { "code": null, "e": 10166, "s": 10158, "text": " Shweta" }, { "code": null, "e": 10199, "s": 10166, "text": "\n 70 Lectures \n 9 hours \n" }, { "code": null, "e": 10216, "s": 10199, "text": " Abhilash Nelson" }, { "code": null, "e": 10249, "s": 10216, "text": "\n 52 Lectures \n 7 hours \n" }, { "code": null, "e": 10271, "s": 10249, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 10278, "s": 10271, "text": " Print" }, { "code": null, "e": 10289, "s": 10278, "text": " Add Notes" } ]
How to create train, test and validation samples from an R data frame?
To create predictive models, it is necessary to create three subsets of a data set for the purpose of training the model, testing the model and checking the validation of the model. These subsets are usually called train, test and validation. For this purpose, we can use different type of sampling methods and the most common is random sampling. In the below example, you can see how it can be done. Consider the mtcars data set in base R − Live Demo data(mtcars) str(mtcars) 'data.frame':32 obs. of 11 variables: $ mpg : num 21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ... $ cyl : num 6 6 4 6 8 6 8 4 4 6 ... $ disp: num 160 160 108 258 360 ... $ hp : num 110 110 93 110 175 105 245 62 95 123 ... $ drat: num 3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ... $ wt : num 2.62 2.88 2.32 3.21 3.44 ... $ qsec: num 16.5 17 18.6 19.4 17 ... $ vs : num 0 0 1 1 0 1 0 1 1 1 ... $ am : num 1 1 1 0 0 0 0 0 0 0 ... $ gear: num 4 4 4 3 3 3 3 4 4 4 ... $ carb: num 4 4 1 1 2 1 4 2 2 4 ... Live Demo head(mtcars) mpg cyl disp hp drat wt qsec vs am gear carb Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1 Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2 Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1 Creating train, test and validation samples − Live Demo Samples<-sample(seq(1,3),size=nrow(mtcars),replace=TRUE,prob=c(0.8,0.2,0.2)) Train<-mtcars[Samples==1,] Test<-mtcars[Samples==2,] Validate<-mtcars[Samples==3,] Train mpg cyl disp hp drat wt qsec vs am gear carb Mazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4 Mazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4 Datsun 710 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1 Hornet Sportabout 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2 Valiant 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1 Duster 360 14.3 8 360.0 245 3.21 3.570 15.84 0 0 3 4 Merc 240D 24.4 4 146.7 62 3.69 3.190 20.00 1 0 4 2 Merc 280 19.2 6 167.6 123 3.92 3.440 18.30 1 0 4 4 Merc 280C 17.8 6 167.6 123 3.92 3.440 18.90 1 0 4 4 Merc 450SE 16.4 8 275.8 180 3.07 4.070 17.40 0 0 3 3 Merc 450SLC 15.2 8 275.8 180 3.07 3.780 18.00 0 0 3 3 Lincoln Continental 10.4 8 460.0 215 3.00 5.424 17.82 0 0 3 4 Fiat 128 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1 Toyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1 Toyota Corona 21.5 4 120.1 97 3.70 2.465 20.01 1 0 3 1 Camaro Z28 13.3 8 350.0 245 3.73 3.840 15.41 0 0 3 4 Porsche 914-2 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2 Ford Pantera L 15.8 8 351.0 264 4.22 3.170 14.50 0 1 5 4 Maserati Bora 15.0 8 301.0 335 3.54 3.570 14.60 0 1 5 8 Test mpg cyl disp hp drat wt qsec vs am gear carb Mazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4 Valiant 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1 Honda Civic 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2 Fiat X1-9 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1 Lotus Europa 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2 Ferrari Dino 19.7 6 145.0 175 3.62 2.770 15.50 0 1 5 6 Validate mpg cyl disp hp drat wt qsec vs am gear carb Merc 230 22.8 4140.8 95 3.92 3.150 22.90 1 0 4 2 Merc 450SE 16.4 8 275.8 180 3.07 4.070 17.40 0 0 3 3 Cadillac Fleetwood 10.4 8 472.0 205 2.93 5.250 17.98 0 0 3 4 Lincoln Continental 10.4 8 460.0 215 3.00 5.424 17.82 0 0 3 4 Dodge Challenger 15.5 8 318.0 150 2.76 3.520 16.87 0 0 3 2 Ford Pantera L 15.8 8 351.0 264 4.22 3.170 14.50 0 1 5 4
[ { "code": null, "e": 1463, "s": 1062, "text": "To create predictive models, it is necessary to create three subsets of a data set for the purpose of training the model, testing the model and checking the validation of the model. These subsets are usually called train, test and validation. For this purpose, we can use different type of sampling methods and the most common is random sampling. In the below example, you can see how it can be done." }, { "code": null, "e": 1504, "s": 1463, "text": "Consider the mtcars data set in base R −" }, { "code": null, "e": 1515, "s": 1504, "text": " Live Demo" }, { "code": null, "e": 1540, "s": 1515, "text": "data(mtcars)\nstr(mtcars)" }, { "code": null, "e": 2047, "s": 1540, "text": "'data.frame':32 obs. of 11 variables:\n$ mpg : num 21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...\n$ cyl : num 6 6 4 6 8 6 8 4 4 6 ...\n$ disp: num 160 160 108 258 360 ...\n$ hp : num 110 110 93 110 175 105 245 62 95 123 ...\n$ drat: num 3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ...\n$ wt : num 2.62 2.88 2.32 3.21 3.44 ...\n$ qsec: num 16.5 17 18.6 19.4 17 ...\n$ vs : num 0 0 1 1 0 1 0 1 1 1 ...\n$ am : num 1 1 1 0 0 0 0 0 0 0 ...\n$ gear: num 4 4 4 3 3 3 3 4 4 4 ...\n$ carb: num 4 4 1 1 2 1 4 2 2 4 ..." }, { "code": null, "e": 2058, "s": 2047, "text": " Live Demo" }, { "code": null, "e": 2071, "s": 2058, "text": "head(mtcars)" }, { "code": null, "e": 2473, "s": 2071, "text": " mpg cyl disp hp drat wt qsec vs am gear carb\nMazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4\nMazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4\nDatsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1\nHornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1\nHornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2\nValiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1" }, { "code": null, "e": 2519, "s": 2473, "text": "Creating train, test and validation samples −" }, { "code": null, "e": 2530, "s": 2519, "text": " Live Demo" }, { "code": null, "e": 2696, "s": 2530, "text": "Samples<-sample(seq(1,3),size=nrow(mtcars),replace=TRUE,prob=c(0.8,0.2,0.2))\nTrain<-mtcars[Samples==1,]\nTest<-mtcars[Samples==2,]\nValidate<-mtcars[Samples==3,]\nTrain" }, { "code": null, "e": 3788, "s": 2696, "text": " mpg cyl disp hp drat wt qsec vs am gear carb\nMazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4\nMazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4\nDatsun 710 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1\nHornet Sportabout 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2\nValiant 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1\nDuster 360 14.3 8 360.0 245 3.21 3.570 15.84 0 0 3 4\nMerc 240D 24.4 4 146.7 62 3.69 3.190 20.00 1 0 4 2\nMerc 280 19.2 6 167.6 123 3.92 3.440 18.30 1 0 4 4\nMerc 280C 17.8 6 167.6 123 3.92 3.440 18.90 1 0 4 4\nMerc 450SE 16.4 8 275.8 180 3.07 4.070 17.40 0 0 3 3\nMerc 450SLC 15.2 8 275.8 180 3.07 3.780 18.00 0 0 3 3\nLincoln Continental 10.4 8 460.0 215 3.00 5.424 17.82 0 0 3 4\nFiat 128 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1\nToyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1\nToyota Corona 21.5 4 120.1 97 3.70 2.465 20.01 1 0 3 1\nCamaro Z28 13.3 8 350.0 245 3.73 3.840 15.41 0 0 3 4\nPorsche 914-2 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2\nFord Pantera L 15.8 8 351.0 264 4.22 3.170 14.50 0 1 5 4\nMaserati Bora 15.0 8 301.0 335 3.54 3.570 14.60 0 1 5 8" }, { "code": null, "e": 3793, "s": 3788, "text": "Test" }, { "code": null, "e": 4186, "s": 3793, "text": " mpg cyl disp hp drat wt qsec vs am gear carb\nMazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4\nValiant 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1\nHonda Civic 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2\nFiat X1-9 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1\nLotus Europa 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2\nFerrari Dino 19.7 6 145.0 175 3.62 2.770 15.50 0 1 5 6" }, { "code": null, "e": 4195, "s": 4186, "text": "Validate" }, { "code": null, "e": 4581, "s": 4195, "text": "mpg cyl disp hp drat wt qsec vs am gear carb\nMerc 230 22.8 4140.8 95 3.92 3.150 22.90 1 0 4 2\nMerc 450SE 16.4 8 275.8 180 3.07 4.070 17.40 0 0 3 3\nCadillac Fleetwood 10.4 8 472.0 205 2.93 5.250 17.98 0 0 3 4\nLincoln Continental 10.4 8 460.0 215 3.00 5.424 17.82 0 0 3 4\nDodge Challenger 15.5 8 318.0 150 2.76 3.520 16.87 0 0 3 2\nFord Pantera L 15.8 8 351.0 264 4.22 3.170 14.50 0 1 5 4" } ]
How to make two plots side-by-side using Python?
Using subplot(row, col, index) method, we can split a figure in row*col parts, and can plot the figure at the index position. In the following program, we will create two diagrams in a single figure. Creating x, y1, y2 points using numpy. Creating x, y1, y2 points using numpy. With nrows = 1, ncols = 2, index = 1, add subplot to the current figure, using the subplot() method. With nrows = 1, ncols = 2, index = 1, add subplot to the current figure, using the subplot() method. Plot the line using x and y1 points, using the plot() method. Plot the line using x and y1 points, using the plot() method. Set up the title, label for X and Y axes for Figure 1, using plt.title(), plt.xlabel() and plt.ylabel() methods. Set up the title, label for X and Y axes for Figure 1, using plt.title(), plt.xlabel() and plt.ylabel() methods. With nrows = 1, ncols = 2, index = 2, add subplot to the current figure, using the subplot() method. With nrows = 1, ncols = 2, index = 2, add subplot to the current figure, using the subplot() method. Plot the line using x and y2 points, using the plot() method. Plot the line using x and y2 points, using the plot() method. Set up the title, label for X and Y axes for Figure 2, using plt.title(), plt.xlabel() and plt.ylabel() methods. Set up the title, label for X and Y axes for Figure 2, using plt.title(), plt.xlabel() and plt.ylabel() methods. To show the figure, use the plt.show() method. To show the figure, use the plt.show() method. from matplotlib import pyplot as plt import numpy as np xPoints = np.array([2, 4, 6, 8, 10, 12, 14, 16, 18, 20]) y1Points = np.array([12, 14, 16, 18, 10, 12, 14, 16, 18, 120]) y2Points = np.array([12, 7, 6, 5, 4, 3, 2, 2, 1, 12]) plt.subplot(1, 2, 1) # row 1, col 2 index 1 plt.plot(xPoints, y1Points) plt.title("My first plot!") plt.xlabel('X-axis ') plt.ylabel('Y-axis ') plt.subplot(1, 2, 2) # index 2 plt.plot(xPoints, y2Points) plt.title("My second plot!") plt.xlabel('X-axis ') plt.ylabel('Y-axis ') plt.show()
[ { "code": null, "e": 1262, "s": 1062, "text": "Using subplot(row, col, index) method, we can split a figure in row*col parts, and can plot the figure at the index position. In the following program, we will create two diagrams in a single figure." }, { "code": null, "e": 1301, "s": 1262, "text": "Creating x, y1, y2 points using numpy." }, { "code": null, "e": 1340, "s": 1301, "text": "Creating x, y1, y2 points using numpy." }, { "code": null, "e": 1441, "s": 1340, "text": "With nrows = 1, ncols = 2, index = 1, add subplot to the current figure, using the subplot() method." }, { "code": null, "e": 1542, "s": 1441, "text": "With nrows = 1, ncols = 2, index = 1, add subplot to the current figure, using the subplot() method." }, { "code": null, "e": 1604, "s": 1542, "text": "Plot the line using x and y1 points, using the plot() method." }, { "code": null, "e": 1666, "s": 1604, "text": "Plot the line using x and y1 points, using the plot() method." }, { "code": null, "e": 1779, "s": 1666, "text": "Set up the title, label for X and Y axes for Figure 1, using plt.title(), plt.xlabel() and plt.ylabel() methods." }, { "code": null, "e": 1892, "s": 1779, "text": "Set up the title, label for X and Y axes for Figure 1, using plt.title(), plt.xlabel() and plt.ylabel() methods." }, { "code": null, "e": 1993, "s": 1892, "text": "With nrows = 1, ncols = 2, index = 2, add subplot to the current figure, using the subplot() method." }, { "code": null, "e": 2094, "s": 1993, "text": "With nrows = 1, ncols = 2, index = 2, add subplot to the current figure, using the subplot() method." }, { "code": null, "e": 2156, "s": 2094, "text": "Plot the line using x and y2 points, using the plot() method." }, { "code": null, "e": 2218, "s": 2156, "text": "Plot the line using x and y2 points, using the plot() method." }, { "code": null, "e": 2331, "s": 2218, "text": "Set up the title, label for X and Y axes for Figure 2, using plt.title(), plt.xlabel() and plt.ylabel() methods." }, { "code": null, "e": 2444, "s": 2331, "text": "Set up the title, label for X and Y axes for Figure 2, using plt.title(), plt.xlabel() and plt.ylabel() methods." }, { "code": null, "e": 2491, "s": 2444, "text": "To show the figure, use the plt.show() method." }, { "code": null, "e": 2538, "s": 2491, "text": "To show the figure, use the plt.show() method." }, { "code": null, "e": 3059, "s": 2538, "text": "from matplotlib import pyplot as plt\nimport numpy as np\n\nxPoints = np.array([2, 4, 6, 8, 10, 12, 14, 16, 18, 20])\ny1Points = np.array([12, 14, 16, 18, 10, 12, 14, 16, 18, 120])\ny2Points = np.array([12, 7, 6, 5, 4, 3, 2, 2, 1, 12])\n\nplt.subplot(1, 2, 1) # row 1, col 2 index 1\nplt.plot(xPoints, y1Points)\nplt.title(\"My first plot!\")\nplt.xlabel('X-axis ')\nplt.ylabel('Y-axis ')\n\nplt.subplot(1, 2, 2) # index 2\nplt.plot(xPoints, y2Points)\nplt.title(\"My second plot!\")\nplt.xlabel('X-axis ')\nplt.ylabel('Y-axis ')\n\nplt.show()" } ]
Random password generator in C - GeeksforGeeks
20 Jan, 2021 In this article, we will discuss how to generate a random password of a given length consists of any characters. Approach: The below-given program involves basic concepts like variables, data types, array, loop, etc. Follow the below steps to solve this problem:Take the length of the password and declare a character array of that length to store that password.Declare character array of all the capital letters, small letters, numbers, special characters.Now according to the program below, respective if-else gets executed and a random password gets generated. Take the length of the password and declare a character array of that length to store that password. Declare character array of all the capital letters, small letters, numbers, special characters. Now according to the program below, respective if-else gets executed and a random password gets generated. Below is the program of the above approach: C // C program for the above approach#include <math.h>#include <stdio.h>#include <stdlib.h>#include <time.h> // Function to randomly generates password// of length Nvoid randomPasswordGeneration(int N){ // Initialize counter int i = 0; int randomizer = 0; // Seed the random-number generator // with current time so that the // numbers will be different every time srand((unsigned int)(time(NULL))); // Array of numbers char numbers[] = "0123456789"; // Array of small alphabets char letter[] = "abcdefghijklmnoqprstuvwyzx"; // Array of capital alphabets char LETTER[] = "ABCDEFGHIJKLMNOQPRSTUYWVZX"; // Array of all the special symbols char symbols[] = "!@#$^&*?"; // Stores the random password char password[N]; // To select the randomizer // inside the loop randomizer = rand() % 4; // Iterate over the range [0, N] for (i = 0; i < N; i++) { if (randomizer == 1) { password[i] = numbers[rand() % 10]; randomizer = rand() % 4; printf("%c", password[i]); } else if (randomizer == 2) { password[i] = symbols[rand() % 8]; randomizer = rand() % 4; printf("%c", password[i]); } else if (randomizer == 3) { password[i] = LETTER[rand() % 26]; randomizer = rand() % 4; printf("%c", password[i]); } else { password[i] = letter[rand() % 26]; randomizer = rand() % 4; printf("%c", password[i]); } }} // Driver Codeint main(){ // Length of the password to // be generated int N = 10; // Function Call randomPasswordGeneration(N); return 0;} 51WAZMT?Z$ Time Complexity: O(N)Auxiliary Space: O(26) cpp-random Technical Scripter 2020 Arrays Strings Technical Scripter Arrays Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Program to find sum of elements in a given array Building Heap from Array Window Sliding Technique Reversal algorithm for array rotation 1's and 2's complement of a Binary Number Longest Common Subsequence | DP-4 Reverse a string in Java Write a program to print all permutations of a given string KMP Algorithm for Pattern Searching C++ Data Types
[ { "code": null, "e": 24431, "s": 24403, "text": "\n20 Jan, 2021" }, { "code": null, "e": 24544, "s": 24431, "text": "In this article, we will discuss how to generate a random password of a given length consists of any characters." }, { "code": null, "e": 24554, "s": 24544, "text": "Approach:" }, { "code": null, "e": 24648, "s": 24554, "text": "The below-given program involves basic concepts like variables, data types, array, loop, etc." }, { "code": null, "e": 24995, "s": 24648, "text": "Follow the below steps to solve this problem:Take the length of the password and declare a character array of that length to store that password.Declare character array of all the capital letters, small letters, numbers, special characters.Now according to the program below, respective if-else gets executed and a random password gets generated." }, { "code": null, "e": 25096, "s": 24995, "text": "Take the length of the password and declare a character array of that length to store that password." }, { "code": null, "e": 25192, "s": 25096, "text": "Declare character array of all the capital letters, small letters, numbers, special characters." }, { "code": null, "e": 25299, "s": 25192, "text": "Now according to the program below, respective if-else gets executed and a random password gets generated." }, { "code": null, "e": 25343, "s": 25299, "text": "Below is the program of the above approach:" }, { "code": null, "e": 25345, "s": 25343, "text": "C" }, { "code": "// C program for the above approach#include <math.h>#include <stdio.h>#include <stdlib.h>#include <time.h> // Function to randomly generates password// of length Nvoid randomPasswordGeneration(int N){ // Initialize counter int i = 0; int randomizer = 0; // Seed the random-number generator // with current time so that the // numbers will be different every time srand((unsigned int)(time(NULL))); // Array of numbers char numbers[] = \"0123456789\"; // Array of small alphabets char letter[] = \"abcdefghijklmnoqprstuvwyzx\"; // Array of capital alphabets char LETTER[] = \"ABCDEFGHIJKLMNOQPRSTUYWVZX\"; // Array of all the special symbols char symbols[] = \"!@#$^&*?\"; // Stores the random password char password[N]; // To select the randomizer // inside the loop randomizer = rand() % 4; // Iterate over the range [0, N] for (i = 0; i < N; i++) { if (randomizer == 1) { password[i] = numbers[rand() % 10]; randomizer = rand() % 4; printf(\"%c\", password[i]); } else if (randomizer == 2) { password[i] = symbols[rand() % 8]; randomizer = rand() % 4; printf(\"%c\", password[i]); } else if (randomizer == 3) { password[i] = LETTER[rand() % 26]; randomizer = rand() % 4; printf(\"%c\", password[i]); } else { password[i] = letter[rand() % 26]; randomizer = rand() % 4; printf(\"%c\", password[i]); } }} // Driver Codeint main(){ // Length of the password to // be generated int N = 10; // Function Call randomPasswordGeneration(N); return 0;}", "e": 27075, "s": 25345, "text": null }, { "code": null, "e": 27087, "s": 27075, "text": "51WAZMT?Z$\n" }, { "code": null, "e": 27131, "s": 27087, "text": "Time Complexity: O(N)Auxiliary Space: O(26)" }, { "code": null, "e": 27142, "s": 27131, "text": "cpp-random" }, { "code": null, "e": 27166, "s": 27142, "text": "Technical Scripter 2020" }, { "code": null, "e": 27173, "s": 27166, "text": "Arrays" }, { "code": null, "e": 27181, "s": 27173, "text": "Strings" }, { "code": null, "e": 27200, "s": 27181, "text": "Technical Scripter" }, { "code": null, "e": 27207, "s": 27200, "text": "Arrays" }, { "code": null, "e": 27215, "s": 27207, "text": "Strings" }, { "code": null, "e": 27313, "s": 27215, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27322, "s": 27313, "text": "Comments" }, { "code": null, "e": 27335, "s": 27322, "text": "Old Comments" }, { "code": null, "e": 27384, "s": 27335, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 27409, "s": 27384, "text": "Building Heap from Array" }, { "code": null, "e": 27434, "s": 27409, "text": "Window Sliding Technique" }, { "code": null, "e": 27472, "s": 27434, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 27514, "s": 27472, "text": "1's and 2's complement of a Binary Number" }, { "code": null, "e": 27548, "s": 27514, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 27573, "s": 27548, "text": "Reverse a string in Java" }, { "code": null, "e": 27633, "s": 27573, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 27669, "s": 27633, "text": "KMP Algorithm for Pattern Searching" } ]
Power BI: Implement AND/OR Selection | by ZhongTr0n | Towards Data Science
Power BI is really growing on me. Using this software everyday, I am amazed by the capabilities of this product and the way it improves month after month by adding new features or optimizing current capabilities. However, like any software solution, there is still room for improvement and a lack of some features that would benefit many users. One of these possible improvements would be enabling the type of multi-selection. In the current setup, Power BI treats multi select like “OR” instead of “AND”. Let me quickly walk you through the difference. The concept of AND/OR is very simple, but for those not familiar I will use a simple example to demonstrate. Let say you have a simple table with students and their language courses like this: French OR English: Student A, B, CFrench AND English: Student A, B The default Power BI behavior is treating this selection as OR. In this article, I will walk you through the setup of having both an AND and OR selection in your own Power BI dashboard. The sample data I created for this demo looks like this: The first table contains basic information about some students, while the other table has multiple rows per student, containing information about the language courses they are taking. The tables are connected on a student ID, in a bidirectional one-to-many relationship. Before we start writing the code you should be familiar with the DAX basics. For those who are not, DAX is a programming language you can use within Power BI to create filtering, calculations, columns and much more. First, we will create a very small table containing the indicators and values we will later use to create an ‘AND/OR’ slicer. It is a 2x2 table which you can add from an external source, or simply create it with this code: ANDOR_Table = DATATABLE( “AND/OR”, STRING, “Binary”, INTEGER, { {“AND”, 0}, {“OR”, 1} } )``` The table should look something like this: Before we start writing a measure, I recently adopted the good practice of placing all your measures in the same table in order to keep things clean. So let’s first create an empty table like this: _Measures = {BLANK()} In this table add the following measure: Selected_AndOr = MAX(ANDOR_Table[Binary]) This measure will indicate whether you select AND or OR selection. You can already add a slicer to the report containing the AND/OR strings as items. Now we have everything for the selection, it’s time to start creating the backend. The next measure we will create is the one that will count how many rows you selected. Selected_counter = IF( ISFILTERED(‘Courses’[Course]), COUNTROWS( ALLSELECTED(‘Courses’[Course]) ), 0) The counter we created in the previous measure will now be used to add an indicator to the table where you want to see the results of your selection, in this case the Student table. The last measure we create is the one that will use the previous measure in order to see if the row satisfies the ‘AND’ criteria. It will return a 0/1 flag. Course_ANDOR_Check = IF( [Selected_counter] = 0, 1, IF( DISTINCTCOUNT(‘Courses’[Course]) = [Selected_counter], 1, _Measures[Selected_AndOr] ) ) Now everything is set up, it’s time to add it to the visual. For each widget you want to get affected by this functionality you should add a filter on the visual level like this: Course_ANDOR_Check IS 1 DONE! There you have it, you can now use the AND/OR slicer to change the functionality as you can see in the video below. This solution is a combination of my own code and snippets I found online. As I am still developing my DAX skills, I am eager to improve this code. So please feel free to leave your comments if you have any questions or ideas to improve this solution. About me: My name is Bruno and I work as a data scientist with Dashmote, an AI technology scale-up headquartered in The Netherlands. Our goal is bridging the gap between images and data thanks to AI-based solutions.Check out my other work on https://www.zhongtron.me.
[ { "code": null, "e": 384, "s": 171, "text": "Power BI is really growing on me. Using this software everyday, I am amazed by the capabilities of this product and the way it improves month after month by adding new features or optimizing current capabilities." }, { "code": null, "e": 725, "s": 384, "text": "However, like any software solution, there is still room for improvement and a lack of some features that would benefit many users. One of these possible improvements would be enabling the type of multi-selection. In the current setup, Power BI treats multi select like “OR” instead of “AND”. Let me quickly walk you through the difference." }, { "code": null, "e": 918, "s": 725, "text": "The concept of AND/OR is very simple, but for those not familiar I will use a simple example to demonstrate. Let say you have a simple table with students and their language courses like this:" }, { "code": null, "e": 985, "s": 918, "text": "French OR English: Student A, B, CFrench AND English: Student A, B" }, { "code": null, "e": 1049, "s": 985, "text": "The default Power BI behavior is treating this selection as OR." }, { "code": null, "e": 1171, "s": 1049, "text": "In this article, I will walk you through the setup of having both an AND and OR selection in your own Power BI dashboard." }, { "code": null, "e": 1228, "s": 1171, "text": "The sample data I created for this demo looks like this:" }, { "code": null, "e": 1499, "s": 1228, "text": "The first table contains basic information about some students, while the other table has multiple rows per student, containing information about the language courses they are taking. The tables are connected on a student ID, in a bidirectional one-to-many relationship." }, { "code": null, "e": 1715, "s": 1499, "text": "Before we start writing the code you should be familiar with the DAX basics. For those who are not, DAX is a programming language you can use within Power BI to create filtering, calculations, columns and much more." }, { "code": null, "e": 1938, "s": 1715, "text": "First, we will create a very small table containing the indicators and values we will later use to create an ‘AND/OR’ slicer. It is a 2x2 table which you can add from an external source, or simply create it with this code:" }, { "code": null, "e": 2063, "s": 1938, "text": "ANDOR_Table = DATATABLE( “AND/OR”, STRING, “Binary”, INTEGER, { {“AND”, 0}, {“OR”, 1} } )```" }, { "code": null, "e": 2106, "s": 2063, "text": "The table should look something like this:" }, { "code": null, "e": 2304, "s": 2106, "text": "Before we start writing a measure, I recently adopted the good practice of placing all your measures in the same table in order to keep things clean. So let’s first create an empty table like this:" }, { "code": null, "e": 2330, "s": 2304, "text": "_Measures = {BLANK()}" }, { "code": null, "e": 2371, "s": 2330, "text": "In this table add the following measure:" }, { "code": null, "e": 2416, "s": 2371, "text": "Selected_AndOr = MAX(ANDOR_Table[Binary]) " }, { "code": null, "e": 2566, "s": 2416, "text": "This measure will indicate whether you select AND or OR selection. You can already add a slicer to the report containing the AND/OR strings as items." }, { "code": null, "e": 2736, "s": 2566, "text": "Now we have everything for the selection, it’s time to start creating the backend. The next measure we will create is the one that will count how many rows you selected." }, { "code": null, "e": 2881, "s": 2736, "text": "Selected_counter = IF( ISFILTERED(‘Courses’[Course]), COUNTROWS( ALLSELECTED(‘Courses’[Course]) ), 0)" }, { "code": null, "e": 3063, "s": 2881, "text": "The counter we created in the previous measure will now be used to add an indicator to the table where you want to see the results of your selection, in this case the Student table." }, { "code": null, "e": 3220, "s": 3063, "text": "The last measure we create is the one that will use the previous measure in order to see if the row satisfies the ‘AND’ criteria. It will return a 0/1 flag." }, { "code": null, "e": 3430, "s": 3220, "text": "Course_ANDOR_Check = IF( [Selected_counter] = 0, 1, IF( DISTINCTCOUNT(‘Courses’[Course]) = [Selected_counter], 1, _Measures[Selected_AndOr] ) )" }, { "code": null, "e": 3633, "s": 3430, "text": "Now everything is set up, it’s time to add it to the visual. For each widget you want to get affected by this functionality you should add a filter on the visual level like this: Course_ANDOR_Check IS 1" }, { "code": null, "e": 3755, "s": 3633, "text": "DONE! There you have it, you can now use the AND/OR slicer to change the functionality as you can see in the video below." }, { "code": null, "e": 4007, "s": 3755, "text": "This solution is a combination of my own code and snippets I found online. As I am still developing my DAX skills, I am eager to improve this code. So please feel free to leave your comments if you have any questions or ideas to improve this solution." } ]
Apache Presto - Configuration Settings
This chapter will discuss the configuration settings for Presto. The Presto Verifier can be used to test Presto against another database (such as MySQL), or to test two Presto clusters against each other. Open MySQL server and create a database using the following command. create database test Now you have created “test” database in the server. Create the table and load it with the following query. CREATE TABLE verifier_queries( id INT NOT NULL AUTO_INCREMENT, suite VARCHAR(256) NOT NULL, name VARCHAR(256), test_catalog VARCHAR(256) NOT NULL, test_schema VARCHAR(256) NOT NULL, test_prequeries TEXT, test_query TEXT NOT NULL, test_postqueries TEXT, test_username VARCHAR(256) NOT NULL default 'verifier-test', test_password VARCHAR(256), control_catalog VARCHAR(256) NOT NULL, control_schema VARCHAR(256) NOT NULL, control_prequeries TEXT, control_query TEXT NOT NULL, control_postqueries TEXT, control_username VARCHAR(256) NOT NULL default 'verifier-test', control_password VARCHAR(256), session_properties_json TEXT, PRIMARY KEY (id) ); Create a properties file to configure the verifier − $ vi config.properties suite = mysuite query-database = jdbc:mysql://localhost:3306/tutorials?user=root&password=pwd control.gateway = jdbc:presto://localhost:8080 test.gateway = jdbc:presto://localhost:8080 thread-count = 1 Here, in the query-database field, enter the following details − mysql database name, user name, and password. Download Presto-verifier jar file by visiting the following link, https://repo1.maven.org/maven2/com/facebook/presto/presto-verifier/0.149/ Now the version “presto-verifier-0.149-executable.jar” is downloaded on your machine. Execute the JAR file using the following command, $ mv presto-verifier-0.149-executable.jar verifier $ chmod+x verifier Run the verifier using the following command, $ ./verifier config.properties Let’s create a simple table in “test” database using the following query. create table product(id int not null, name varchar(50)) After creating a table, insert two records using the following query, insert into product values(1,’Phone') insert into product values(2,’Television’) Execute the following sample query in the verifier terminal (./verifier config.propeties) to check the verifier result. insert into verifier_queries (suite, test_catalog, test_schema, test_query, control_catalog, control_schema, control_query) values ('mysuite', 'mysql', 'default', 'select * from mysql.test.product', 'mysql', 'default', 'select * from mysql.test.product'); Here, select * from mysql.test.product query refers to mysql catalog, test is database name and product is table name. In this way, you can access mysql connector using Presto server. Here, two same select queries are tested against each other to see the performance. Similarly, you can run other queries to test the performance results. You can also connect two Presto clusters to check the performance results. 46 Lectures 3.5 hours Arnab Chakraborty 23 Lectures 1.5 hours Mukund Kumar Mishra 16 Lectures 1 hours Nilay Mehta 52 Lectures 1.5 hours Bigdata Engineer 14 Lectures 1 hours Bigdata Engineer 23 Lectures 1 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 2071, "s": 2006, "text": "This chapter will discuss the configuration settings for Presto." }, { "code": null, "e": 2211, "s": 2071, "text": "The Presto Verifier can be used to test Presto against another database (such as MySQL), or to test two Presto clusters against each other." }, { "code": null, "e": 2280, "s": 2211, "text": "Open MySQL server and create a database using the following command." }, { "code": null, "e": 2302, "s": 2280, "text": "create database test " }, { "code": null, "e": 2409, "s": 2302, "text": "Now you have created “test” database in the server. Create the table and load it with the following query." }, { "code": null, "e": 3141, "s": 2409, "text": "CREATE TABLE verifier_queries( \n id INT NOT NULL AUTO_INCREMENT, \n suite VARCHAR(256) NOT NULL, \n name VARCHAR(256), \n test_catalog VARCHAR(256) NOT NULL, \n test_schema VARCHAR(256) NOT NULL, \n test_prequeries TEXT, \n test_query TEXT NOT NULL, \n test_postqueries TEXT, \n test_username VARCHAR(256) NOT NULL default 'verifier-test', \n test_password VARCHAR(256), \n control_catalog VARCHAR(256) NOT NULL, \n control_schema VARCHAR(256) NOT NULL, \n control_prequeries TEXT, \n control_query TEXT NOT NULL, \n control_postqueries TEXT, \n control_username VARCHAR(256) NOT NULL default 'verifier-test', \n control_password VARCHAR(256), \n session_properties_json TEXT, \n PRIMARY KEY (id) \n);" }, { "code": null, "e": 3194, "s": 3141, "text": "Create a properties file to configure the verifier −" }, { "code": null, "e": 3428, "s": 3194, "text": "$ vi config.properties \n\nsuite = mysuite \nquery-database = jdbc:mysql://localhost:3306/tutorials?user=root&password=pwd \ncontrol.gateway = jdbc:presto://localhost:8080 \ntest.gateway = jdbc:presto://localhost:8080 \nthread-count = 1 \n" }, { "code": null, "e": 3539, "s": 3428, "text": "Here, in the query-database field, enter the following details − mysql database name, user name, and password." }, { "code": null, "e": 3605, "s": 3539, "text": "Download Presto-verifier jar file by visiting the following link," }, { "code": null, "e": 3679, "s": 3605, "text": "https://repo1.maven.org/maven2/com/facebook/presto/presto-verifier/0.149/" }, { "code": null, "e": 3765, "s": 3679, "text": "Now the version “presto-verifier-0.149-executable.jar” is downloaded on your machine." }, { "code": null, "e": 3815, "s": 3765, "text": "Execute the JAR file using the following command," }, { "code": null, "e": 3889, "s": 3815, "text": "$ mv presto-verifier-0.149-executable.jar verifier \n$ chmod+x verifier \n" }, { "code": null, "e": 3935, "s": 3889, "text": "Run the verifier using the following command," }, { "code": null, "e": 3968, "s": 3935, "text": "$ ./verifier config.properties \n" }, { "code": null, "e": 4042, "s": 3968, "text": "Let’s create a simple table in “test” database using the following query." }, { "code": null, "e": 4098, "s": 4042, "text": "create table product(id int not null, name varchar(50))" }, { "code": null, "e": 4168, "s": 4098, "text": "After creating a table, insert two records using the following query," }, { "code": null, "e": 4250, "s": 4168, "text": "insert into product values(1,’Phone') \ninsert into product values(2,’Television’)" }, { "code": null, "e": 4370, "s": 4250, "text": "Execute the following sample query in the verifier terminal (./verifier config.propeties) to check the verifier result." }, { "code": null, "e": 4629, "s": 4370, "text": "insert into verifier_queries (suite, test_catalog, test_schema, test_query, \ncontrol_catalog, control_schema, control_query) values \n('mysuite', 'mysql', 'default', 'select * from mysql.test.product', \n'mysql', 'default', 'select * from mysql.test.product');" }, { "code": null, "e": 4814, "s": 4629, "text": "Here, select * from mysql.test.product query refers to mysql catalog, test is database name and product is table name. In this way, you can access mysql connector using Presto server." }, { "code": null, "e": 5043, "s": 4814, "text": "Here, two same select queries are tested against each other to see the performance. Similarly, you can run other queries to test the performance results. You can also connect two Presto clusters to check the performance results." }, { "code": null, "e": 5078, "s": 5043, "text": "\n 46 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5097, "s": 5078, "text": " Arnab Chakraborty" }, { "code": null, "e": 5132, "s": 5097, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5153, "s": 5132, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 5186, "s": 5153, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 5199, "s": 5186, "text": " Nilay Mehta" }, { "code": null, "e": 5234, "s": 5199, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5252, "s": 5234, "text": " Bigdata Engineer" }, { "code": null, "e": 5285, "s": 5252, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 5303, "s": 5285, "text": " Bigdata Engineer" }, { "code": null, "e": 5336, "s": 5303, "text": "\n 23 Lectures \n 1 hours \n" }, { "code": null, "e": 5354, "s": 5336, "text": " Bigdata Engineer" }, { "code": null, "e": 5361, "s": 5354, "text": " Print" }, { "code": null, "e": 5372, "s": 5361, "text": " Add Notes" } ]
Operating System - Quick Guide
An Operating System (OS) is an interface between a computer user and computer hardware. An operating system is a software which performs all the basic tasks like file management, memory management, process management, handling input and output, and controlling peripheral devices such as disk drives and printers. Some popular Operating Systems include Linux Operating System, Windows Operating System, VMS, OS/400, AIX, z/OS, etc. An operating system is a program that acts as an interface between the user and the computer hardware and controls the execution of all kinds of programs. Following are some of important functions of an operating System. Memory Management Processor Management Device Management File Management Security Control over system performance Job accounting Error detecting aids Coordination between other software and users Memory management refers to management of Primary Memory or Main Memory. Main memory is a large array of words or bytes where each word or byte has its own address. Main memory provides a fast storage that can be accessed directly by the CPU. For a program to be executed, it must in the main memory. An Operating System does the following activities for memory management − Keeps tracks of primary memory, i.e., what part of it are in use by whom, what part are not in use. Keeps tracks of primary memory, i.e., what part of it are in use by whom, what part are not in use. In multiprogramming, the OS decides which process will get memory when and how much. In multiprogramming, the OS decides which process will get memory when and how much. Allocates the memory when a process requests it to do so. Allocates the memory when a process requests it to do so. De-allocates the memory when a process no longer needs it or has been terminated. De-allocates the memory when a process no longer needs it or has been terminated. In multiprogramming environment, the OS decides which process gets the processor when and for how much time. This function is called process scheduling. An Operating System does the following activities for processor management − Keeps tracks of processor and status of process. The program responsible for this task is known as traffic controller. Keeps tracks of processor and status of process. The program responsible for this task is known as traffic controller. Allocates the processor (CPU) to a process. Allocates the processor (CPU) to a process. De-allocates processor when a process is no longer required. De-allocates processor when a process is no longer required. An Operating System manages device communication via their respective drivers. It does the following activities for device management − Keeps tracks of all devices. Program responsible for this task is known as the I/O controller. Keeps tracks of all devices. Program responsible for this task is known as the I/O controller. Decides which process gets the device when and for how much time. Decides which process gets the device when and for how much time. Allocates the device in the efficient way. Allocates the device in the efficient way. De-allocates devices. De-allocates devices. A file system is normally organized into directories for easy navigation and usage. These directories may contain files and other directions. An Operating System does the following activities for file management − Keeps track of information, location, uses, status etc. The collective facilities are often known as file system. Keeps track of information, location, uses, status etc. The collective facilities are often known as file system. Decides who gets the resources. Decides who gets the resources. Allocates the resources. Allocates the resources. De-allocates the resources. De-allocates the resources. Following are some of the important activities that an Operating System performs − Security − By means of password and similar other techniques, it prevents unauthorized access to programs and data. Security − By means of password and similar other techniques, it prevents unauthorized access to programs and data. Control over system performance − Recording delays between request for a service and response from the system. Control over system performance − Recording delays between request for a service and response from the system. Job accounting − Keeping track of time and resources used by various jobs and users. Job accounting − Keeping track of time and resources used by various jobs and users. Error detecting aids − Production of dumps, traces, error messages, and other debugging and error detecting aids. Error detecting aids − Production of dumps, traces, error messages, and other debugging and error detecting aids. Coordination between other softwares and users − Coordination and assignment of compilers, interpreters, assemblers and other software to the various users of the computer systems. Coordination between other softwares and users − Coordination and assignment of compilers, interpreters, assemblers and other software to the various users of the computer systems. Operating systems are there from the very first computer generation and they keep evolving with time. In this chapter, we will discuss some of the important types of operating systems which are most commonly used. The users of a batch operating system do not interact with the computer directly. Each user prepares his job on an off-line device like punch cards and submits it to the computer operator. To speed up processing, jobs with similar needs are batched together and run as a group. The programmers leave their programs with the operator and the operator then sorts the programs with similar requirements into batches. The problems with Batch Systems are as follows − Lack of interaction between the user and the job. CPU is often idle, because the speed of the mechanical I/O devices is slower than the CPU. Difficult to provide the desired priority. Time-sharing is a technique which enables many people, located at various terminals, to use a particular computer system at the same time. Time-sharing or multitasking is a logical extension of multiprogramming. Processor's time which is shared among multiple users simultaneously is termed as time-sharing. The main difference between Multiprogrammed Batch Systems and Time-Sharing Systems is that in case of Multiprogrammed batch systems, the objective is to maximize processor use, whereas in Time-Sharing Systems, the objective is to minimize response time. Multiple jobs are executed by the CPU by switching between them, but the switches occur so frequently. Thus, the user can receive an immediate response. For example, in a transaction processing, the processor executes each user program in a short burst or quantum of computation. That is, if n users are present, then each user can get a time quantum. When the user submits the command, the response time is in few seconds at most. The operating system uses CPU scheduling and multiprogramming to provide each user with a small portion of a time. Computer systems that were designed primarily as batch systems have been modified to time-sharing systems. Advantages of Timesharing operating systems are as follows − Provides the advantage of quick response. Avoids duplication of software. Reduces CPU idle time. Disadvantages of Time-sharing operating systems are as follows − Problem of reliability. Question of security and integrity of user programs and data. Problem of data communication. Distributed systems use multiple central processors to serve multiple real-time applications and multiple users. Data processing jobs are distributed among the processors accordingly. The processors communicate with one another through various communication lines (such as high-speed buses or telephone lines). These are referred as loosely coupled systems or distributed systems. Processors in a distributed system may vary in size and function. These processors are referred as sites, nodes, computers, and so on. The advantages of distributed systems are as follows − With resource sharing facility, a user at one site may be able to use the resources available at another. Speedup the exchange of data with one another via electronic mail. If one site fails in a distributed system, the remaining sites can potentially continue operating. Better service to the customers. Reduction of the load on the host computer. Reduction of delays in data processing. A Network Operating System runs on a server and provides the server the capability to manage data, users, groups, security, applications, and other networking functions. The primary purpose of the network operating system is to allow shared file and printer access among multiple computers in a network, typically a local area network (LAN), a private network or to other networks. Examples of network operating systems include Microsoft Windows Server 2003, Microsoft Windows Server 2008, UNIX, Linux, Mac OS X, Novell NetWare, and BSD. The advantages of network operating systems are as follows − Centralized servers are highly stable. Security is server managed. Upgrades to new technologies and hardware can be easily integrated into the system. Remote access to servers is possible from different locations and types of systems. The disadvantages of network operating systems are as follows − High cost of buying and running a server. Dependency on a central location for most operations. Regular maintenance and updates are required. A real-time system is defined as a data processing system in which the time interval required to process and respond to inputs is so small that it controls the environment. The time taken by the system to respond to an input and display of required updated information is termed as the response time. So in this method, the response time is very less as compared to online processing. Real-time systems are used when there are rigid time requirements on the operation of a processor or the flow of data and real-time systems can be used as a control device in a dedicated application. A real-time operating system must have well-defined, fixed time constraints, otherwise the system will fail. For example, Scientific experiments, medical imaging systems, industrial control systems, weapon systems, robots, air traffic control systems, etc. There are two types of real-time operating systems. Hard real-time systems guarantee that critical tasks complete on time. In hard real-time systems, secondary storage is limited or missing and the data is stored in ROM. In these systems, virtual memory is almost never found. Soft real-time systems are less restrictive. A critical real-time task gets priority over other tasks and retains the priority until it completes. Soft real-time systems have limited utility than hard real-time systems. For example, multimedia, virtual reality, Advanced Scientific Projects like undersea exploration and planetary rovers, etc. An Operating System provides services to both the users and to the programs. It provides programs an environment to execute. It provides users the services to execute the programs in a convenient manner. Following are a few common services provided by an operating system − Program execution I/O operations File System manipulation Communication Error Detection Resource Allocation Protection Operating systems handle many kinds of activities from user programs to system programs like printer spooler, name servers, file server, etc. Each of these activities is encapsulated as a process. A process includes the complete execution context (code to execute, data to manipulate, registers, OS resources in use). Following are the major activities of an operating system with respect to program management − Loads a program into memory. Executes the program. Handles program's execution. Provides a mechanism for process synchronization. Provides a mechanism for process communication. Provides a mechanism for deadlock handling. An I/O subsystem comprises of I/O devices and their corresponding driver software. Drivers hide the peculiarities of specific hardware devices from the users. An Operating System manages the communication between user and device drivers. I/O operation means read or write operation with any file or any specific I/O device. Operating system provides the access to the required I/O device when required. A file represents a collection of related information. Computers can store files on the disk (secondary storage), for long-term storage purpose. Examples of storage media include magnetic tape, magnetic disk and optical disk drives like CD, DVD. Each of these media has its own properties like speed, capacity, data transfer rate and data access methods. A file system is normally organized into directories for easy navigation and usage. These directories may contain files and other directions. Following are the major activities of an operating system with respect to file management − Program needs to read a file or write a file. The operating system gives the permission to the program for operation on file. Permission varies from read-only, read-write, denied and so on. Operating System provides an interface to the user to create/delete files. Operating System provides an interface to the user to create/delete directories. Operating System provides an interface to create the backup of file system. In case of distributed systems which are a collection of processors that do not share memory, peripheral devices, or a clock, the operating system manages communications between all the processes. Multiple processes communicate with one another through communication lines in the network. The OS handles routing and connection strategies, and the problems of contention and security. Following are the major activities of an operating system with respect to communication − Two processes often require data to be transferred between them Both the processes can be on one computer or on different computers, but are connected through a computer network. Communication may be implemented by two methods, either by Shared Memory or by Message Passing. Errors can occur anytime and anywhere. An error may occur in CPU, in I/O devices or in the memory hardware. Following are the major activities of an operating system with respect to error handling − The OS constantly checks for possible errors. The OS takes an appropriate action to ensure correct and consistent computing. In case of multi-user or multi-tasking environment, resources such as main memory, CPU cycles and files storage are to be allocated to each user or job. Following are the major activities of an operating system with respect to resource management − The OS manages all kinds of resources using schedulers. CPU scheduling algorithms are used for better utilization of CPU. Considering a computer system having multiple users and concurrent execution of multiple processes, the various processes must be protected from each other's activities. Protection refers to a mechanism or a way to control the access of programs, processes, or users to the resources defined by a computer system. Following are the major activities of an operating system with respect to protection − The OS ensures that all access to system resources is controlled. The OS ensures that external I/O devices are protected from invalid access attempts. The OS provides authentication features for each user by means of passwords. Batch processing is a technique in which an Operating System collects the programs and data together in a batch before processing starts. An operating system does the following activities related to batch processing − The OS defines a job which has predefined sequence of commands, programs and data as a single unit. The OS defines a job which has predefined sequence of commands, programs and data as a single unit. The OS keeps a number a jobs in memory and executes them without any manual information. The OS keeps a number a jobs in memory and executes them without any manual information. Jobs are processed in the order of submission, i.e., first come first served fashion. Jobs are processed in the order of submission, i.e., first come first served fashion. When a job completes its execution, its memory is released and the output for the job gets copied into an output spool for later printing or processing. When a job completes its execution, its memory is released and the output for the job gets copied into an output spool for later printing or processing. Batch processing takes much of the work of the operator to the computer. Batch processing takes much of the work of the operator to the computer. Increased performance as a new job get started as soon as the previous job is finished, without any manual intervention. Increased performance as a new job get started as soon as the previous job is finished, without any manual intervention. Difficult to debug program. A job could enter an infinite loop. Due to lack of protection scheme, one batch job can affect pending jobs. Multitasking is when multiple jobs are executed by the CPU simultaneously by switching between them. Switches occur so frequently that the users may interact with each program while it is running. An OS does the following activities related to multitasking − The user gives instructions to the operating system or to a program directly, and receives an immediate response. The user gives instructions to the operating system or to a program directly, and receives an immediate response. The OS handles multitasking in the way that it can handle multiple operations/executes multiple programs at a time. The OS handles multitasking in the way that it can handle multiple operations/executes multiple programs at a time. Multitasking Operating Systems are also known as Time-sharing systems. Multitasking Operating Systems are also known as Time-sharing systems. These Operating Systems were developed to provide interactive use of a computer system at a reasonable cost. These Operating Systems were developed to provide interactive use of a computer system at a reasonable cost. A time-shared operating system uses the concept of CPU scheduling and multiprogramming to provide each user with a small portion of a time-shared CPU. A time-shared operating system uses the concept of CPU scheduling and multiprogramming to provide each user with a small portion of a time-shared CPU. Each user has at least one separate program in memory. Each user has at least one separate program in memory. A program that is loaded into memory and is executing is commonly referred to as a process. A program that is loaded into memory and is executing is commonly referred to as a process. When a process executes, it typically executes for only a very short time before it either finishes or needs to perform I/O. When a process executes, it typically executes for only a very short time before it either finishes or needs to perform I/O. Since interactive I/O typically runs at slower speeds, it may take a long time to complete. During this time, a CPU can be utilized by another process. Since interactive I/O typically runs at slower speeds, it may take a long time to complete. During this time, a CPU can be utilized by another process. The operating system allows the users to share the computer simultaneously. Since each action or command in a time-shared system tends to be short, only a little CPU time is needed for each user. The operating system allows the users to share the computer simultaneously. Since each action or command in a time-shared system tends to be short, only a little CPU time is needed for each user. As the system switches CPU rapidly from one user/program to the next, each user is given the impression that he/she has his/her own CPU, whereas actually one CPU is being shared among many users. As the system switches CPU rapidly from one user/program to the next, each user is given the impression that he/she has his/her own CPU, whereas actually one CPU is being shared among many users. Sharing the processor, when two or more programs reside in memory at the same time, is referred as multiprogramming. Multiprogramming assumes a single shared processor. Multiprogramming increases CPU utilization by organizing jobs so that the CPU always has one to execute. The following figure shows the memory layout for a multiprogramming system. An OS does the following activities related to multiprogramming. The operating system keeps several jobs in memory at a time. The operating system keeps several jobs in memory at a time. This set of jobs is a subset of the jobs kept in the job pool. This set of jobs is a subset of the jobs kept in the job pool. The operating system picks and begins to execute one of the jobs in the memory. The operating system picks and begins to execute one of the jobs in the memory. Multiprogramming operating systems monitor the state of all active programs and system resources using memory management programs to ensures that the CPU is never idle, unless there are no jobs to process. Multiprogramming operating systems monitor the state of all active programs and system resources using memory management programs to ensures that the CPU is never idle, unless there are no jobs to process. High and efficient CPU utilization. User feels that many programs are allotted CPU almost simultaneously. CPU scheduling is required. To accommodate many jobs in memory, memory management is required. Interactivity refers to the ability of users to interact with a computer system. An Operating system does the following activities related to interactivity − Provides the user an interface to interact with the system. Manages input devices to take inputs from the user. For example, keyboard. Manages output devices to show outputs to the user. For example, Monitor. The response time of the OS needs to be short, since the user submits and waits for the result. Real-time systems are usually dedicated, embedded systems. An operating system does the following activities related to real-time system activity. In such systems, Operating Systems typically read from and react to sensor data. The Operating system must guarantee response to events within fixed periods of time to ensure correct performance. A distributed environment refers to multiple independent CPUs or processors in a computer system. An operating system does the following activities related to distributed environment − The OS distributes computation logics among several physical processors. The OS distributes computation logics among several physical processors. The processors do not share memory or a clock. Instead, each processor has its own local memory. The processors do not share memory or a clock. Instead, each processor has its own local memory. The OS manages the communications between the processors. They communicate with each other through various communication lines. The OS manages the communications between the processors. They communicate with each other through various communication lines. Spooling is an acronym for simultaneous peripheral operations on line. Spooling refers to putting data of various I/O jobs in a buffer. This buffer is a special area in memory or hard disk which is accessible to I/O devices. An operating system does the following activities related to distributed environment − Handles I/O device data spooling as devices have different data access rates. Handles I/O device data spooling as devices have different data access rates. Maintains the spooling buffer which provides a waiting station where data can rest while the slower device catches up. Maintains the spooling buffer which provides a waiting station where data can rest while the slower device catches up. Maintains parallel computation because of spooling process as a computer can perform I/O in parallel fashion. It becomes possible to have the computer read data from a tape, write data to disk and to write out to a tape printer while it is doing its computing task. Maintains parallel computation because of spooling process as a computer can perform I/O in parallel fashion. It becomes possible to have the computer read data from a tape, write data to disk and to write out to a tape printer while it is doing its computing task. The spooling operation uses a disk as a very large buffer. Spooling is capable of overlapping I/O operation for one job with processor operations for another job. A process is basically a program in execution. The execution of a process must progress in a sequential fashion. To put it in simple terms, we write our computer programs in a text file and when we execute this program, it becomes a process which performs all the tasks mentioned in the program. When a program is loaded into the memory and it becomes a process, it can be divided into four sections ─ stack, heap, text and data. The following image shows a simplified layout of a process inside main memory − Stack The process Stack contains the temporary data such as method/function parameters, return address and local variables. Heap This is dynamically allocated memory to a process during its run time. Text This includes the current activity represented by the value of Program Counter and the contents of the processor's registers. Data This section contains the global and static variables. A program is a piece of code which may be a single line or millions of lines. A computer program is usually written by a computer programmer in a programming language. For example, here is a simple program written in C programming language − #include <stdio.h> int main() { printf("Hello, World! \n"); return 0; } A computer program is a collection of instructions that performs a specific task when executed by a computer. When we compare a program with a process, we can conclude that a process is a dynamic instance of a computer program. A part of a computer program that performs a well-defined task is known as an algorithm. A collection of computer programs, libraries and related data are referred to as a software. When a process executes, it passes through different states. These stages may differ in different operating systems, and the names of these states are also not standardized. In general, a process can have one of the following five states at a time. Start This is the initial state when a process is first started/created. Ready The process is waiting to be assigned to a processor. Ready processes are waiting to have the processor allocated to them by the operating system so that they can run. Process may come into this state after Start state or while running it by but interrupted by the scheduler to assign CPU to some other process. Running Once the process has been assigned to a processor by the OS scheduler, the process state is set to running and the processor executes its instructions. Waiting Process moves into the waiting state if it needs to wait for a resource, such as waiting for user input, or waiting for a file to become available. Terminated or Exit Once the process finishes its execution, or it is terminated by the operating system, it is moved to the terminated state where it waits to be removed from main memory. A Process Control Block is a data structure maintained by the Operating System for every process. The PCB is identified by an integer process ID (PID). A PCB keeps all the information needed to keep track of a process as listed below in the table − Process State The current state of the process i.e., whether it is ready, running, waiting, or whatever. Process privileges This is required to allow/disallow access to system resources. Process ID Unique identification for each of the process in the operating system. Pointer A pointer to parent process. Program Counter Program Counter is a pointer to the address of the next instruction to be executed for this process. CPU registers Various CPU registers where process need to be stored for execution for running state. CPU Scheduling Information Process priority and other scheduling information which is required to schedule the process. Memory management information This includes the information of page table, memory limits, Segment table depending on memory used by the operating system. Accounting information This includes the amount of CPU used for process execution, time limits, execution ID etc. IO status information This includes a list of I/O devices allocated to the process. The architecture of a PCB is completely dependent on Operating System and may contain different information in different operating systems. Here is a simplified diagram of a PCB − The PCB is maintained for a process throughout its lifetime, and is deleted once the process terminates. The process scheduling is the activity of the process manager that handles the removal of the running process from the CPU and the selection of another process on the basis of a particular strategy. Process scheduling is an essential part of a Multiprogramming operating systems. Such operating systems allow more than one process to be loaded into the executable memory at a time and the loaded process shares the CPU using time multiplexing. The OS maintains all PCBs in Process Scheduling Queues. The OS maintains a separate queue for each of the process states and PCBs of all processes in the same execution state are placed in the same queue. When the state of a process is changed, its PCB is unlinked from its current queue and moved to its new state queue. The Operating System maintains the following important process scheduling queues − Job queue − This queue keeps all the processes in the system. Job queue − This queue keeps all the processes in the system. Ready queue − This queue keeps a set of all processes residing in main memory, ready and waiting to execute. A new process is always put in this queue. Ready queue − This queue keeps a set of all processes residing in main memory, ready and waiting to execute. A new process is always put in this queue. Device queues − The processes which are blocked due to unavailability of an I/O device constitute this queue. Device queues − The processes which are blocked due to unavailability of an I/O device constitute this queue. The OS can use different policies to manage each queue (FIFO, Round Robin, Priority, etc.). The OS scheduler determines how to move processes between the ready and run queues which can only have one entry per processor core on the system; in the above diagram, it has been merged with the CPU. Two-state process model refers to running and non-running states which are described below − Running When a new process is created, it enters into the system as in the running state. Not Running Processes that are not running are kept in queue, waiting for their turn to execute. Each entry in the queue is a pointer to a particular process. Queue is implemented by using linked list. Use of dispatcher is as follows. When a process is interrupted, that process is transferred in the waiting queue. If the process has completed or aborted, the process is discarded. In either case, the dispatcher then selects a process from the queue to execute. Schedulers are special system software which handle process scheduling in various ways. Their main task is to select the jobs to be submitted into the system and to decide which process to run. Schedulers are of three types − Long-Term Scheduler Short-Term Scheduler Medium-Term Scheduler It is also called a job scheduler. A long-term scheduler determines which programs are admitted to the system for processing. It selects processes from the queue and loads them into memory for execution. Process loads into the memory for CPU scheduling. The primary objective of the job scheduler is to provide a balanced mix of jobs, such as I/O bound and processor bound. It also controls the degree of multiprogramming. If the degree of multiprogramming is stable, then the average rate of process creation must be equal to the average departure rate of processes leaving the system. On some systems, the long-term scheduler may not be available or minimal. Time-sharing operating systems have no long term scheduler. When a process changes the state from new to ready, then there is use of long-term scheduler. It is also called as CPU scheduler. Its main objective is to increase system performance in accordance with the chosen set of criteria. It is the change of ready state to running state of the process. CPU scheduler selects a process among the processes that are ready to execute and allocates CPU to one of them. Short-term schedulers, also known as dispatchers, make the decision of which process to execute next. Short-term schedulers are faster than long-term schedulers. Medium-term scheduling is a part of swapping. It removes the processes from the memory. It reduces the degree of multiprogramming. The medium-term scheduler is in-charge of handling the swapped out-processes. A running process may become suspended if it makes an I/O request. A suspended processes cannot make any progress towards completion. In this condition, to remove the process from memory and make space for other processes, the suspended process is moved to the secondary storage. This process is called swapping, and the process is said to be swapped out or rolled out. Swapping may be necessary to improve the process mix. A context switch is the mechanism to store and restore the state or context of a CPU in Process Control block so that a process execution can be resumed from the same point at a later time. Using this technique, a context switcher enables multiple processes to share a single CPU. Context switching is an essential part of a multitasking operating system features. When the scheduler switches the CPU from executing one process to execute another, the state from the current running process is stored into the process control block. After this, the state for the process to run next is loaded from its own PCB and used to set the PC, registers, etc. At that point, the second process can start executing. Context switches are computationally intensive since register and memory state must be saved and restored. To avoid the amount of context switching time, some hardware systems employ two or more sets of processor registers. When the process is switched, the following information is stored for later use. Program Counter Scheduling information Base and limit register value Currently used register Changed State I/O State information Accounting information A Process Scheduler schedules different processes to be assigned to the CPU based on particular scheduling algorithms. There are six popular process scheduling algorithms which we are going to discuss in this chapter − First-Come, First-Served (FCFS) Scheduling Shortest-Job-Next (SJN) Scheduling Priority Scheduling Shortest Remaining Time Round Robin(RR) Scheduling Multiple-Level Queues Scheduling These algorithms are either non-preemptive or preemptive. Non-preemptive algorithms are designed so that once a process enters the running state, it cannot be preempted until it completes its allotted time, whereas the preemptive scheduling is based on priority where a scheduler may preempt a low priority running process anytime when a high priority process enters into a ready state. Jobs are executed on first come, first serve basis. It is a non-preemptive, pre-emptive scheduling algorithm. Easy to understand and implement. Its implementation is based on FIFO queue. Poor in performance as average wait time is high. Wait time of each process is as follows − Average Wait Time: (0+4+6+13) / 4 = 5.75 This is also known as shortest job first, or SJF This is also known as shortest job first, or SJF This is a non-preemptive, pre-emptive scheduling algorithm. This is a non-preemptive, pre-emptive scheduling algorithm. Best approach to minimize waiting time. Best approach to minimize waiting time. Easy to implement in Batch systems where required CPU time is known in advance. Easy to implement in Batch systems where required CPU time is known in advance. Impossible to implement in interactive systems where required CPU time is not known. Impossible to implement in interactive systems where required CPU time is not known. The processer should know in advance how much time process will take. The processer should know in advance how much time process will take. Given: Table of processes, and their Arrival time, Execution time Waiting time of each process is as follows − Average Wait Time: (0 + 4 + 12 + 5)/4 = 21 / 4 = 5.25 Priority scheduling is a non-preemptive algorithm and one of the most common scheduling algorithms in batch systems. Priority scheduling is a non-preemptive algorithm and one of the most common scheduling algorithms in batch systems. Each process is assigned a priority. Process with highest priority is to be executed first and so on. Each process is assigned a priority. Process with highest priority is to be executed first and so on. Processes with same priority are executed on first come first served basis. Processes with same priority are executed on first come first served basis. Priority can be decided based on memory requirements, time requirements or any other resource requirement. Priority can be decided based on memory requirements, time requirements or any other resource requirement. Given: Table of processes, and their Arrival time, Execution time, and priority. Here we are considering 1 is the lowest priority. Waiting time of each process is as follows − Average Wait Time: (0 + 10 + 12 + 2)/4 = 24 / 4 = 6 Shortest remaining time (SRT) is the preemptive version of the SJN algorithm. Shortest remaining time (SRT) is the preemptive version of the SJN algorithm. The processor is allocated to the job closest to completion but it can be preempted by a newer ready job with shorter time to completion. The processor is allocated to the job closest to completion but it can be preempted by a newer ready job with shorter time to completion. Impossible to implement in interactive systems where required CPU time is not known. Impossible to implement in interactive systems where required CPU time is not known. It is often used in batch environments where short jobs need to give preference. It is often used in batch environments where short jobs need to give preference. Round Robin is the preemptive process scheduling algorithm. Round Robin is the preemptive process scheduling algorithm. Each process is provided a fix time to execute, it is called a quantum. Each process is provided a fix time to execute, it is called a quantum. Once a process is executed for a given time period, it is preempted and other process executes for a given time period. Once a process is executed for a given time period, it is preempted and other process executes for a given time period. Context switching is used to save states of preempted processes. Context switching is used to save states of preempted processes. Wait time of each process is as follows − Average Wait Time: (9+2+12+11) / 4 = 8.5 Multiple-level queues are not an independent scheduling algorithm. They make use of other existing algorithms to group and schedule jobs with common characteristics. Multiple queues are maintained for processes with common characteristics. Each queue can have its own scheduling algorithms. Priorities are assigned to each queue. For example, CPU-bound jobs can be scheduled in one queue and all I/O-bound jobs in another queue. The Process Scheduler then alternately selects jobs from each queue and assigns them to the CPU based on the algorithm assigned to the queue. A thread is a flow of execution through the process code, with its own program counter that keeps track of which instruction to execute next, system registers which hold its current working variables, and a stack which contains the execution history. A thread shares with its peer threads few information like code segment, data segment and open files. When one thread alters a code segment memory item, all other threads see that. A thread is also called a lightweight process. Threads provide a way to improve application performance through parallelism. Threads represent a software approach to improving performance of operating system by reducing the overhead thread is equivalent to a classical process. Each thread belongs to exactly one process and no thread can exist outside a process. Each thread represents a separate flow of control. Threads have been successfully used in implementing network servers and web server. They also provide a suitable foundation for parallel execution of applications on shared memory multiprocessors. The following figure shows the working of a single-threaded and a multithreaded process. Threads minimize the context switching time. Use of threads provides concurrency within a process. Efficient communication. It is more economical to create and context switch threads. Threads allow utilization of multiprocessor architectures to a greater scale and efficiency. Threads are implemented in following two ways − User Level Threads − User managed threads. User Level Threads − User managed threads. Kernel Level Threads − Operating System managed threads acting on kernel, an operating system core. Kernel Level Threads − Operating System managed threads acting on kernel, an operating system core. In this case, the thread management kernel is not aware of the existence of threads. The thread library contains code for creating and destroying threads, for passing message and data between threads, for scheduling thread execution and for saving and restoring thread contexts. The application starts with a single thread. Thread switching does not require Kernel mode privileges. User level thread can run on any operating system. Scheduling can be application specific in the user level thread. User level threads are fast to create and manage. In a typical operating system, most system calls are blocking. Multithreaded application cannot take advantage of multiprocessing. In this case, thread management is done by the Kernel. There is no thread management code in the application area. Kernel threads are supported directly by the operating system. Any application can be programmed to be multithreaded. All of the threads within an application are supported within a single process. The Kernel maintains context information for the process as a whole and for individuals threads within the process. Scheduling by the Kernel is done on a thread basis. The Kernel performs thread creation, scheduling and management in Kernel space. Kernel threads are generally slower to create and manage than the user threads. Kernel can simultaneously schedule multiple threads from the same process on multiple processes. If one thread in a process is blocked, the Kernel can schedule another thread of the same process. Kernel routines themselves can be multithreaded. Kernel threads are generally slower to create and manage than the user threads. Transfer of control from one thread to another within the same process requires a mode switch to the Kernel. Some operating system provide a combined user level thread and Kernel level thread facility. Solaris is a good example of this combined approach. In a combined system, multiple threads within the same application can run in parallel on multiple processors and a blocking system call need not block the entire process. Multithreading models are three types Many to many relationship. Many to one relationship. One to one relationship. The many-to-many model multiplexes any number of user threads onto an equal or smaller number of kernel threads. The following diagram shows the many-to-many threading model where 6 user level threads are multiplexing with 6 kernel level threads. In this model, developers can create as many user threads as necessary and the corresponding Kernel threads can run in parallel on a multiprocessor machine. This model provides the best accuracy on concurrency and when a thread performs a blocking system call, the kernel can schedule another thread for execution. Many-to-one model maps many user level threads to one Kernel-level thread. Thread management is done in user space by the thread library. When thread makes a blocking system call, the entire process will be blocked. Only one thread can access the Kernel at a time, so multiple threads are unable to run in parallel on multiprocessors. If the user-level thread libraries are implemented in the operating system in such a way that the system does not support them, then the Kernel threads use the many-to-one relationship modes. There is one-to-one relationship of user-level thread to the kernel-level thread. This model provides more concurrency than the many-to-one model. It also allows another thread to run when a thread makes a blocking system call. It supports multiple threads to execute in parallel on microprocessors. Disadvantage of this model is that creating user thread requires the corresponding Kernel thread. OS/2, windows NT and windows 2000 use one to one relationship model. Memory management is the functionality of an operating system which handles or manages primary memory and moves processes back and forth between main memory and disk during execution. Memory management keeps track of each and every memory location, regardless of either it is allocated to some process or it is free. It checks how much memory is to be allocated to processes. It decides which process will get memory at what time. It tracks whenever some memory gets freed or unallocated and correspondingly it updates the status. This tutorial will teach you basic concepts related to Memory Management. The process address space is the set of logical addresses that a process references in its code. For example, when 32-bit addressing is in use, addresses can range from 0 to 0x7fffffff; that is, 2^31 possible numbers, for a total theoretical size of 2 gigabytes. The operating system takes care of mapping the logical addresses to physical addresses at the time of memory allocation to the program. There are three types of addresses used in a program before and after memory is allocated − Symbolic addresses The addresses used in a source code. The variable names, constants, and instruction labels are the basic elements of the symbolic address space. Relative addresses At the time of compilation, a compiler converts symbolic addresses into relative addresses. Physical addresses The loader generates these addresses at the time when a program is loaded into main memory. Virtual and physical addresses are the same in compile-time and load-time address-binding schemes. Virtual and physical addresses differ in execution-time address-binding scheme. The set of all logical addresses generated by a program is referred to as a logical address space. The set of all physical addresses corresponding to these logical addresses is referred to as a physical address space. The runtime mapping from virtual to physical address is done by the memory management unit (MMU) which is a hardware device. MMU uses following mechanism to convert virtual address to physical address. The value in the base register is added to every address generated by a user process, which is treated as offset at the time it is sent to memory. For example, if the base register value is 10000, then an attempt by the user to use address location 100 will be dynamically reallocated to location 10100. The value in the base register is added to every address generated by a user process, which is treated as offset at the time it is sent to memory. For example, if the base register value is 10000, then an attempt by the user to use address location 100 will be dynamically reallocated to location 10100. The user program deals with virtual addresses; it never sees the real physical addresses. The user program deals with virtual addresses; it never sees the real physical addresses. The choice between Static or Dynamic Loading is to be made at the time of computer program being developed. If you have to load your program statically, then at the time of compilation, the complete programs will be compiled and linked without leaving any external program or module dependency. The linker combines the object program with other necessary object modules into an absolute program, which also includes logical addresses. If you are writing a Dynamically loaded program, then your compiler will compile the program and for all the modules which you want to include dynamically, only references will be provided and rest of the work will be done at the time of execution. At the time of loading, with static loading, the absolute program (and data) is loaded into memory in order for execution to start. If you are using dynamic loading, dynamic routines of the library are stored on a disk in relocatable form and are loaded into memory only when they are needed by the program. As explained above, when static linking is used, the linker combines all other modules needed by a program into a single executable program to avoid any runtime dependency. When dynamic linking is used, it is not required to link the actual module or library with the program, rather a reference to the dynamic module is provided at the time of compilation and linking. Dynamic Link Libraries (DLL) in Windows and Shared Objects in Unix are good examples of dynamic libraries. Swapping is a mechanism in which a process can be swapped temporarily out of main memory (or move) to secondary storage (disk) and make that memory available to other processes. At some later time, the system swaps back the process from the secondary storage to main memory. Though performance is usually affected by swapping process but it helps in running multiple and big processes in parallel and that's the reason Swapping is also known as a technique for memory compaction. The total time taken by swapping process includes the time it takes to move the entire process to a secondary disk and then to copy the process back to memory, as well as the time the process takes to regain main memory. Let us assume that the user process is of size 2048KB and on a standard hard disk where swapping will take place has a data transfer rate around 1 MB per second. The actual transfer of the 1000K process to or from memory will take 2048KB / 1024KB per second = 2 seconds = 2000 milliseconds Now considering in and out time, it will take complete 4000 milliseconds plus other overhead where the process competes to regain main memory. Main memory usually has two partitions − Low Memory − Operating system resides in this memory. Low Memory − Operating system resides in this memory. High Memory − User processes are held in high memory. High Memory − User processes are held in high memory. Operating system uses the following memory allocation mechanism. Single-partition allocation In this type of allocation, relocation-register scheme is used to protect user processes from each other, and from changing operating-system code and data. Relocation register contains value of smallest physical address whereas limit register contains range of logical addresses. Each logical address must be less than the limit register. Multiple-partition allocation In this type of allocation, main memory is divided into a number of fixed-sized partitions where each partition should contain only one process. When a partition is free, a process is selected from the input queue and is loaded into the free partition. When the process terminates, the partition becomes available for another process. As processes are loaded and removed from memory, the free memory space is broken into little pieces. It happens after sometimes that processes cannot be allocated to memory blocks considering their small size and memory blocks remains unused. This problem is known as Fragmentation. Fragmentation is of two types − External fragmentation Total memory space is enough to satisfy a request or to reside a process in it, but it is not contiguous, so it cannot be used. Internal fragmentation Memory block assigned to process is bigger. Some portion of memory is left unused, as it cannot be used by another process. The following diagram shows how fragmentation can cause waste of memory and a compaction technique can be used to create more free memory out of fragmented memory − External fragmentation can be reduced by compaction or shuffle memory contents to place all free memory together in one large block. To make compaction feasible, relocation should be dynamic. The internal fragmentation can be reduced by effectively assigning the smallest partition but large enough for the process. A computer can address more memory than the amount physically installed on the system. This extra memory is actually called virtual memory and it is a section of a hard that's set up to emulate the computer's RAM. Paging technique plays an important role in implementing virtual memory. Paging is a memory management technique in which process address space is broken into blocks of the same size called pages (size is power of 2, between 512 bytes and 8192 bytes). The size of the process is measured in the number of pages. Similarly, main memory is divided into small fixed-sized blocks of (physical) memory called frames and the size of a frame is kept the same as that of a page to have optimum utilization of the main memory and to avoid external fragmentation. Page address is called logical address and represented by page number and the offset. Logical Address = Page number + page offset Frame address is called physical address and represented by a frame number and the offset. Physical Address = Frame number + page offset A data structure called page map table is used to keep track of the relation between a page of a process to a frame in physical memory. When the system allocates a frame to any page, it translates this logical address into a physical address and create entry into the page table to be used throughout execution of the program. When a process is to be executed, its corresponding pages are loaded into any available memory frames. Suppose you have a program of 8Kb but your memory can accommodate only 5Kb at a given point in time, then the paging concept will come into picture. When a computer runs out of RAM, the operating system (OS) will move idle or unwanted pages of memory to secondary memory to free up RAM for other processes and brings them back when needed by the program. This process continues during the whole execution of the program where the OS keeps removing idle pages from the main memory and write them onto the secondary memory and bring them back when required by the program. Here is a list of advantages and disadvantages of paging − Paging reduces external fragmentation, but still suffer from internal fragmentation. Paging reduces external fragmentation, but still suffer from internal fragmentation. Paging is simple to implement and assumed as an efficient memory management technique. Paging is simple to implement and assumed as an efficient memory management technique. Due to equal size of the pages and frames, swapping becomes very easy. Due to equal size of the pages and frames, swapping becomes very easy. Page table requires extra memory space, so may not be good for a system having small RAM. Page table requires extra memory space, so may not be good for a system having small RAM. Segmentation is a memory management technique in which each job is divided into several segments of different sizes, one for each module that contains pieces that perform related functions. Each segment is actually a different logical address space of the program. When a process is to be executed, its corresponding segmentation are loaded into non-contiguous memory though every segment is loaded into a contiguous block of available memory. Segmentation memory management works very similar to paging but here segments are of variable-length where as in paging pages are of fixed size. A program segment contains the program's main function, utility functions, data structures, and so on. The operating system maintains a segment map table for every process and a list of free memory blocks along with segment numbers, their size and corresponding memory locations in main memory. For each segment, the table stores the starting address of the segment and the length of the segment. A reference to a memory location includes a value that identifies a segment and an offset. A computer can address more memory than the amount physically installed on the system. This extra memory is actually called virtual memory and it is a section of a hard disk that's set up to emulate the computer's RAM. The main visible advantage of this scheme is that programs can be larger than physical memory. Virtual memory serves two purposes. First, it allows us to extend the use of physical memory by using disk. Second, it allows us to have memory protection, because each virtual address is translated to a physical address. Following are the situations, when entire program is not required to be loaded fully in main memory. User written error handling routines are used only when an error occurred in the data or computation. User written error handling routines are used only when an error occurred in the data or computation. Certain options and features of a program may be used rarely. Certain options and features of a program may be used rarely. Many tables are assigned a fixed amount of address space even though only a small amount of the table is actually used. Many tables are assigned a fixed amount of address space even though only a small amount of the table is actually used. The ability to execute a program that is only partially in memory would counter many benefits. The ability to execute a program that is only partially in memory would counter many benefits. Less number of I/O would be needed to load or swap each user program into memory. Less number of I/O would be needed to load or swap each user program into memory. A program would no longer be constrained by the amount of physical memory that is available. A program would no longer be constrained by the amount of physical memory that is available. Each user program could take less physical memory, more programs could be run the same time, with a corresponding increase in CPU utilization and throughput. Each user program could take less physical memory, more programs could be run the same time, with a corresponding increase in CPU utilization and throughput. Modern microprocessors intended for general-purpose use, a memory management unit, or MMU, is built into the hardware. The MMU's job is to translate virtual addresses into physical addresses. A basic example is given below − Virtual memory is commonly implemented by demand paging. It can also be implemented in a segmentation system. Demand segmentation can also be used to provide virtual memory. A demand paging system is quite similar to a paging system with swapping where processes reside in secondary memory and pages are loaded only on demand, not in advance. When a context switch occurs, the operating system does not copy any of the old program’s pages out to the disk or any of the new program’s pages into the main memory Instead, it just begins executing the new program after loading the first page and fetches that program’s pages as they are referenced. While executing a program, if the program references a page which is not available in the main memory because it was swapped out a little ago, the processor treats this invalid memory reference as a page fault and transfers control from the program to the operating system to demand the page back into the memory. Following are the advantages of Demand Paging − Large virtual memory. More efficient use of memory. There is no limit on degree of multiprogramming. Number of tables and the amount of processor overhead for handling page interrupts are greater than in the case of the simple paged management techniques. Number of tables and the amount of processor overhead for handling page interrupts are greater than in the case of the simple paged management techniques. Page replacement algorithms are the techniques using which an Operating System decides which memory pages to swap out, write to disk when a page of memory needs to be allocated. Paging happens whenever a page fault occurs and a free page cannot be used for allocation purpose accounting to reason that pages are not available or the number of free pages is lower than required pages. When the page that was selected for replacement and was paged out, is referenced again, it has to read in from disk, and this requires for I/O completion. This process determines the quality of the page replacement algorithm: the lesser the time waiting for page-ins, the better is the algorithm. A page replacement algorithm looks at the limited information about accessing the pages provided by hardware, and tries to select which pages should be replaced to minimize the total number of page misses, while balancing it with the costs of primary storage and processor time of the algorithm itself. There are many different page replacement algorithms. We evaluate an algorithm by running it on a particular string of memory reference and computing the number of page faults, The string of memory references is called reference string. Reference strings are generated artificially or by tracing a given system and recording the address of each memory reference. The latter choice produces a large number of data, where we note two things. For a given page size, we need to consider only the page number, not the entire address. For a given page size, we need to consider only the page number, not the entire address. If we have a reference to a page p, then any immediately following references to page p will never cause a page fault. Page p will be in memory after the first reference; the immediately following references will not fault. If we have a reference to a page p, then any immediately following references to page p will never cause a page fault. Page p will be in memory after the first reference; the immediately following references will not fault. For example, consider the following sequence of addresses − 123,215,600,1234,76,96 For example, consider the following sequence of addresses − 123,215,600,1234,76,96 If page size is 100, then the reference string is 1,2,6,12,0,0 If page size is 100, then the reference string is 1,2,6,12,0,0 Oldest page in main memory is the one which will be selected for replacement. Oldest page in main memory is the one which will be selected for replacement. Easy to implement, keep a list, replace pages from the tail and add new pages at the head. Easy to implement, keep a list, replace pages from the tail and add new pages at the head. An optimal page-replacement algorithm has the lowest page-fault rate of all algorithms. An optimal page-replacement algorithm exists, and has been called OPT or MIN. An optimal page-replacement algorithm has the lowest page-fault rate of all algorithms. An optimal page-replacement algorithm exists, and has been called OPT or MIN. Replace the page that will not be used for the longest period of time. Use the time when a page is to be used. Replace the page that will not be used for the longest period of time. Use the time when a page is to be used. Page which has not been used for the longest time in main memory is the one which will be selected for replacement. Page which has not been used for the longest time in main memory is the one which will be selected for replacement. Easy to implement, keep a list, replace pages by looking back into time. Easy to implement, keep a list, replace pages by looking back into time. To get a process start quickly, keep a pool of free frames. On page fault, select a page to be replaced. Write the new page in the frame of free pool, mark the page table and restart the process. Now write the dirty page out of disk and place the frame holding replaced page in free pool. The page with the smallest count is the one which will be selected for replacement. The page with the smallest count is the one which will be selected for replacement. This algorithm suffers from the situation in which a page is used heavily during the initial phase of a process, but then is never used again. This algorithm suffers from the situation in which a page is used heavily during the initial phase of a process, but then is never used again. This algorithm is based on the argument that the page with the smallest count was probably just brought in and has yet to be used. This algorithm is based on the argument that the page with the smallest count was probably just brought in and has yet to be used. One of the important jobs of an Operating System is to manage various I/O devices including mouse, keyboards, touch pad, disk drives, display adapters, USB devices, Bit-mapped screen, LED, Analog-to-digital converter, On/off switch, network connections, audio I/O, printers etc. An I/O system is required to take an application I/O request and send it to the physical device, then take whatever response comes back from the device and send it to the application. I/O devices can be divided into two categories − Block devices − A block device is one with which the driver communicates by sending entire blocks of data. For example, Hard disks, USB cameras, Disk-On-Key etc. Block devices − A block device is one with which the driver communicates by sending entire blocks of data. For example, Hard disks, USB cameras, Disk-On-Key etc. Character devices − A character device is one with which the driver communicates by sending and receiving single characters (bytes, octets). For example, serial ports, parallel ports, sounds cards etc Character devices − A character device is one with which the driver communicates by sending and receiving single characters (bytes, octets). For example, serial ports, parallel ports, sounds cards etc Device drivers are software modules that can be plugged into an OS to handle a particular device. Operating System takes help from device drivers to handle all I/O devices. The Device Controller works like an interface between a device and a device driver. I/O units (Keyboard, mouse, printer, etc.) typically consist of a mechanical component and an electronic component where electronic component is called the device controller. There is always a device controller and a device driver for each device to communicate with the Operating Systems. A device controller may be able to handle multiple devices. As an interface its main task is to convert serial bit stream to block of bytes, perform error correction as necessary. Any device connected to the computer is connected by a plug and socket, and the socket is connected to a device controller. Following is a model for connecting the CPU, memory, controllers, and I/O devices where CPU and device controllers all use a common bus for communication. Synchronous I/O − In this scheme CPU execution waits while I/O proceeds Synchronous I/O − In this scheme CPU execution waits while I/O proceeds Asynchronous I/O − I/O proceeds concurrently with CPU execution Asynchronous I/O − I/O proceeds concurrently with CPU execution The CPU must have a way to pass information to and from an I/O device. There are three approaches available to communicate with the CPU and Device. Special Instruction I/O Memory-mapped I/O Direct memory access (DMA) This uses CPU instructions that are specifically made for controlling I/O devices. These instructions typically allow data to be sent to an I/O device or read from an I/O device. When using memory-mapped I/O, the same address space is shared by memory and I/O devices. The device is connected directly to certain main memory locations so that I/O device can transfer block of data to/from memory without going through CPU. While using memory mapped IO, OS allocates buffer in memory and informs I/O device to use that buffer to send data to the CPU. I/O device operates asynchronously with CPU, interrupts CPU when finished. The advantage to this method is that every instruction which can access memory can be used to manipulate an I/O device. Memory mapped IO is used for most high-speed I/O devices like disks, communication interfaces. Slow devices like keyboards will generate an interrupt to the main CPU after each byte is transferred. If a fast device such as a disk generated an interrupt for each byte, the operating system would spend most of its time handling these interrupts. So a typical computer uses direct memory access (DMA) hardware to reduce this overhead. Direct Memory Access (DMA) means CPU grants I/O module authority to read from or write to memory without involvement. DMA module itself controls exchange of data between main memory and the I/O device. CPU is only involved at the beginning and end of the transfer and interrupted only after entire block has been transferred. Direct Memory Access needs a special hardware called DMA controller (DMAC) that manages the data transfers and arbitrates access to the system bus. The controllers are programmed with source and destination pointers (where to read/write the data), counters to track the number of transferred bytes, and settings, which includes I/O and memory types, interrupts and states for the CPU cycles. The operating system uses the DMA hardware as follows − A computer must have a way of detecting the arrival of any type of input. There are two ways that this can happen, known as polling and interrupts. Both of these techniques allow the processor to deal with events that can happen at any time and that are not related to the process it is currently running. Polling is the simplest way for an I/O device to communicate with the processor. The process of periodically checking status of the device to see if it is time for the next I/O operation, is called polling. The I/O device simply puts the information in a Status register, and the processor must come and get the information. Most of the time, devices will not require attention and when one does it will have to wait until it is next interrogated by the polling program. This is an inefficient method and much of the processors time is wasted on unnecessary polls. Compare this method to a teacher continually asking every student in a class, one after another, if they need help. Obviously the more efficient method would be for a student to inform the teacher whenever they require assistance. An alternative scheme for dealing with I/O is the interrupt-driven method. An interrupt is a signal to the microprocessor from a device that requires attention. A device controller puts an interrupt signal on the bus when it needs CPU’s attention when CPU receives an interrupt, It saves its current state and invokes the appropriate interrupt handler using the interrupt vector (addresses of OS routines to handle various events). When the interrupting device has been dealt with, the CPU continues with its original task as if it had never been interrupted. I/O software is often organized in the following layers − User Level Libraries − This provides simple interface to the user program to perform input and output. For example, stdio is a library provided by C and C++ programming languages. User Level Libraries − This provides simple interface to the user program to perform input and output. For example, stdio is a library provided by C and C++ programming languages. Kernel Level Modules − This provides device driver to interact with the device controller and device independent I/O modules used by the device drivers. Kernel Level Modules − This provides device driver to interact with the device controller and device independent I/O modules used by the device drivers. Hardware − This layer includes actual hardware and hardware controller which interact with the device drivers and makes hardware alive. Hardware − This layer includes actual hardware and hardware controller which interact with the device drivers and makes hardware alive. A key concept in the design of I/O software is that it should be device independent where it should be possible to write programs that can access any I/O device without having to specify the device in advance. For example, a program that reads a file as input should be able to read a file on a floppy disk, on a hard disk, or on a CD-ROM, without having to modify the program for each different device. Device drivers are software modules that can be plugged into an OS to handle a particular device. Operating System takes help from device drivers to handle all I/O devices. Device drivers encapsulate device-dependent code and implement a standard interface in such a way that code contains device-specific register reads/writes. Device driver, is generally written by the device's manufacturer and delivered along with the device on a CD-ROM. A device driver performs the following jobs − To accept request from the device independent software above to it. Interact with the device controller to take and give I/O and perform required error handling Making sure that the request is executed successfully How a device driver handles a request is as follows: Suppose a request comes to read a block N. If the driver is idle at the time a request arrives, it starts carrying out the request immediately. Otherwise, if the driver is already busy with some other request, it places the new request in the queue of pending requests. An interrupt handler, also known as an interrupt service routine or ISR, is a piece of software or more specifically a callback function in an operating system or more specifically in a device driver, whose execution is triggered by the reception of an interrupt. When the interrupt happens, the interrupt procedure does whatever it has to in order to handle the interrupt, updates data structures and wakes up process that was waiting for an interrupt to happen. The interrupt mechanism accepts an address ─ a number that selects a specific interrupt handling routine/function from a small set. In most architectures, this address is an offset stored in a table called the interrupt vector table. This vector contains the memory addresses of specialized interrupt handlers. The basic function of the device-independent software is to perform the I/O functions that are common to all devices and to provide a uniform interface to the user-level software. Though it is difficult to write completely device independent software but we can write some modules which are common among all the devices. Following is a list of functions of device-independent I/O Software − Uniform interfacing for device drivers Device naming - Mnemonic names mapped to Major and Minor device numbers Device protection Providing a device-independent block size Buffering because data coming off a device cannot be stored in final destination. Storage allocation on block devices Allocation and releasing dedicated devices Error Reporting These are the libraries which provide richer and simplified interface to access the functionality of the kernel or ultimately interactive with the device drivers. Most of the user-level I/O software consists of library procedures with some exception like spooling system which is a way of dealing with dedicated I/O devices in a multiprogramming system. I/O Libraries (e.g., stdio) are in user-space to provide an interface to the OS resident device-independent I/O SW. For example putchar(), getchar(), printf() and scanf() are example of user level I/O library stdio available in C programming. Kernel I/O Subsystem is responsible to provide many services related to I/O. Following are some of the services provided. Scheduling − Kernel schedules a set of I/O requests to determine a good order in which to execute them. When an application issues a blocking I/O system call, the request is placed on the queue for that device. The Kernel I/O scheduler rearranges the order of the queue to improve the overall system efficiency and the average response time experienced by the applications. Scheduling − Kernel schedules a set of I/O requests to determine a good order in which to execute them. When an application issues a blocking I/O system call, the request is placed on the queue for that device. The Kernel I/O scheduler rearranges the order of the queue to improve the overall system efficiency and the average response time experienced by the applications. Buffering − Kernel I/O Subsystem maintains a memory area known as buffer that stores data while they are transferred between two devices or between a device with an application operation. Buffering is done to cope with a speed mismatch between the producer and consumer of a data stream or to adapt between devices that have different data transfer sizes. Buffering − Kernel I/O Subsystem maintains a memory area known as buffer that stores data while they are transferred between two devices or between a device with an application operation. Buffering is done to cope with a speed mismatch between the producer and consumer of a data stream or to adapt between devices that have different data transfer sizes. Caching − Kernel maintains cache memory which is region of fast memory that holds copies of data. Access to the cached copy is more efficient than access to the original. Caching − Kernel maintains cache memory which is region of fast memory that holds copies of data. Access to the cached copy is more efficient than access to the original. Spooling and Device Reservation − A spool is a buffer that holds output for a device, such as a printer, that cannot accept interleaved data streams. The spooling system copies the queued spool files to the printer one at a time. In some operating systems, spooling is managed by a system daemon process. In other operating systems, it is handled by an in kernel thread. Spooling and Device Reservation − A spool is a buffer that holds output for a device, such as a printer, that cannot accept interleaved data streams. The spooling system copies the queued spool files to the printer one at a time. In some operating systems, spooling is managed by a system daemon process. In other operating systems, it is handled by an in kernel thread. Error Handling − An operating system that uses protected memory can guard against many kinds of hardware and application errors. Error Handling − An operating system that uses protected memory can guard against many kinds of hardware and application errors. A file is a named collection of related information that is recorded on secondary storage such as magnetic disks, magnetic tapes and optical disks. In general, a file is a sequence of bits, bytes, lines or records whose meaning is defined by the files creator and user. A File Structure should be according to a required format that the operating system can understand. A file has a certain defined structure according to its type. A file has a certain defined structure according to its type. A text file is a sequence of characters organized into lines. A text file is a sequence of characters organized into lines. A source file is a sequence of procedures and functions. A source file is a sequence of procedures and functions. An object file is a sequence of bytes organized into blocks that are understandable by the machine. An object file is a sequence of bytes organized into blocks that are understandable by the machine. When operating system defines different file structures, it also contains the code to support these file structure. Unix, MS-DOS support minimum number of file structure. When operating system defines different file structures, it also contains the code to support these file structure. Unix, MS-DOS support minimum number of file structure. File type refers to the ability of the operating system to distinguish different types of file such as text files source files and binary files etc. Many operating systems support many types of files. Operating system like MS-DOS and UNIX have the following types of files − These are the files that contain user information. These may have text, databases or executable program. The user can apply various operations on such files like add, modify, delete or even remove the entire file. These files contain list of file names and other information related to these files. These files are also known as device files. These files represent physical device like disks, terminals, printers, networks, tape drive etc. These files are of two types − Character special files − data is handled character by character as in case of terminals or printers. Character special files − data is handled character by character as in case of terminals or printers. Block special files − data is handled in blocks as in the case of disks and tapes. Block special files − data is handled in blocks as in the case of disks and tapes. File access mechanism refers to the manner in which the records of a file may be accessed. There are several ways to access files − Sequential access Direct/Random access Indexed sequential access A sequential access is that in which the records are accessed in some sequence, i.e., the information in the file is processed in order, one record after the other. This access method is the most primitive one. Example: Compilers usually access files in this fashion. Random access file organization provides, accessing the records directly. Random access file organization provides, accessing the records directly. Each record has its own address on the file with by the help of which it can be directly accessed for reading or writing. Each record has its own address on the file with by the help of which it can be directly accessed for reading or writing. The records need not be in any sequence within the file and they need not be in adjacent locations on the storage medium. The records need not be in any sequence within the file and they need not be in adjacent locations on the storage medium. This mechanism is built up on base of sequential access. An index is created for each file which contains pointers to various blocks. Index is searched sequentially and its pointer is used to access the file directly. Files are allocated disk spaces by operating system. Operating systems deploy following three main ways to allocate disk space to files. Contiguous Allocation Linked Allocation Indexed Allocation Each file occupies a contiguous address space on disk. Assigned disk address is in linear order. Easy to implement. External fragmentation is a major issue with this type of allocation technique. Each file carries a list of links to disk blocks. Directory contains link / pointer to first block of a file. No external fragmentation Effectively used in sequential access file. Inefficient in case of direct access file. Provides solutions to problems of contiguous and linked allocation. A index block is created having all pointers to files. Each file has its own index block which stores the addresses of disk space occupied by the file. Directory contains the addresses of index blocks of files. Security refers to providing a protection system to computer system resources such as CPU, memory, disk, software programs and most importantly data/information stored in the computer system. If a computer program is run by an unauthorized user, then he/she may cause severe damage to computer or data stored in it. So a computer system must be protected against unauthorized access, malicious access to system memory, viruses, worms etc. We're going to discuss following topics in this chapter. Authentication One Time passwords Program Threats System Threats Computer Security Classifications Authentication refers to identifying each user of the system and associating the executing programs with those users. It is the responsibility of the Operating System to create a protection system which ensures that a user who is running a particular program is authentic. Operating Systems generally identifies/authenticates users using following three ways − Username / Password − User need to enter a registered username and password with Operating system to login into the system. Username / Password − User need to enter a registered username and password with Operating system to login into the system. User card/key − User need to punch card in card slot, or enter key generated by key generator in option provided by operating system to login into the system. User card/key − User need to punch card in card slot, or enter key generated by key generator in option provided by operating system to login into the system. User attribute - fingerprint/ eye retina pattern/ signature − User need to pass his/her attribute via designated input device used by operating system to login into the system. User attribute - fingerprint/ eye retina pattern/ signature − User need to pass his/her attribute via designated input device used by operating system to login into the system. One-time passwords provide additional security along with normal authentication. In One-Time Password system, a unique password is required every time user tries to login into the system. Once a one-time password is used, then it cannot be used again. One-time password are implemented in various ways. Random numbers − Users are provided cards having numbers printed along with corresponding alphabets. System asks for numbers corresponding to few alphabets randomly chosen. Random numbers − Users are provided cards having numbers printed along with corresponding alphabets. System asks for numbers corresponding to few alphabets randomly chosen. Secret key − User are provided a hardware device which can create a secret id mapped with user id. System asks for such secret id which is to be generated every time prior to login. Secret key − User are provided a hardware device which can create a secret id mapped with user id. System asks for such secret id which is to be generated every time prior to login. Network password − Some commercial applications send one-time passwords to user on registered mobile/ email which is required to be entered prior to login. Network password − Some commercial applications send one-time passwords to user on registered mobile/ email which is required to be entered prior to login. Operating system's processes and kernel do the designated task as instructed. If a user program made these process do malicious tasks, then it is known as Program Threats. One of the common example of program threat is a program installed in a computer which can store and send user credentials via network to some hacker. Following is the list of some well-known program threats. Trojan Horse − Such program traps user login credentials and stores them to send to malicious user who can later on login to computer and can access system resources. Trojan Horse − Such program traps user login credentials and stores them to send to malicious user who can later on login to computer and can access system resources. Trap Door − If a program which is designed to work as required, have a security hole in its code and perform illegal action without knowledge of user then it is called to have a trap door. Trap Door − If a program which is designed to work as required, have a security hole in its code and perform illegal action without knowledge of user then it is called to have a trap door. Logic Bomb − Logic bomb is a situation when a program misbehaves only when certain conditions met otherwise it works as a genuine program. It is harder to detect. Logic Bomb − Logic bomb is a situation when a program misbehaves only when certain conditions met otherwise it works as a genuine program. It is harder to detect. Virus − Virus as name suggest can replicate themselves on computer system. They are highly dangerous and can modify/delete user files, crash systems. A virus is generatlly a small code embedded in a program. As user accesses the program, the virus starts getting embedded in other files/ programs and can make system unusable for user Virus − Virus as name suggest can replicate themselves on computer system. They are highly dangerous and can modify/delete user files, crash systems. A virus is generatlly a small code embedded in a program. As user accesses the program, the virus starts getting embedded in other files/ programs and can make system unusable for user System threats refers to misuse of system services and network connections to put user in trouble. System threats can be used to launch program threats on a complete network called as program attack. System threats creates such an environment that operating system resources/ user files are misused. Following is the list of some well-known system threats. Worm − Worm is a process which can choked down a system performance by using system resources to extreme levels. A Worm process generates its multiple copies where each copy uses system resources, prevents all other processes to get required resources. Worms processes can even shut down an entire network. Worm − Worm is a process which can choked down a system performance by using system resources to extreme levels. A Worm process generates its multiple copies where each copy uses system resources, prevents all other processes to get required resources. Worms processes can even shut down an entire network. Port Scanning − Port scanning is a mechanism or means by which a hacker can detects system vulnerabilities to make an attack on the system. Port Scanning − Port scanning is a mechanism or means by which a hacker can detects system vulnerabilities to make an attack on the system. Denial of Service − Denial of service attacks normally prevents user to make legitimate use of the system. For example, a user may not be able to use internet if denial of service attacks browser's content settings. Denial of Service − Denial of service attacks normally prevents user to make legitimate use of the system. For example, a user may not be able to use internet if denial of service attacks browser's content settings. As per the U.S. Department of Defense Trusted Computer System's Evaluation Criteria there are four security classifications in computer systems: A, B, C, and D. This is widely used specifications to determine and model the security of systems and of security solutions. Following is the brief description of each classification. Type A Highest Level. Uses formal design specifications and verification techniques. Grants a high degree of assurance of process security. Type B Provides mandatory protection system. Have all the properties of a class C2 system. Attaches a sensitivity label to each object. It is of three types. B1 − Maintains the security label of each object in the system. Label is used for making decisions to access control. B1 − Maintains the security label of each object in the system. Label is used for making decisions to access control. B2 − Extends the sensitivity labels to each system resource, such as storage objects, supports covert channels and auditing of events. B2 − Extends the sensitivity labels to each system resource, such as storage objects, supports covert channels and auditing of events. B3 − Allows creating lists or user groups for access-control to grant access or revoke access to a given named object. B3 − Allows creating lists or user groups for access-control to grant access or revoke access to a given named object. Type C Provides protection and user accountability using audit capabilities. It is of two types. C1 − Incorporates controls so that users can protect their private information and keep other users from accidentally reading / deleting their data. UNIX versions are mostly Cl class. C1 − Incorporates controls so that users can protect their private information and keep other users from accidentally reading / deleting their data. UNIX versions are mostly Cl class. C2 − Adds an individual-level access control to the capabilities of a Cl level system. C2 − Adds an individual-level access control to the capabilities of a Cl level system. Type D Lowest level. Minimum protection. MS-DOS, Window 3.1 fall in this category. Linux is one of popular version of UNIX operating System. It is open source as its source code is freely available. It is free to use. Linux was designed considering UNIX compatibility. Its functionality list is quite similar to that of UNIX. Linux Operating System has primarily three components Kernel − Kernel is the core part of Linux. It is responsible for all major activities of this operating system. It consists of various modules and it interacts directly with the underlying hardware. Kernel provides the required abstraction to hide low level hardware details to system or application programs. Kernel − Kernel is the core part of Linux. It is responsible for all major activities of this operating system. It consists of various modules and it interacts directly with the underlying hardware. Kernel provides the required abstraction to hide low level hardware details to system or application programs. System Library − System libraries are special functions or programs using which application programs or system utilities accesses Kernel's features. These libraries implement most of the functionalities of the operating system and do not requires kernel module's code access rights. System Library − System libraries are special functions or programs using which application programs or system utilities accesses Kernel's features. These libraries implement most of the functionalities of the operating system and do not requires kernel module's code access rights. System Utility − System Utility programs are responsible to do specialized, individual level tasks. System Utility − System Utility programs are responsible to do specialized, individual level tasks. Kernel component code executes in a special privileged mode called kernel mode with full access to all resources of the computer. This code represents a single process, executes in single address space and do not require any context switch and hence is very efficient and fast. Kernel runs each processes and provides system services to processes, provides protected access to hardware to processes. Support code which is not required to run in kernel mode is in System Library. User programs and other system programs works in User Mode which has no access to system hardware and kernel code. User programs/ utilities use System libraries to access Kernel functions to get system's low level tasks. Following are some of the important features of Linux Operating System. Portable − Portability means software can works on different types of hardware in same way. Linux kernel and application programs supports their installation on any kind of hardware platform. Portable − Portability means software can works on different types of hardware in same way. Linux kernel and application programs supports their installation on any kind of hardware platform. Open Source − Linux source code is freely available and it is community based development project. Multiple teams work in collaboration to enhance the capability of Linux operating system and it is continuously evolving. Open Source − Linux source code is freely available and it is community based development project. Multiple teams work in collaboration to enhance the capability of Linux operating system and it is continuously evolving. Multi-User − Linux is a multiuser system means multiple users can access system resources like memory/ ram/ application programs at same time. Multi-User − Linux is a multiuser system means multiple users can access system resources like memory/ ram/ application programs at same time. Multiprogramming − Linux is a multiprogramming system means multiple applications can run at same time. Multiprogramming − Linux is a multiprogramming system means multiple applications can run at same time. Hierarchical File System − Linux provides a standard file structure in which system files/ user files are arranged. Hierarchical File System − Linux provides a standard file structure in which system files/ user files are arranged. Shell − Linux provides a special interpreter program which can be used to execute commands of the operating system. It can be used to do various types of operations, call application programs. etc. Shell − Linux provides a special interpreter program which can be used to execute commands of the operating system. It can be used to do various types of operations, call application programs. etc. Security − Linux provides user security using authentication features like password protection/ controlled access to specific files/ encryption of data. Security − Linux provides user security using authentication features like password protection/ controlled access to specific files/ encryption of data. The following illustration shows the architecture of a Linux system − The architecture of a Linux System consists of the following layers − Hardware layer − Hardware consists of all peripheral devices (RAM/ HDD/ CPU etc). Hardware layer − Hardware consists of all peripheral devices (RAM/ HDD/ CPU etc). Kernel − It is the core component of Operating System, interacts directly with hardware, provides low level services to upper layer components. Kernel − It is the core component of Operating System, interacts directly with hardware, provides low level services to upper layer components. Shell − An interface to kernel, hiding complexity of kernel's functions from users. The shell takes commands from the user and executes kernel's functions. Shell − An interface to kernel, hiding complexity of kernel's functions from users. The shell takes commands from the user and executes kernel's functions. Utilities − Utility programs that provide the user most of the functionalities of an operating systems. Utilities − Utility programs that provide the user most of the functionalities of an operating systems. 86 Lectures 10 hours Arnab Chakraborty 5 Lectures 4.5 hours Frahaan Hussain 8 Lectures 43 mins Harshit Srivastava 29 Lectures 2.5 hours Ashraf Said 43 Lectures 20 hours ILANCHEZHIAN K 45 Lectures 20 hours ILANCHEZHIAN K Print Add Notes Bookmark this page
[ { "code": null, "e": 2228, "s": 1914, "text": "An Operating System (OS) is an interface between a computer user and computer hardware. An operating system is a software which performs all the basic tasks like file management, memory management, process management, handling input and output, and controlling peripheral devices such as disk drives and printers." }, { "code": null, "e": 2346, "s": 2228, "text": "Some popular Operating Systems include Linux Operating System, Windows Operating System, VMS, OS/400, AIX, z/OS, etc." }, { "code": null, "e": 2501, "s": 2346, "text": "An operating system is a program that acts as an interface between the user and the computer hardware and controls the execution of all kinds of programs." }, { "code": null, "e": 2567, "s": 2501, "text": "Following are some of important functions of an operating System." }, { "code": null, "e": 2585, "s": 2567, "text": "Memory Management" }, { "code": null, "e": 2606, "s": 2585, "text": "Processor Management" }, { "code": null, "e": 2624, "s": 2606, "text": "Device Management" }, { "code": null, "e": 2640, "s": 2624, "text": "File Management" }, { "code": null, "e": 2649, "s": 2640, "text": "Security" }, { "code": null, "e": 2681, "s": 2649, "text": "Control over system performance" }, { "code": null, "e": 2696, "s": 2681, "text": "Job accounting" }, { "code": null, "e": 2717, "s": 2696, "text": "Error detecting aids" }, { "code": null, "e": 2763, "s": 2717, "text": "Coordination between other software and users" }, { "code": null, "e": 2928, "s": 2763, "text": "Memory management refers to management of Primary Memory or Main Memory. Main memory is a large array of words or bytes where each word or byte has its own address." }, { "code": null, "e": 3138, "s": 2928, "text": "Main memory provides a fast storage that can be accessed directly by the CPU. For a program to be executed, it must in the main memory. An Operating System does the following activities for memory management −" }, { "code": null, "e": 3238, "s": 3138, "text": "Keeps tracks of primary memory, i.e., what part of it are in use by whom, what part are not in use." }, { "code": null, "e": 3338, "s": 3238, "text": "Keeps tracks of primary memory, i.e., what part of it are in use by whom, what part are not in use." }, { "code": null, "e": 3423, "s": 3338, "text": "In multiprogramming, the OS decides which process will get memory when and how much." }, { "code": null, "e": 3508, "s": 3423, "text": "In multiprogramming, the OS decides which process will get memory when and how much." }, { "code": null, "e": 3566, "s": 3508, "text": "Allocates the memory when a process requests it to do so." }, { "code": null, "e": 3624, "s": 3566, "text": "Allocates the memory when a process requests it to do so." }, { "code": null, "e": 3706, "s": 3624, "text": "De-allocates the memory when a process no longer needs it or has been terminated." }, { "code": null, "e": 3788, "s": 3706, "text": "De-allocates the memory when a process no longer needs it or has been terminated." }, { "code": null, "e": 4019, "s": 3788, "text": "In multiprogramming environment, the OS decides which process gets the processor when and for how much time. This function is called process scheduling. An Operating System does the following activities for processor management −" }, { "code": null, "e": 4138, "s": 4019, "text": "Keeps tracks of processor and status of process. The program responsible for this task is known as traffic controller." }, { "code": null, "e": 4257, "s": 4138, "text": "Keeps tracks of processor and status of process. The program responsible for this task is known as traffic controller." }, { "code": null, "e": 4301, "s": 4257, "text": "Allocates the processor (CPU) to a process." }, { "code": null, "e": 4345, "s": 4301, "text": "Allocates the processor (CPU) to a process." }, { "code": null, "e": 4406, "s": 4345, "text": "De-allocates processor when a process is no longer required." }, { "code": null, "e": 4467, "s": 4406, "text": "De-allocates processor when a process is no longer required." }, { "code": null, "e": 4603, "s": 4467, "text": "An Operating System manages device communication via their respective drivers. It does the following activities for device management −" }, { "code": null, "e": 4698, "s": 4603, "text": "Keeps tracks of all devices. Program responsible for this task is known as the I/O controller." }, { "code": null, "e": 4793, "s": 4698, "text": "Keeps tracks of all devices. Program responsible for this task is known as the I/O controller." }, { "code": null, "e": 4859, "s": 4793, "text": "Decides which process gets the device when and for how much time." }, { "code": null, "e": 4925, "s": 4859, "text": "Decides which process gets the device when and for how much time." }, { "code": null, "e": 4968, "s": 4925, "text": "Allocates the device in the efficient way." }, { "code": null, "e": 5011, "s": 4968, "text": "Allocates the device in the efficient way." }, { "code": null, "e": 5033, "s": 5011, "text": "De-allocates devices." }, { "code": null, "e": 5055, "s": 5033, "text": "De-allocates devices." }, { "code": null, "e": 5197, "s": 5055, "text": "A file system is normally organized into directories for easy navigation and usage. These directories may contain files and other directions." }, { "code": null, "e": 5269, "s": 5197, "text": "An Operating System does the following activities for file management −" }, { "code": null, "e": 5383, "s": 5269, "text": "Keeps track of information, location, uses, status etc. The collective facilities are often known as file system." }, { "code": null, "e": 5497, "s": 5383, "text": "Keeps track of information, location, uses, status etc. The collective facilities are often known as file system." }, { "code": null, "e": 5529, "s": 5497, "text": "Decides who gets the resources." }, { "code": null, "e": 5561, "s": 5529, "text": "Decides who gets the resources." }, { "code": null, "e": 5586, "s": 5561, "text": "Allocates the resources." }, { "code": null, "e": 5611, "s": 5586, "text": "Allocates the resources." }, { "code": null, "e": 5639, "s": 5611, "text": "De-allocates the resources." }, { "code": null, "e": 5667, "s": 5639, "text": "De-allocates the resources." }, { "code": null, "e": 5750, "s": 5667, "text": "Following are some of the important activities that an Operating System performs −" }, { "code": null, "e": 5867, "s": 5750, "text": "Security − By means of password and similar other techniques, it prevents unauthorized access to programs and data." }, { "code": null, "e": 5984, "s": 5867, "text": "Security − By means of password and similar other techniques, it prevents unauthorized access to programs and data." }, { "code": null, "e": 6095, "s": 5984, "text": "Control over system performance − Recording delays between request for a service and response from the system." }, { "code": null, "e": 6206, "s": 6095, "text": "Control over system performance − Recording delays between request for a service and response from the system." }, { "code": null, "e": 6291, "s": 6206, "text": "Job accounting − Keeping track of time and resources used by various jobs and users." }, { "code": null, "e": 6376, "s": 6291, "text": "Job accounting − Keeping track of time and resources used by various jobs and users." }, { "code": null, "e": 6490, "s": 6376, "text": "Error detecting aids − Production of dumps, traces, error messages, and other debugging and error detecting aids." }, { "code": null, "e": 6604, "s": 6490, "text": "Error detecting aids − Production of dumps, traces, error messages, and other debugging and error detecting aids." }, { "code": null, "e": 6785, "s": 6604, "text": "Coordination between other softwares and users − Coordination and assignment of compilers, interpreters, assemblers and other software to the various users of the computer systems." }, { "code": null, "e": 6966, "s": 6785, "text": "Coordination between other softwares and users − Coordination and assignment of compilers, interpreters, assemblers and other software to the various users of the computer systems." }, { "code": null, "e": 7180, "s": 6966, "text": "Operating systems are there from the very first computer generation and they keep evolving with time. In this chapter, we will discuss some of the important types of operating systems which are most commonly used." }, { "code": null, "e": 7594, "s": 7180, "text": "The users of a batch operating system do not interact with the computer directly. Each user prepares his job on an off-line device like punch cards and submits it to the computer operator. To speed up processing, jobs with similar needs are batched together and run as a group. The programmers leave their programs with the operator and the operator then sorts the programs with similar requirements into batches." }, { "code": null, "e": 7643, "s": 7594, "text": "The problems with Batch Systems are as follows −" }, { "code": null, "e": 7693, "s": 7643, "text": "Lack of interaction between the user and the job." }, { "code": null, "e": 7784, "s": 7693, "text": "CPU is often idle, because the speed of the mechanical I/O devices is slower than the CPU." }, { "code": null, "e": 7827, "s": 7784, "text": "Difficult to provide the desired priority." }, { "code": null, "e": 8135, "s": 7827, "text": "Time-sharing is a technique which enables many people, located at various terminals, to use a particular computer system at the same time. Time-sharing or multitasking is a logical extension of multiprogramming. Processor's time which is shared among multiple users simultaneously is termed as time-sharing." }, { "code": null, "e": 8389, "s": 8135, "text": "The main difference between Multiprogrammed Batch Systems and Time-Sharing Systems is that in case of Multiprogrammed batch systems, the objective is to maximize processor use, whereas in Time-Sharing Systems, the objective is to minimize response time." }, { "code": null, "e": 8821, "s": 8389, "text": "Multiple jobs are executed by the CPU by switching between them, but the switches occur so frequently. Thus, the user can receive an immediate response. For example, in a transaction processing, the processor executes each user program in a short burst or quantum of computation. That is, if n users are present, then each user can get a time quantum. When the user submits the command, the response time is in few seconds at most." }, { "code": null, "e": 9043, "s": 8821, "text": "The operating system uses CPU scheduling and multiprogramming to provide each user with a small portion of a time. Computer systems that were designed primarily as batch systems have been modified to time-sharing systems." }, { "code": null, "e": 9104, "s": 9043, "text": "Advantages of Timesharing operating systems are as follows −" }, { "code": null, "e": 9146, "s": 9104, "text": "Provides the advantage of quick response." }, { "code": null, "e": 9178, "s": 9146, "text": "Avoids duplication of software." }, { "code": null, "e": 9201, "s": 9178, "text": "Reduces CPU idle time." }, { "code": null, "e": 9266, "s": 9201, "text": "Disadvantages of Time-sharing operating systems are as follows −" }, { "code": null, "e": 9290, "s": 9266, "text": "Problem of reliability." }, { "code": null, "e": 9352, "s": 9290, "text": "Question of security and integrity of user programs and data." }, { "code": null, "e": 9383, "s": 9352, "text": "Problem of data communication." }, { "code": null, "e": 9567, "s": 9383, "text": "Distributed systems use multiple central processors to serve multiple real-time applications and multiple users. Data processing jobs are distributed among the processors accordingly." }, { "code": null, "e": 9899, "s": 9567, "text": "The processors communicate with one another through various communication lines (such as high-speed buses or telephone lines). These are referred as loosely coupled systems or distributed systems. Processors in a distributed system may vary in size and function. These processors are referred as sites, nodes, computers, and so on." }, { "code": null, "e": 9954, "s": 9899, "text": "The advantages of distributed systems are as follows −" }, { "code": null, "e": 10060, "s": 9954, "text": "With resource sharing facility, a user at one site may be able to use the resources available at another." }, { "code": null, "e": 10127, "s": 10060, "text": "Speedup the exchange of data with one another via electronic mail." }, { "code": null, "e": 10226, "s": 10127, "text": "If one site fails in a distributed system, the remaining sites can potentially continue operating." }, { "code": null, "e": 10259, "s": 10226, "text": "Better service to the customers." }, { "code": null, "e": 10303, "s": 10259, "text": "Reduction of the load on the host computer." }, { "code": null, "e": 10343, "s": 10303, "text": "Reduction of delays in data processing." }, { "code": null, "e": 10725, "s": 10343, "text": "A Network Operating System runs on a server and provides the server the capability to manage data, users, groups, security, applications, and other networking functions. The primary purpose of the network operating system is to allow shared file and printer access among multiple computers in a network, typically a local area network (LAN), a private network or to other networks." }, { "code": null, "e": 10881, "s": 10725, "text": "Examples of network operating systems include Microsoft Windows Server 2003, Microsoft Windows Server 2008, UNIX, Linux, Mac OS X, Novell NetWare, and BSD." }, { "code": null, "e": 10942, "s": 10881, "text": "The advantages of network operating systems are as follows −" }, { "code": null, "e": 10981, "s": 10942, "text": "Centralized servers are highly stable." }, { "code": null, "e": 11009, "s": 10981, "text": "Security is server managed." }, { "code": null, "e": 11093, "s": 11009, "text": "Upgrades to new technologies and hardware can be easily integrated into the system." }, { "code": null, "e": 11177, "s": 11093, "text": "Remote access to servers is possible from different locations and types of systems." }, { "code": null, "e": 11241, "s": 11177, "text": "The disadvantages of network operating systems are as follows −" }, { "code": null, "e": 11283, "s": 11241, "text": "High cost of buying and running a server." }, { "code": null, "e": 11337, "s": 11283, "text": "Dependency on a central location for most operations." }, { "code": null, "e": 11383, "s": 11337, "text": "Regular maintenance and updates are required." }, { "code": null, "e": 11768, "s": 11383, "text": "A real-time system is defined as a data processing system in which the time interval required to process and respond to inputs is so small that it controls the environment. The time taken by the system to respond to an input and display of required updated information is termed as the response time. So in this method, the response time is very less as compared to online processing." }, { "code": null, "e": 12225, "s": 11768, "text": "Real-time systems are used when there are rigid time requirements on the operation of a processor or the flow of data and real-time systems can be used as a control device in a dedicated application. A real-time operating system must have well-defined, fixed time constraints, otherwise the system will fail. For example, Scientific experiments, medical imaging systems, industrial control systems, weapon systems, robots, air traffic control systems, etc." }, { "code": null, "e": 12277, "s": 12225, "text": "There are two types of real-time operating systems." }, { "code": null, "e": 12502, "s": 12277, "text": "Hard real-time systems guarantee that critical tasks complete on time. In hard real-time systems, secondary storage is limited or missing and the data is stored in ROM. In these systems, virtual memory is almost never found." }, { "code": null, "e": 12846, "s": 12502, "text": "Soft real-time systems are less restrictive. A critical real-time task gets priority over other tasks and retains the priority until it completes. Soft real-time systems have limited utility than hard real-time systems. For example, multimedia, virtual reality, Advanced Scientific Projects like undersea exploration and planetary rovers, etc." }, { "code": null, "e": 12923, "s": 12846, "text": "An Operating System provides services to both the users and to the programs." }, { "code": null, "e": 12971, "s": 12923, "text": "It provides programs an environment to execute." }, { "code": null, "e": 13050, "s": 12971, "text": "It provides users the services to execute the programs in a convenient manner." }, { "code": null, "e": 13120, "s": 13050, "text": "Following are a few common services provided by an operating system −" }, { "code": null, "e": 13138, "s": 13120, "text": "Program execution" }, { "code": null, "e": 13153, "s": 13138, "text": "I/O operations" }, { "code": null, "e": 13178, "s": 13153, "text": "File System manipulation" }, { "code": null, "e": 13192, "s": 13178, "text": "Communication" }, { "code": null, "e": 13208, "s": 13192, "text": "Error Detection" }, { "code": null, "e": 13228, "s": 13208, "text": "Resource Allocation" }, { "code": null, "e": 13239, "s": 13228, "text": "Protection" }, { "code": null, "e": 13436, "s": 13239, "text": "Operating systems handle many kinds of activities from user programs to system programs like printer spooler, name servers, file server, etc. Each of these activities is encapsulated as a process." }, { "code": null, "e": 13652, "s": 13436, "text": "A process includes the complete execution context (code to execute, data to manipulate, registers, OS resources in use). Following are the major activities of an operating system with respect to program management −" }, { "code": null, "e": 13681, "s": 13652, "text": "Loads a program into memory." }, { "code": null, "e": 13703, "s": 13681, "text": "Executes the program." }, { "code": null, "e": 13732, "s": 13703, "text": "Handles program's execution." }, { "code": null, "e": 13782, "s": 13732, "text": "Provides a mechanism for process synchronization." }, { "code": null, "e": 13830, "s": 13782, "text": "Provides a mechanism for process communication." }, { "code": null, "e": 13874, "s": 13830, "text": "Provides a mechanism for deadlock handling." }, { "code": null, "e": 14033, "s": 13874, "text": "An I/O subsystem comprises of I/O devices and their corresponding driver software. Drivers hide the peculiarities of specific hardware devices from the users." }, { "code": null, "e": 14112, "s": 14033, "text": "An Operating System manages the communication between user and device drivers." }, { "code": null, "e": 14198, "s": 14112, "text": "I/O operation means read or write operation with any file or any specific I/O device." }, { "code": null, "e": 14277, "s": 14198, "text": "Operating system provides the access to the required I/O device when required." }, { "code": null, "e": 14632, "s": 14277, "text": "A file represents a collection of related information. Computers can store files on the disk (secondary storage), for long-term storage purpose. Examples of storage media include magnetic tape, magnetic disk and optical disk drives like CD, DVD. Each of these media has its own properties like speed, capacity, data transfer rate and data access methods." }, { "code": null, "e": 14866, "s": 14632, "text": "A file system is normally organized into directories for easy navigation and usage. These directories may contain files and other directions. Following are the major activities of an operating system with respect to file management −" }, { "code": null, "e": 14912, "s": 14866, "text": "Program needs to read a file or write a file." }, { "code": null, "e": 14992, "s": 14912, "text": "The operating system gives the permission to the program for operation on file." }, { "code": null, "e": 15056, "s": 14992, "text": "Permission varies from read-only, read-write, denied and so on." }, { "code": null, "e": 15131, "s": 15056, "text": "Operating System provides an interface to the user to create/delete files." }, { "code": null, "e": 15212, "s": 15131, "text": "Operating System provides an interface to the user to create/delete directories." }, { "code": null, "e": 15288, "s": 15212, "text": "Operating System provides an interface to create the backup of file system." }, { "code": null, "e": 15577, "s": 15288, "text": "In case of distributed systems which are a collection of processors that do not share memory, peripheral devices, or a clock, the operating system manages communications between all the processes. Multiple processes communicate with one another through communication lines in the network." }, { "code": null, "e": 15762, "s": 15577, "text": "The OS handles routing and connection strategies, and the problems of contention and security. Following are the major activities of an operating system with respect to communication −" }, { "code": null, "e": 15826, "s": 15762, "text": "Two processes often require data to be transferred between them" }, { "code": null, "e": 15941, "s": 15826, "text": "Both the processes can be on one computer or on different computers, but are connected through a computer network." }, { "code": null, "e": 16037, "s": 15941, "text": "Communication may be implemented by two methods, either by Shared Memory or by Message Passing." }, { "code": null, "e": 16236, "s": 16037, "text": "Errors can occur anytime and anywhere. An error may occur in CPU, in I/O devices or in the memory hardware. Following are the major activities of an operating system with respect to error handling −" }, { "code": null, "e": 16282, "s": 16236, "text": "The OS constantly checks for possible errors." }, { "code": null, "e": 16361, "s": 16282, "text": "The OS takes an appropriate action to ensure correct and consistent computing." }, { "code": null, "e": 16610, "s": 16361, "text": "In case of multi-user or multi-tasking environment, resources such as main memory, CPU cycles and files storage are to be allocated to each user or job. Following are the major activities of an operating system with respect to resource management −" }, { "code": null, "e": 16666, "s": 16610, "text": "The OS manages all kinds of resources using schedulers." }, { "code": null, "e": 16732, "s": 16666, "text": "CPU scheduling algorithms are used for better utilization of CPU." }, { "code": null, "e": 16902, "s": 16732, "text": "Considering a computer system having multiple users and concurrent execution of multiple processes, the various processes must be protected from each other's activities." }, { "code": null, "e": 17133, "s": 16902, "text": "Protection refers to a mechanism or a way to control the access of programs, processes, or users to the resources defined by a computer system. Following are the major activities of an operating system with respect to protection −" }, { "code": null, "e": 17199, "s": 17133, "text": "The OS ensures that all access to system resources is controlled." }, { "code": null, "e": 17284, "s": 17199, "text": "The OS ensures that external I/O devices are protected from invalid access attempts." }, { "code": null, "e": 17361, "s": 17284, "text": "The OS provides authentication features for each user by means of passwords." }, { "code": null, "e": 17579, "s": 17361, "text": "Batch processing is a technique in which an Operating System collects the programs and data together in a batch before processing starts. An operating system does the following activities related to batch processing −" }, { "code": null, "e": 17679, "s": 17579, "text": "The OS defines a job which has predefined sequence of commands, programs and data as a single unit." }, { "code": null, "e": 17779, "s": 17679, "text": "The OS defines a job which has predefined sequence of commands, programs and data as a single unit." }, { "code": null, "e": 17868, "s": 17779, "text": "The OS keeps a number a jobs in memory and executes them without any manual information." }, { "code": null, "e": 17957, "s": 17868, "text": "The OS keeps a number a jobs in memory and executes them without any manual information." }, { "code": null, "e": 18043, "s": 17957, "text": "Jobs are processed in the order of submission, i.e., first come first served fashion." }, { "code": null, "e": 18129, "s": 18043, "text": "Jobs are processed in the order of submission, i.e., first come first served fashion." }, { "code": null, "e": 18282, "s": 18129, "text": "When a job completes its execution, its memory is released and the output for the job gets copied into an output spool for later printing or processing." }, { "code": null, "e": 18435, "s": 18282, "text": "When a job completes its execution, its memory is released and the output for the job gets copied into an output spool for later printing or processing." }, { "code": null, "e": 18508, "s": 18435, "text": "Batch processing takes much of the work of the operator to the computer." }, { "code": null, "e": 18581, "s": 18508, "text": "Batch processing takes much of the work of the operator to the computer." }, { "code": null, "e": 18702, "s": 18581, "text": "Increased performance as a new job get started as soon as the previous job is finished, without any manual intervention." }, { "code": null, "e": 18823, "s": 18702, "text": "Increased performance as a new job get started as soon as the previous job is finished, without any manual intervention." }, { "code": null, "e": 18851, "s": 18823, "text": "Difficult to debug program." }, { "code": null, "e": 18887, "s": 18851, "text": "A job could enter an infinite loop." }, { "code": null, "e": 18960, "s": 18887, "text": "Due to lack of protection scheme, one batch job can affect pending jobs." }, { "code": null, "e": 19219, "s": 18960, "text": "Multitasking is when multiple jobs are executed by the CPU simultaneously by switching between them. Switches occur so frequently that the users may interact with each program while it is running. An OS does the following activities related to multitasking −" }, { "code": null, "e": 19333, "s": 19219, "text": "The user gives instructions to the operating system or to a program directly, and receives an immediate response." }, { "code": null, "e": 19447, "s": 19333, "text": "The user gives instructions to the operating system or to a program directly, and receives an immediate response." }, { "code": null, "e": 19563, "s": 19447, "text": "The OS handles multitasking in the way that it can handle multiple operations/executes multiple programs at a time." }, { "code": null, "e": 19679, "s": 19563, "text": "The OS handles multitasking in the way that it can handle multiple operations/executes multiple programs at a time." }, { "code": null, "e": 19750, "s": 19679, "text": "Multitasking Operating Systems are also known as Time-sharing systems." }, { "code": null, "e": 19821, "s": 19750, "text": "Multitasking Operating Systems are also known as Time-sharing systems." }, { "code": null, "e": 19930, "s": 19821, "text": "These Operating Systems were developed to provide interactive use of a computer system at a reasonable cost." }, { "code": null, "e": 20039, "s": 19930, "text": "These Operating Systems were developed to provide interactive use of a computer system at a reasonable cost." }, { "code": null, "e": 20190, "s": 20039, "text": "A time-shared operating system uses the concept of CPU scheduling and multiprogramming to provide each user with a small portion of a time-shared CPU." }, { "code": null, "e": 20341, "s": 20190, "text": "A time-shared operating system uses the concept of CPU scheduling and multiprogramming to provide each user with a small portion of a time-shared CPU." }, { "code": null, "e": 20396, "s": 20341, "text": "Each user has at least one separate program in memory." }, { "code": null, "e": 20451, "s": 20396, "text": "Each user has at least one separate program in memory." }, { "code": null, "e": 20543, "s": 20451, "text": "A program that is loaded into memory and is executing is commonly referred to as a process." }, { "code": null, "e": 20635, "s": 20543, "text": "A program that is loaded into memory and is executing is commonly referred to as a process." }, { "code": null, "e": 20760, "s": 20635, "text": "When a process executes, it typically executes for only a very short time before it either finishes or needs to perform I/O." }, { "code": null, "e": 20885, "s": 20760, "text": "When a process executes, it typically executes for only a very short time before it either finishes or needs to perform I/O." }, { "code": null, "e": 21037, "s": 20885, "text": "Since interactive I/O typically runs at slower speeds, it may take a long time to complete. During this time, a CPU can be utilized by another process." }, { "code": null, "e": 21189, "s": 21037, "text": "Since interactive I/O typically runs at slower speeds, it may take a long time to complete. During this time, a CPU can be utilized by another process." }, { "code": null, "e": 21385, "s": 21189, "text": "The operating system allows the users to share the computer simultaneously. Since each action or command in a time-shared system tends to be short, only a little CPU time is needed for each user." }, { "code": null, "e": 21581, "s": 21385, "text": "The operating system allows the users to share the computer simultaneously. Since each action or command in a time-shared system tends to be short, only a little CPU time is needed for each user." }, { "code": null, "e": 21777, "s": 21581, "text": "As the system switches CPU rapidly from one user/program to the next, each user is given the impression that he/she has his/her own CPU, whereas actually one CPU is being shared among many users." }, { "code": null, "e": 21973, "s": 21777, "text": "As the system switches CPU rapidly from one user/program to the next, each user is given the impression that he/she has his/her own CPU, whereas actually one CPU is being shared among many users." }, { "code": null, "e": 22248, "s": 21973, "text": "Sharing the processor, when two or more programs reside in memory at the same time, is referred as multiprogramming. Multiprogramming assumes a single shared processor. Multiprogramming increases CPU utilization by organizing jobs so that the CPU always has one to execute." }, { "code": null, "e": 22324, "s": 22248, "text": "The following figure shows the memory layout for a multiprogramming system." }, { "code": null, "e": 22389, "s": 22324, "text": "An OS does the following activities related to multiprogramming." }, { "code": null, "e": 22450, "s": 22389, "text": "The operating system keeps several jobs in memory at a time." }, { "code": null, "e": 22511, "s": 22450, "text": "The operating system keeps several jobs in memory at a time." }, { "code": null, "e": 22574, "s": 22511, "text": "This set of jobs is a subset of the jobs kept in the job pool." }, { "code": null, "e": 22637, "s": 22574, "text": "This set of jobs is a subset of the jobs kept in the job pool." }, { "code": null, "e": 22717, "s": 22637, "text": "The operating system picks and begins to execute one of the jobs in the memory." }, { "code": null, "e": 22797, "s": 22717, "text": "The operating system picks and begins to execute one of the jobs in the memory." }, { "code": null, "e": 23003, "s": 22797, "text": "Multiprogramming operating systems monitor the state of all active programs and system resources using memory management programs to ensures that the CPU is never idle, unless there are no jobs to process." }, { "code": null, "e": 23209, "s": 23003, "text": "Multiprogramming operating systems monitor the state of all active programs and system resources using memory management programs to ensures that the CPU is never idle, unless there are no jobs to process." }, { "code": null, "e": 23245, "s": 23209, "text": "High and efficient CPU utilization." }, { "code": null, "e": 23315, "s": 23245, "text": "User feels that many programs are allotted CPU almost simultaneously." }, { "code": null, "e": 23343, "s": 23315, "text": "CPU scheduling is required." }, { "code": null, "e": 23410, "s": 23343, "text": "To accommodate many jobs in memory, memory management is required." }, { "code": null, "e": 23568, "s": 23410, "text": "Interactivity refers to the ability of users to interact with a computer system. An Operating system does the following activities related to interactivity −" }, { "code": null, "e": 23628, "s": 23568, "text": "Provides the user an interface to interact with the system." }, { "code": null, "e": 23703, "s": 23628, "text": "Manages input devices to take inputs from the user. For example, keyboard." }, { "code": null, "e": 23777, "s": 23703, "text": "Manages output devices to show outputs to the user. For example, Monitor." }, { "code": null, "e": 23873, "s": 23777, "text": "The response time of the OS needs to be short, since the user submits and waits for the result." }, { "code": null, "e": 24020, "s": 23873, "text": "Real-time systems are usually dedicated, embedded systems. An operating system does the following activities related to real-time system activity." }, { "code": null, "e": 24101, "s": 24020, "text": "In such systems, Operating Systems typically read from and react to sensor data." }, { "code": null, "e": 24216, "s": 24101, "text": "The Operating system must guarantee response to events within fixed periods of time to ensure correct performance." }, { "code": null, "e": 24401, "s": 24216, "text": "A distributed environment refers to multiple independent CPUs or processors in a computer system. An operating system does the following activities related to distributed environment −" }, { "code": null, "e": 24474, "s": 24401, "text": "The OS distributes computation logics among several physical processors." }, { "code": null, "e": 24547, "s": 24474, "text": "The OS distributes computation logics among several physical processors." }, { "code": null, "e": 24644, "s": 24547, "text": "The processors do not share memory or a clock. Instead, each processor has its own local memory." }, { "code": null, "e": 24741, "s": 24644, "text": "The processors do not share memory or a clock. Instead, each processor has its own local memory." }, { "code": null, "e": 24869, "s": 24741, "text": "The OS manages the communications between the processors. They communicate with each other through various communication lines." }, { "code": null, "e": 24997, "s": 24869, "text": "The OS manages the communications between the processors. They communicate with each other through various communication lines." }, { "code": null, "e": 25222, "s": 24997, "text": "Spooling is an acronym for simultaneous peripheral operations on line. Spooling refers to putting data of various I/O jobs in a buffer. This buffer is a special area in memory or hard disk which is accessible to I/O devices." }, { "code": null, "e": 25309, "s": 25222, "text": "An operating system does the following activities related to distributed environment −" }, { "code": null, "e": 25387, "s": 25309, "text": "Handles I/O device data spooling as devices have different data access rates." }, { "code": null, "e": 25465, "s": 25387, "text": "Handles I/O device data spooling as devices have different data access rates." }, { "code": null, "e": 25584, "s": 25465, "text": "Maintains the spooling buffer which provides a waiting station where data can rest while the slower device catches up." }, { "code": null, "e": 25703, "s": 25584, "text": "Maintains the spooling buffer which provides a waiting station where data can rest while the slower device catches up." }, { "code": null, "e": 25969, "s": 25703, "text": "Maintains parallel computation because of spooling process as a computer can perform I/O in parallel fashion. It becomes possible to have the computer read data from a tape, write data to disk and to write out to a tape printer while it is doing its computing task." }, { "code": null, "e": 26235, "s": 25969, "text": "Maintains parallel computation because of spooling process as a computer can perform I/O in parallel fashion. It becomes possible to have the computer read data from a tape, write data to disk and to write out to a tape printer while it is doing its computing task." }, { "code": null, "e": 26294, "s": 26235, "text": "The spooling operation uses a disk as a very large buffer." }, { "code": null, "e": 26398, "s": 26294, "text": "Spooling is capable of overlapping I/O operation for one job with processor operations for another job." }, { "code": null, "e": 26511, "s": 26398, "text": "A process is basically a program in execution. The execution of a process must progress in a sequential fashion." }, { "code": null, "e": 26694, "s": 26511, "text": "To put it in simple terms, we write our computer programs in a text file and when we execute this program, it becomes a process which performs all the tasks mentioned in the program." }, { "code": null, "e": 26908, "s": 26694, "text": "When a program is loaded into the memory and it becomes a process, it can be divided into four sections ─ stack, heap, text and data. The following image shows a simplified layout of a process inside main memory −" }, { "code": null, "e": 26914, "s": 26908, "text": "Stack" }, { "code": null, "e": 27032, "s": 26914, "text": "The process Stack contains the temporary data such as method/function parameters, return address and local variables." }, { "code": null, "e": 27037, "s": 27032, "text": "Heap" }, { "code": null, "e": 27108, "s": 27037, "text": "This is dynamically allocated memory to a process during its run time." }, { "code": null, "e": 27113, "s": 27108, "text": "Text" }, { "code": null, "e": 27239, "s": 27113, "text": "This includes the current activity represented by the value of Program Counter and the contents of the processor's registers." }, { "code": null, "e": 27244, "s": 27239, "text": "Data" }, { "code": null, "e": 27299, "s": 27244, "text": "This section contains the global and static variables." }, { "code": null, "e": 27541, "s": 27299, "text": "A program is a piece of code which may be a single line or millions of lines. A computer program is usually written by a computer programmer in a programming language. For example, here is a simple program written in C programming language −" }, { "code": null, "e": 27620, "s": 27541, "text": "#include <stdio.h>\n\nint main() {\n printf(\"Hello, World! \\n\");\n return 0;\n}" }, { "code": null, "e": 27848, "s": 27620, "text": "A computer program is a collection of instructions that performs a specific task when executed by a computer. When we compare a program with a process, we can conclude that a process is a dynamic instance of a computer program." }, { "code": null, "e": 28030, "s": 27848, "text": "A part of a computer program that performs a well-defined task is known as an algorithm. A collection of computer programs, libraries and related data are referred to as a software." }, { "code": null, "e": 28205, "s": 28030, "text": " When a process executes, it passes through different states. These stages may differ in different operating systems, and the names of these states are also not standardized." }, { "code": null, "e": 28280, "s": 28205, "text": "In general, a process can have one of the following five states at a time." }, { "code": null, "e": 28286, "s": 28280, "text": "Start" }, { "code": null, "e": 28353, "s": 28286, "text": "This is the initial state when a process is first started/created." }, { "code": null, "e": 28359, "s": 28353, "text": "Ready" }, { "code": null, "e": 28671, "s": 28359, "text": "The process is waiting to be assigned to a processor. Ready processes are waiting to have the processor allocated to them by the operating system so that they can run. Process may come into this state after Start state or while running it by but interrupted by the scheduler to assign CPU to some other process." }, { "code": null, "e": 28679, "s": 28671, "text": "Running" }, { "code": null, "e": 28831, "s": 28679, "text": "Once the process has been assigned to a processor by the OS scheduler, the process state is set to running and the processor executes its instructions." }, { "code": null, "e": 28839, "s": 28831, "text": "Waiting" }, { "code": null, "e": 28987, "s": 28839, "text": "Process moves into the waiting state if it needs to wait for a resource, such as waiting for user input, or waiting for a file to become available." }, { "code": null, "e": 29006, "s": 28987, "text": "Terminated or Exit" }, { "code": null, "e": 29175, "s": 29006, "text": "Once the process finishes its execution, or it is terminated by the operating system, it is moved to the terminated state where it waits to be removed from main memory." }, { "code": null, "e": 29424, "s": 29175, "text": "A Process Control Block is a data structure maintained by the Operating System for every process. The PCB is identified by an integer process ID (PID). A PCB keeps all the information needed to keep track of a process as listed below in the table −" }, { "code": null, "e": 29438, "s": 29424, "text": "Process State" }, { "code": null, "e": 29529, "s": 29438, "text": "The current state of the process i.e., whether it is ready, running, waiting, or whatever." }, { "code": null, "e": 29548, "s": 29529, "text": "Process privileges" }, { "code": null, "e": 29611, "s": 29548, "text": "This is required to allow/disallow access to system resources." }, { "code": null, "e": 29622, "s": 29611, "text": "Process ID" }, { "code": null, "e": 29693, "s": 29622, "text": "Unique identification for each of the process in the operating system." }, { "code": null, "e": 29701, "s": 29693, "text": "Pointer" }, { "code": null, "e": 29730, "s": 29701, "text": "A pointer to parent process." }, { "code": null, "e": 29746, "s": 29730, "text": "Program Counter" }, { "code": null, "e": 29847, "s": 29746, "text": "Program Counter is a pointer to the address of the next instruction to be executed for this process." }, { "code": null, "e": 29861, "s": 29847, "text": "CPU registers" }, { "code": null, "e": 29948, "s": 29861, "text": "Various CPU registers where process need to be stored for execution for running state." }, { "code": null, "e": 29975, "s": 29948, "text": "CPU Scheduling Information" }, { "code": null, "e": 30069, "s": 29975, "text": "Process priority and other scheduling information which is required to schedule the process." }, { "code": null, "e": 30099, "s": 30069, "text": "Memory management information" }, { "code": null, "e": 30223, "s": 30099, "text": "This includes the information of page table, memory limits, Segment table depending on memory used by the operating system." }, { "code": null, "e": 30246, "s": 30223, "text": "Accounting information" }, { "code": null, "e": 30338, "s": 30246, "text": "This includes the amount of CPU used for process execution, time limits, execution ID etc." }, { "code": null, "e": 30360, "s": 30338, "text": "IO status information" }, { "code": null, "e": 30422, "s": 30360, "text": "This includes a list of I/O devices allocated to the process." }, { "code": null, "e": 30602, "s": 30422, "text": "The architecture of a PCB is completely dependent on Operating System and may contain different information in different operating systems. Here is a simplified diagram of a PCB −" }, { "code": null, "e": 30707, "s": 30602, "text": "The PCB is maintained for a process throughout its lifetime, and is deleted once the process terminates." }, { "code": null, "e": 30906, "s": 30707, "text": "The process scheduling is the activity of the process manager that handles the removal of the running process from the CPU and the selection of another process on the basis of a particular strategy." }, { "code": null, "e": 31151, "s": 30906, "text": "Process scheduling is an essential part of a Multiprogramming operating systems. Such operating systems allow more than one process to be loaded into the executable memory at a time and the loaded process shares the CPU using time multiplexing." }, { "code": null, "e": 31473, "s": 31151, "text": "The OS maintains all PCBs in Process Scheduling Queues. The OS maintains a separate queue for each of the process states and PCBs of all processes in the same execution state are placed in the same queue. When the state of a process is changed, its PCB is unlinked from its current queue and moved to its new state queue." }, { "code": null, "e": 31556, "s": 31473, "text": "The Operating System maintains the following important process scheduling queues −" }, { "code": null, "e": 31618, "s": 31556, "text": "Job queue − This queue keeps all the processes in the system." }, { "code": null, "e": 31680, "s": 31618, "text": "Job queue − This queue keeps all the processes in the system." }, { "code": null, "e": 31832, "s": 31680, "text": "Ready queue − This queue keeps a set of all processes residing in main memory, ready and waiting to execute. A new process is always put in this queue." }, { "code": null, "e": 31984, "s": 31832, "text": "Ready queue − This queue keeps a set of all processes residing in main memory, ready and waiting to execute. A new process is always put in this queue." }, { "code": null, "e": 32094, "s": 31984, "text": "Device queues − The processes which are blocked due to unavailability of an I/O device constitute this queue." }, { "code": null, "e": 32204, "s": 32094, "text": "Device queues − The processes which are blocked due to unavailability of an I/O device constitute this queue." }, { "code": null, "e": 32498, "s": 32204, "text": "The OS can use different policies to manage each queue (FIFO, Round Robin, Priority, etc.). The OS scheduler determines how to move processes between the ready and run queues which can only have one entry per processor core on the system; in the above diagram, it has been merged with the CPU." }, { "code": null, "e": 32591, "s": 32498, "text": "Two-state process model refers to running and non-running states which are described below −" }, { "code": null, "e": 32599, "s": 32591, "text": "Running" }, { "code": null, "e": 32681, "s": 32599, "text": "When a new process is created, it enters into the system as in the running state." }, { "code": null, "e": 32693, "s": 32681, "text": "Not Running" }, { "code": null, "e": 33145, "s": 32693, "text": "Processes that are not running are kept in queue, waiting for their turn to execute. Each entry in the queue is a pointer to a particular process. Queue is implemented by using linked list. Use of dispatcher is as follows. When a process is interrupted, that process is transferred in the waiting queue. If the process has completed or aborted, the process is discarded. In either case, the dispatcher then selects a process from the queue to execute." }, { "code": null, "e": 33371, "s": 33145, "text": "Schedulers are special system software which handle process scheduling in various ways. Their main task is to select the jobs to be submitted into the system and to decide which process to run. Schedulers are of three types −" }, { "code": null, "e": 33391, "s": 33371, "text": "Long-Term Scheduler" }, { "code": null, "e": 33412, "s": 33391, "text": "Short-Term Scheduler" }, { "code": null, "e": 33434, "s": 33412, "text": "Medium-Term Scheduler" }, { "code": null, "e": 33688, "s": 33434, "text": "It is also called a job scheduler. A long-term scheduler determines which programs are admitted to the system for processing. It selects processes from the queue and loads them into memory for execution. Process loads into the memory for CPU scheduling." }, { "code": null, "e": 34021, "s": 33688, "text": "The primary objective of the job scheduler is to provide a balanced mix of jobs, such as I/O bound and processor bound. It also controls the degree of multiprogramming. If the degree of multiprogramming is stable, then the average rate of process creation must be equal to the average departure rate of processes leaving the system." }, { "code": null, "e": 34249, "s": 34021, "text": "On some systems, the long-term scheduler may not be available or minimal. Time-sharing operating systems have no long term scheduler. When a process changes the state from new to ready, then there is use of long-term scheduler." }, { "code": null, "e": 34562, "s": 34249, "text": "It is also called as CPU scheduler. Its main objective is to increase system performance in accordance with the chosen set of criteria. It is the change of ready state to running state of the process. CPU scheduler selects a process among the processes that are ready to execute and allocates CPU to one of them." }, { "code": null, "e": 34724, "s": 34562, "text": "Short-term schedulers, also known as dispatchers, make the decision of which process to execute next. Short-term schedulers are faster than long-term schedulers." }, { "code": null, "e": 34933, "s": 34724, "text": "Medium-term scheduling is a part of swapping. It removes the processes from the memory. It reduces the degree of multiprogramming. The medium-term scheduler is in-charge of handling the swapped out-processes." }, { "code": null, "e": 35357, "s": 34933, "text": "A running process may become suspended if it makes an I/O request. A suspended processes cannot make any progress towards completion. In this condition, to remove the process from memory and make space for other processes, the suspended process is moved to the secondary storage. This process is called swapping, and the process is said to be swapped out or rolled out. Swapping may be necessary to improve the process mix." }, { "code": null, "e": 35722, "s": 35357, "text": "A context switch is the mechanism to store and restore the state or context of a CPU in Process Control block so that a process execution can be resumed from the same point at a later time. Using this technique, a context switcher enables multiple processes to share a single CPU. Context switching is an essential part of a multitasking operating system features." }, { "code": null, "e": 36062, "s": 35722, "text": "When the scheduler switches the CPU from executing one process to execute another, the state from the current running process is stored into the process control block. After this, the state for the process to run next is loaded from its own PCB and used to set the PC, registers, etc. At that point, the second process can start executing." }, { "code": null, "e": 36367, "s": 36062, "text": "Context switches are computationally intensive since register and memory state must be saved and restored. To avoid the amount of context switching time, some hardware systems employ two or more sets of processor registers. When the process is switched, the following information is stored for later use." }, { "code": null, "e": 36383, "s": 36367, "text": "Program Counter" }, { "code": null, "e": 36406, "s": 36383, "text": "Scheduling information" }, { "code": null, "e": 36436, "s": 36406, "text": "Base and limit register value" }, { "code": null, "e": 36460, "s": 36436, "text": "Currently used register" }, { "code": null, "e": 36474, "s": 36460, "text": "Changed State" }, { "code": null, "e": 36496, "s": 36474, "text": "I/O State information" }, { "code": null, "e": 36519, "s": 36496, "text": "Accounting information" }, { "code": null, "e": 36738, "s": 36519, "text": "A Process Scheduler schedules different processes to be assigned to the CPU based on particular scheduling algorithms. There are six popular process scheduling algorithms which we are going to discuss in this chapter −" }, { "code": null, "e": 36781, "s": 36738, "text": "First-Come, First-Served (FCFS) Scheduling" }, { "code": null, "e": 36816, "s": 36781, "text": "Shortest-Job-Next (SJN) Scheduling" }, { "code": null, "e": 36836, "s": 36816, "text": "Priority Scheduling" }, { "code": null, "e": 36860, "s": 36836, "text": "Shortest Remaining Time" }, { "code": null, "e": 36887, "s": 36860, "text": "Round Robin(RR) Scheduling" }, { "code": null, "e": 36920, "s": 36887, "text": "Multiple-Level Queues Scheduling" }, { "code": null, "e": 37307, "s": 36920, "text": "These algorithms are either non-preemptive or preemptive. Non-preemptive\nalgorithms are designed so that once a process enters the running state, it cannot be preempted until it completes its allotted time, whereas the preemptive scheduling is based on priority where a scheduler may preempt a low priority running process anytime when a high priority process enters into a ready state." }, { "code": null, "e": 37359, "s": 37307, "text": "Jobs are executed on first come, first serve basis." }, { "code": null, "e": 37417, "s": 37359, "text": "It is a non-preemptive, pre-emptive scheduling algorithm." }, { "code": null, "e": 37451, "s": 37417, "text": "Easy to understand and implement." }, { "code": null, "e": 37494, "s": 37451, "text": "Its implementation is based on FIFO queue." }, { "code": null, "e": 37544, "s": 37494, "text": "Poor in performance as average wait time is high." }, { "code": null, "e": 37586, "s": 37544, "text": "Wait time of each process is as follows −" }, { "code": null, "e": 37627, "s": 37586, "text": "Average Wait Time: (0+4+6+13) / 4 = 5.75" }, { "code": null, "e": 37676, "s": 37627, "text": "This is also known as shortest job first, or SJF" }, { "code": null, "e": 37725, "s": 37676, "text": "This is also known as shortest job first, or SJF" }, { "code": null, "e": 37785, "s": 37725, "text": "This is a non-preemptive, pre-emptive scheduling algorithm." }, { "code": null, "e": 37845, "s": 37785, "text": "This is a non-preemptive, pre-emptive scheduling algorithm." }, { "code": null, "e": 37885, "s": 37845, "text": "Best approach to minimize waiting time." }, { "code": null, "e": 37925, "s": 37885, "text": "Best approach to minimize waiting time." }, { "code": null, "e": 38005, "s": 37925, "text": "Easy to implement in Batch systems where required CPU time is known in advance." }, { "code": null, "e": 38085, "s": 38005, "text": "Easy to implement in Batch systems where required CPU time is known in advance." }, { "code": null, "e": 38170, "s": 38085, "text": "Impossible to implement in interactive systems where required CPU time is not known." }, { "code": null, "e": 38255, "s": 38170, "text": "Impossible to implement in interactive systems where required CPU time is not known." }, { "code": null, "e": 38325, "s": 38255, "text": "The processer should know in advance how much time process will take." }, { "code": null, "e": 38395, "s": 38325, "text": "The processer should know in advance how much time process will take." }, { "code": null, "e": 38461, "s": 38395, "text": "Given: Table of processes, and their Arrival time, Execution time" }, { "code": null, "e": 38506, "s": 38461, "text": "Waiting time of each process is as follows −" }, { "code": null, "e": 38560, "s": 38506, "text": "Average Wait Time: (0 + 4 + 12 + 5)/4 = 21 / 4 = 5.25" }, { "code": null, "e": 38677, "s": 38560, "text": "Priority scheduling is a non-preemptive algorithm and one of the most common scheduling algorithms in batch systems." }, { "code": null, "e": 38794, "s": 38677, "text": "Priority scheduling is a non-preemptive algorithm and one of the most common scheduling algorithms in batch systems." }, { "code": null, "e": 38896, "s": 38794, "text": "Each process is assigned a priority. Process with highest priority is to be executed first and so on." }, { "code": null, "e": 38998, "s": 38896, "text": "Each process is assigned a priority. Process with highest priority is to be executed first and so on." }, { "code": null, "e": 39074, "s": 38998, "text": "Processes with same priority are executed on first come first served basis." }, { "code": null, "e": 39150, "s": 39074, "text": "Processes with same priority are executed on first come first served basis." }, { "code": null, "e": 39257, "s": 39150, "text": "Priority can be decided based on memory requirements, time requirements or any other resource requirement." }, { "code": null, "e": 39364, "s": 39257, "text": "Priority can be decided based on memory requirements, time requirements or any other resource requirement." }, { "code": null, "e": 39495, "s": 39364, "text": "Given: Table of processes, and their Arrival time, Execution time, and priority. Here we are considering 1 is the lowest priority." }, { "code": null, "e": 39540, "s": 39495, "text": "Waiting time of each process is as follows −" }, { "code": null, "e": 39592, "s": 39540, "text": "Average Wait Time: (0 + 10 + 12 + 2)/4 = 24 / 4 = 6" }, { "code": null, "e": 39670, "s": 39592, "text": "Shortest remaining time (SRT) is the preemptive version of the SJN algorithm." }, { "code": null, "e": 39748, "s": 39670, "text": "Shortest remaining time (SRT) is the preemptive version of the SJN algorithm." }, { "code": null, "e": 39886, "s": 39748, "text": "The processor is allocated to the job closest to completion but it can be preempted by a newer ready job with shorter time to completion." }, { "code": null, "e": 40024, "s": 39886, "text": "The processor is allocated to the job closest to completion but it can be preempted by a newer ready job with shorter time to completion." }, { "code": null, "e": 40109, "s": 40024, "text": "Impossible to implement in interactive systems where required CPU time is not known." }, { "code": null, "e": 40194, "s": 40109, "text": "Impossible to implement in interactive systems where required CPU time is not known." }, { "code": null, "e": 40275, "s": 40194, "text": "It is often used in batch environments where short jobs need to give preference." }, { "code": null, "e": 40356, "s": 40275, "text": "It is often used in batch environments where short jobs need to give preference." }, { "code": null, "e": 40416, "s": 40356, "text": "Round Robin is the preemptive process scheduling algorithm." }, { "code": null, "e": 40476, "s": 40416, "text": "Round Robin is the preemptive process scheduling algorithm." }, { "code": null, "e": 40548, "s": 40476, "text": "Each process is provided a fix time to execute, it is called a quantum." }, { "code": null, "e": 40620, "s": 40548, "text": "Each process is provided a fix time to execute, it is called a quantum." }, { "code": null, "e": 40740, "s": 40620, "text": "Once a process is executed for a given time period, it is preempted and other process executes for a given time period." }, { "code": null, "e": 40860, "s": 40740, "text": "Once a process is executed for a given time period, it is preempted and other process executes for a given time period." }, { "code": null, "e": 40925, "s": 40860, "text": "Context switching is used to save states of preempted processes." }, { "code": null, "e": 40990, "s": 40925, "text": "Context switching is used to save states of preempted processes." }, { "code": null, "e": 41032, "s": 40990, "text": "Wait time of each process is as follows −" }, { "code": null, "e": 41073, "s": 41032, "text": "Average Wait Time: (9+2+12+11) / 4 = 8.5" }, { "code": null, "e": 41239, "s": 41073, "text": "Multiple-level queues are not an independent scheduling algorithm. They make use of other existing algorithms to group and schedule jobs with common characteristics." }, { "code": null, "e": 41313, "s": 41239, "text": "Multiple queues are maintained for processes with common characteristics." }, { "code": null, "e": 41364, "s": 41313, "text": "Each queue can have its own scheduling algorithms." }, { "code": null, "e": 41403, "s": 41364, "text": "Priorities are assigned to each queue." }, { "code": null, "e": 41644, "s": 41403, "text": "For example, CPU-bound jobs can be scheduled in one queue and all I/O-bound jobs in another queue. The Process Scheduler then alternately selects jobs from each queue and assigns them to the CPU based on the algorithm assigned to the queue." }, { "code": null, "e": 41895, "s": 41644, "text": "A thread is a flow of execution through the process code, with its own program counter that keeps track of which instruction to execute next, system registers which hold its current working variables, and a stack which contains the execution history." }, { "code": null, "e": 42076, "s": 41895, "text": "A thread shares with its peer threads few information like code segment, data segment and open files. When one thread alters a code segment memory item, all other threads see that." }, { "code": null, "e": 42354, "s": 42076, "text": "A thread is also called a lightweight process. Threads provide a way to improve application performance through parallelism. Threads represent a software approach to improving performance of operating system by reducing the overhead thread is equivalent to a classical process." }, { "code": null, "e": 42777, "s": 42354, "text": "Each thread belongs to exactly one process and no thread can exist outside a process. Each thread represents a separate flow of control. Threads have been successfully used in implementing network servers and web server. They also provide a suitable foundation for parallel execution of applications on shared memory multiprocessors. The following figure shows the working of a single-threaded and a multithreaded process." }, { "code": null, "e": 42822, "s": 42777, "text": "Threads minimize the context switching time." }, { "code": null, "e": 42876, "s": 42822, "text": "Use of threads provides concurrency within a process." }, { "code": null, "e": 42901, "s": 42876, "text": "Efficient communication." }, { "code": null, "e": 42961, "s": 42901, "text": "It is more economical to create and context switch threads." }, { "code": null, "e": 43054, "s": 42961, "text": "Threads allow utilization of multiprocessor architectures to a greater scale and efficiency." }, { "code": null, "e": 43102, "s": 43054, "text": "Threads are implemented in following two ways −" }, { "code": null, "e": 43145, "s": 43102, "text": "User Level Threads − User managed threads." }, { "code": null, "e": 43188, "s": 43145, "text": "User Level Threads − User managed threads." }, { "code": null, "e": 43288, "s": 43188, "text": "Kernel Level Threads − Operating System managed threads acting on kernel, an operating system core." }, { "code": null, "e": 43388, "s": 43288, "text": "Kernel Level Threads − Operating System managed threads acting on kernel, an operating system core." }, { "code": null, "e": 43712, "s": 43388, "text": "In this case, the thread management kernel is not aware of the existence of threads. The thread library contains code for creating and destroying threads, for passing message and data between threads, for scheduling thread execution and for saving and restoring thread contexts. The application starts with a single thread." }, { "code": null, "e": 43770, "s": 43712, "text": "Thread switching does not require Kernel mode privileges." }, { "code": null, "e": 43821, "s": 43770, "text": "User level thread can run on any operating system." }, { "code": null, "e": 43886, "s": 43821, "text": "Scheduling can be application specific in the user level thread." }, { "code": null, "e": 43936, "s": 43886, "text": "User level threads are fast to create and manage." }, { "code": null, "e": 43999, "s": 43936, "text": "In a typical operating system, most system calls are blocking." }, { "code": null, "e": 44067, "s": 43999, "text": "Multithreaded application cannot take advantage of multiprocessing." }, { "code": null, "e": 44380, "s": 44067, "text": "In this case, thread management is done by the Kernel. There is no thread management code in the application area. Kernel threads are supported directly by the operating system. Any application can be programmed to be multithreaded. All of the threads within an application are supported within a single process." }, { "code": null, "e": 44708, "s": 44380, "text": "The Kernel maintains context information for the process as a whole and for individuals threads within the process. Scheduling by the Kernel is done on a thread basis. The Kernel performs thread creation, scheduling and management in Kernel space. Kernel threads are generally slower to create and manage than the user threads." }, { "code": null, "e": 44805, "s": 44708, "text": "Kernel can simultaneously schedule multiple threads from the same process on multiple processes." }, { "code": null, "e": 44904, "s": 44805, "text": "If one thread in a process is blocked, the Kernel can schedule another thread of the same process." }, { "code": null, "e": 44953, "s": 44904, "text": "Kernel routines themselves can be multithreaded." }, { "code": null, "e": 45033, "s": 44953, "text": "Kernel threads are generally slower to create and manage than the user threads." }, { "code": null, "e": 45142, "s": 45033, "text": "Transfer of control from one thread to another within the same process requires a mode switch to the Kernel." }, { "code": null, "e": 45498, "s": 45142, "text": "Some operating system provide a combined user level thread and Kernel level thread facility. Solaris is a good example of this combined approach. In a combined system, multiple threads within the same application can run in parallel on multiple processors and a blocking system call need not block the entire process. Multithreading models are three types" }, { "code": null, "e": 45525, "s": 45498, "text": "Many to many relationship." }, { "code": null, "e": 45551, "s": 45525, "text": "Many to one relationship." }, { "code": null, "e": 45576, "s": 45551, "text": "One to one relationship." }, { "code": null, "e": 45689, "s": 45576, "text": "The many-to-many model multiplexes any number of user threads onto an equal or smaller number of kernel threads." }, { "code": null, "e": 46138, "s": 45689, "text": "The following diagram shows the many-to-many threading model where 6 user level threads are multiplexing with 6 kernel level threads. In this model, developers can create as many user threads as necessary and the corresponding Kernel threads can run in parallel on a multiprocessor machine. This model provides the best accuracy on concurrency and when a thread performs a blocking system call, the kernel can schedule another thread for execution." }, { "code": null, "e": 46473, "s": 46138, "text": "Many-to-one model maps many user level threads to one Kernel-level thread. Thread management is done in user space by the thread library. When thread makes a blocking system call, the entire process will be blocked. Only one thread can access the Kernel at a time, so multiple threads are unable to run in parallel on multiprocessors." }, { "code": null, "e": 46665, "s": 46473, "text": "If the user-level thread libraries are implemented in the operating system in such a way that the system does not support them, then the Kernel threads use the many-to-one relationship modes." }, { "code": null, "e": 46965, "s": 46665, "text": "There is one-to-one relationship of user-level thread to the kernel-level thread. This model provides more concurrency than the many-to-one model. It also allows another thread to run when a thread makes a blocking system call. It supports multiple threads to execute in parallel on microprocessors." }, { "code": null, "e": 47132, "s": 46965, "text": "Disadvantage of this model is that creating user thread requires the corresponding Kernel thread. OS/2, windows NT and windows 2000 use one to one relationship model." }, { "code": null, "e": 47663, "s": 47132, "text": "Memory management is the functionality of an operating system which handles or manages primary memory and moves processes back and forth between main memory and disk during execution. Memory management keeps track of each and every memory location, regardless of either it is allocated to some process or it is free. It checks how much memory is to be allocated to processes. It decides which process will get memory at what time. It tracks whenever some memory gets freed or unallocated and correspondingly it updates the status." }, { "code": null, "e": 47737, "s": 47663, "text": "This tutorial will teach you basic concepts related to Memory Management." }, { "code": null, "e": 48000, "s": 47737, "text": "The process address space is the set of logical addresses that a process references in its code. For example, when 32-bit addressing is in use, addresses can range from 0 to 0x7fffffff; that is, 2^31 possible numbers, for a total theoretical size of 2 gigabytes." }, { "code": null, "e": 48228, "s": 48000, "text": "The operating system takes care of mapping the logical addresses to physical addresses at the time of memory allocation to the program. There are three types of addresses used in a program before and after memory is allocated −" }, { "code": null, "e": 48247, "s": 48228, "text": "Symbolic addresses" }, { "code": null, "e": 48392, "s": 48247, "text": "The addresses used in a source code. The variable names, constants, and instruction labels are the basic elements of the symbolic address space." }, { "code": null, "e": 48411, "s": 48392, "text": "Relative addresses" }, { "code": null, "e": 48503, "s": 48411, "text": "At the time of compilation, a compiler converts symbolic addresses into relative\naddresses." }, { "code": null, "e": 48522, "s": 48503, "text": "Physical addresses" }, { "code": null, "e": 48614, "s": 48522, "text": "The loader generates these addresses at the time when a program is loaded into main memory." }, { "code": null, "e": 48793, "s": 48614, "text": "Virtual and physical addresses are the same in compile-time and load-time address-binding schemes. Virtual and physical addresses differ in execution-time address-binding scheme." }, { "code": null, "e": 49011, "s": 48793, "text": "The set of all logical addresses generated by a program is referred to as a logical address space. The set of all physical addresses corresponding to these logical addresses is referred to as a physical address space." }, { "code": null, "e": 49213, "s": 49011, "text": "The runtime mapping from virtual to physical address is done by the memory management unit (MMU) which is a hardware device. MMU uses following mechanism to convert virtual address to physical address." }, { "code": null, "e": 49517, "s": 49213, "text": "The value in the base register is added to every address generated by a user process, which is treated as offset at the time it is sent to memory. For example, if the base register value is 10000, then an attempt by the user to use address location 100 will be dynamically reallocated to location 10100." }, { "code": null, "e": 49821, "s": 49517, "text": "The value in the base register is added to every address generated by a user process, which is treated as offset at the time it is sent to memory. For example, if the base register value is 10000, then an attempt by the user to use address location 100 will be dynamically reallocated to location 10100." }, { "code": null, "e": 49911, "s": 49821, "text": "The user program deals with virtual addresses; it never sees the real physical addresses." }, { "code": null, "e": 50001, "s": 49911, "text": "The user program deals with virtual addresses; it never sees the real physical addresses." }, { "code": null, "e": 50436, "s": 50001, "text": "The choice between Static or Dynamic Loading is to be made at the time of computer program being developed. If you have to load your program statically, then at the time of compilation, the complete programs will be compiled and linked without leaving any external program or module dependency. The linker combines the object program with other necessary object modules into an absolute program, which also includes logical addresses." }, { "code": null, "e": 50685, "s": 50436, "text": "If you are writing a Dynamically loaded program, then your compiler will compile the program and for all the modules which you want to include dynamically, only references will be provided and rest of the work will be done at the time of execution." }, { "code": null, "e": 50817, "s": 50685, "text": "At the time of loading, with static loading, the absolute program (and data) is loaded into memory in order for execution to start." }, { "code": null, "e": 50993, "s": 50817, "text": "If you are using dynamic loading, dynamic routines of the library are stored on a disk in relocatable form and are loaded into memory only when they are needed by the program." }, { "code": null, "e": 51166, "s": 50993, "text": "As explained above, when static linking is used, the linker combines all other modules needed by a program into a single executable program to avoid any runtime dependency." }, { "code": null, "e": 51470, "s": 51166, "text": "When dynamic linking is used, it is not required to link the actual module or library with the program, rather a reference to the dynamic module is provided at the time of compilation and linking. Dynamic Link Libraries (DLL) in Windows and Shared Objects in Unix are good examples of dynamic libraries." }, { "code": null, "e": 51745, "s": 51470, "text": "Swapping is a mechanism in which a process can be swapped temporarily out of main memory (or move) to secondary storage (disk) and make that memory available to other processes. At some later time, the system swaps back the process from the secondary storage to main memory." }, { "code": null, "e": 51950, "s": 51745, "text": "Though performance is usually affected by swapping process but it helps in running multiple and big processes in parallel and that's the reason Swapping is also known as a technique for memory compaction." }, { "code": null, "e": 52171, "s": 51950, "text": "The total time taken by swapping process includes the time it takes to move the entire process to a secondary disk and then to copy the process back to memory, as well as the time the process takes to regain main memory." }, { "code": null, "e": 52402, "s": 52171, "text": "Let us assume that the user process is of size 2048KB and on a standard hard disk where swapping will take place has a data transfer rate around 1 MB per second. The actual transfer of the 1000K process to or from memory will take" }, { "code": null, "e": 52462, "s": 52402, "text": "2048KB / 1024KB per second\n= 2 seconds\n= 2000 milliseconds\n" }, { "code": null, "e": 52605, "s": 52462, "text": "Now considering in and out time, it will take complete 4000 milliseconds plus other overhead where the process competes to regain main memory." }, { "code": null, "e": 52646, "s": 52605, "text": "Main memory usually has two partitions −" }, { "code": null, "e": 52700, "s": 52646, "text": "Low Memory − Operating system resides in this memory." }, { "code": null, "e": 52754, "s": 52700, "text": "Low Memory − Operating system resides in this memory." }, { "code": null, "e": 52808, "s": 52754, "text": "High Memory − User processes are held in high memory." }, { "code": null, "e": 52862, "s": 52808, "text": "High Memory − User processes are held in high memory." }, { "code": null, "e": 52927, "s": 52862, "text": "Operating system uses the following memory allocation mechanism." }, { "code": null, "e": 52955, "s": 52927, "text": "Single-partition allocation" }, { "code": null, "e": 53294, "s": 52955, "text": "In this type of allocation, relocation-register scheme is used to protect user processes from each other, and from changing operating-system code and data. Relocation register contains value of smallest physical address whereas limit register contains range of logical addresses. Each logical address must be less than the limit register." }, { "code": null, "e": 53324, "s": 53294, "text": "Multiple-partition allocation" }, { "code": null, "e": 53659, "s": 53324, "text": "In this type of allocation, main memory is divided into a number of fixed-sized\npartitions where each partition should contain only one process. When a partition\nis free, a process is selected from the input queue and is loaded into the free\npartition. When the process terminates, the partition becomes available for\nanother process." }, { "code": null, "e": 53942, "s": 53659, "text": "As processes are loaded and removed from memory, the free memory space is broken into little pieces. It happens after sometimes that processes cannot be allocated to memory blocks considering their small size and memory blocks remains unused. This problem is known as Fragmentation." }, { "code": null, "e": 53974, "s": 53942, "text": "Fragmentation is of two types −" }, { "code": null, "e": 53997, "s": 53974, "text": "External fragmentation" }, { "code": null, "e": 54125, "s": 53997, "text": "Total memory space is enough to satisfy a request or to reside a process in it, but it is not contiguous, so it cannot be used." }, { "code": null, "e": 54148, "s": 54125, "text": "Internal fragmentation" }, { "code": null, "e": 54272, "s": 54148, "text": "Memory block assigned to process is bigger. Some portion of memory is left unused, as it cannot be used by another process." }, { "code": null, "e": 54437, "s": 54272, "text": "The following diagram shows how fragmentation can cause waste of memory and a compaction technique can be used to create more free memory out of fragmented memory −" }, { "code": null, "e": 54629, "s": 54437, "text": "External fragmentation can be reduced by compaction or shuffle memory contents to place all free memory together in one large block. To make compaction feasible, relocation should be dynamic." }, { "code": null, "e": 54753, "s": 54629, "text": "The internal fragmentation can be reduced by effectively assigning the smallest partition but large enough for the process." }, { "code": null, "e": 55040, "s": 54753, "text": "A computer can address more memory than the amount physically installed on the system. This extra memory is actually called virtual memory and it is a section of a hard that's set up to emulate the computer's RAM. Paging technique plays an important role in implementing virtual memory." }, { "code": null, "e": 55279, "s": 55040, "text": "Paging is a memory management technique in which process address space is broken into blocks of the same size called pages (size is power of 2, between 512 bytes and 8192 bytes). The size of the process is measured in the number of pages." }, { "code": null, "e": 55521, "s": 55279, "text": "Similarly, main memory is divided into small fixed-sized blocks of (physical) memory called frames and the size of a frame is kept the same as that of a page to have optimum utilization of the main memory and to avoid external fragmentation." }, { "code": null, "e": 55607, "s": 55521, "text": "Page address is called logical address and represented by page number and the offset." }, { "code": null, "e": 55652, "s": 55607, "text": "Logical Address = Page number + page offset\n" }, { "code": null, "e": 55743, "s": 55652, "text": "Frame address is called physical address and represented by a frame number and the offset." }, { "code": null, "e": 55790, "s": 55743, "text": "Physical Address = Frame number + page offset\n" }, { "code": null, "e": 55926, "s": 55790, "text": "A data structure called page map table is used to keep track of the relation between a page of a process to a frame in physical memory." }, { "code": null, "e": 56117, "s": 55926, "text": "When the system allocates a frame to any page, it translates this logical address into a physical address and create entry into the page table to be used throughout execution of the program." }, { "code": null, "e": 56575, "s": 56117, "text": "When a process is to be executed, its corresponding pages are loaded into any available memory frames. Suppose you have a program of 8Kb but your memory can accommodate only 5Kb at a given point in time, then the paging concept will come into picture. When a computer runs out of RAM, the operating system (OS) will move idle or unwanted pages of memory to secondary memory to free up RAM for other processes and brings them back when needed by the program." }, { "code": null, "e": 56791, "s": 56575, "text": "This process continues during the whole execution of the program where the OS keeps removing idle pages from the main memory and write them onto the secondary memory and bring them back when required by the program." }, { "code": null, "e": 56850, "s": 56791, "text": "Here is a list of advantages and disadvantages of paging −" }, { "code": null, "e": 56935, "s": 56850, "text": "Paging reduces external fragmentation, but still suffer from internal fragmentation." }, { "code": null, "e": 57020, "s": 56935, "text": "Paging reduces external fragmentation, but still suffer from internal fragmentation." }, { "code": null, "e": 57107, "s": 57020, "text": "Paging is simple to implement and assumed as an efficient memory management technique." }, { "code": null, "e": 57194, "s": 57107, "text": "Paging is simple to implement and assumed as an efficient memory management technique." }, { "code": null, "e": 57265, "s": 57194, "text": "Due to equal size of the pages and frames, swapping becomes very easy." }, { "code": null, "e": 57336, "s": 57265, "text": "Due to equal size of the pages and frames, swapping becomes very easy." }, { "code": null, "e": 57426, "s": 57336, "text": "Page table requires extra memory space, so may not be good for a system having small RAM." }, { "code": null, "e": 57516, "s": 57426, "text": "Page table requires extra memory space, so may not be good for a system having small RAM." }, { "code": null, "e": 57781, "s": 57516, "text": "Segmentation is a memory management technique in which each job is divided into several segments of different sizes, one for each module that contains pieces that perform related functions. Each segment is actually a different logical address space of the program." }, { "code": null, "e": 57960, "s": 57781, "text": "When a process is to be executed, its corresponding segmentation are loaded into non-contiguous memory though every segment is loaded into a contiguous block of available memory." }, { "code": null, "e": 58105, "s": 57960, "text": "Segmentation memory management works very similar to paging but here segments are of variable-length where as in paging pages are of fixed size." }, { "code": null, "e": 58593, "s": 58105, "text": "A program segment contains the program's main function, utility functions, data structures, and so on. The operating system maintains a segment map table for every process and a list of free memory blocks along with segment numbers, their size and corresponding memory locations in main memory. For each segment, the table stores the starting address of the segment and the length of the segment. A reference to a memory location includes a value that identifies a segment and an offset." }, { "code": null, "e": 58812, "s": 58593, "text": "A computer can address more memory than the amount physically installed on the system. This extra memory is actually called virtual memory and it is a section of a hard disk that's set up to emulate the computer's RAM." }, { "code": null, "e": 59129, "s": 58812, "text": "The main visible advantage of this scheme is that programs can be larger than physical memory. Virtual memory serves two purposes. First, it allows us to extend the use of physical memory by using disk. Second, it allows us to have memory protection, because each virtual address is translated to a physical address." }, { "code": null, "e": 59230, "s": 59129, "text": "Following are the situations, when entire program is not required to be loaded fully in main memory." }, { "code": null, "e": 59332, "s": 59230, "text": "User written error handling routines are used only when an error occurred in the data or computation." }, { "code": null, "e": 59434, "s": 59332, "text": "User written error handling routines are used only when an error occurred in the data or computation." }, { "code": null, "e": 59496, "s": 59434, "text": "Certain options and features of a program may be used rarely." }, { "code": null, "e": 59558, "s": 59496, "text": "Certain options and features of a program may be used rarely." }, { "code": null, "e": 59678, "s": 59558, "text": "Many tables are assigned a fixed amount of address space even though only a small amount of the table is actually used." }, { "code": null, "e": 59798, "s": 59678, "text": "Many tables are assigned a fixed amount of address space even though only a small amount of the table is actually used." }, { "code": null, "e": 59893, "s": 59798, "text": "The ability to execute a program that is only partially in memory would counter many benefits." }, { "code": null, "e": 59988, "s": 59893, "text": "The ability to execute a program that is only partially in memory would counter many benefits." }, { "code": null, "e": 60070, "s": 59988, "text": "Less number of I/O would be needed to load or swap each user program into memory." }, { "code": null, "e": 60152, "s": 60070, "text": "Less number of I/O would be needed to load or swap each user program into memory." }, { "code": null, "e": 60245, "s": 60152, "text": "A program would no longer be constrained by the amount of physical memory that is available." }, { "code": null, "e": 60338, "s": 60245, "text": "A program would no longer be constrained by the amount of physical memory that is available." }, { "code": null, "e": 60496, "s": 60338, "text": "Each user program could take less physical memory, more programs could be run the same time, with a corresponding increase in CPU utilization and throughput." }, { "code": null, "e": 60654, "s": 60496, "text": "Each user program could take less physical memory, more programs could be run the same time, with a corresponding increase in CPU utilization and throughput." }, { "code": null, "e": 60879, "s": 60654, "text": "Modern microprocessors intended for general-purpose use, a memory management unit, or MMU, is built into the hardware. The MMU's job is to translate virtual addresses into physical addresses. A basic example is given below −" }, { "code": null, "e": 61053, "s": 60879, "text": "Virtual memory is commonly implemented by demand paging. It can also be implemented in a segmentation system. Demand segmentation can also be used to provide virtual memory." }, { "code": null, "e": 61525, "s": 61053, "text": "A demand paging system is quite similar to a paging system with swapping where processes reside in secondary memory and pages are loaded only on demand, not in advance. When a context switch occurs, the operating system does not copy any of the old program’s pages out to the disk or any of the new program’s pages into the main memory Instead, it just begins executing the new program after loading the first page and fetches that program’s pages as they are referenced." }, { "code": null, "e": 61839, "s": 61525, "text": "While executing a program, if the program references a page which is not available in the main memory because it was swapped out a little ago, the processor treats this invalid memory reference as a page fault and transfers control from the program to the operating system to demand the page back into the memory." }, { "code": null, "e": 61887, "s": 61839, "text": "Following are the advantages of Demand Paging −" }, { "code": null, "e": 61909, "s": 61887, "text": "Large virtual memory." }, { "code": null, "e": 61939, "s": 61909, "text": "More efficient use of memory." }, { "code": null, "e": 61988, "s": 61939, "text": "There is no limit on degree of multiprogramming." }, { "code": null, "e": 62143, "s": 61988, "text": "Number of tables and the amount of processor overhead for handling page interrupts are greater than in the case of the simple paged management techniques." }, { "code": null, "e": 62298, "s": 62143, "text": "Number of tables and the amount of processor overhead for handling page interrupts are greater than in the case of the simple paged management techniques." }, { "code": null, "e": 62682, "s": 62298, "text": "Page replacement algorithms are the techniques using which an Operating System decides which memory pages to swap out, write to disk when a page of memory needs to be allocated. Paging happens whenever a page fault occurs and a free page cannot be used for allocation purpose accounting to reason that pages are not available or the number of free pages is lower than required pages." }, { "code": null, "e": 62979, "s": 62682, "text": "When the page that was selected for replacement and was paged out, is referenced again, it has to read in from disk, and this requires for I/O completion. This process determines the quality of the page replacement algorithm: the lesser the time waiting for page-ins, the better is the algorithm." }, { "code": null, "e": 63459, "s": 62979, "text": "A page replacement algorithm looks at the limited information about accessing the pages provided by hardware, and tries to select which pages should be replaced to minimize the total number of page misses, while balancing it with the costs of primary storage and processor time of the algorithm itself. There are many different page replacement algorithms. We evaluate an algorithm by running it on a particular string of memory reference and computing the number of page faults," }, { "code": null, "e": 63722, "s": 63459, "text": "The string of memory references is called reference string. Reference strings are generated artificially or by tracing a given system and recording the address of each memory reference. The latter choice produces a large number of data, where we note two things." }, { "code": null, "e": 63811, "s": 63722, "text": "For a given page size, we need to consider only the page number, not the entire address." }, { "code": null, "e": 63900, "s": 63811, "text": "For a given page size, we need to consider only the page number, not the entire address." }, { "code": null, "e": 64124, "s": 63900, "text": "If we have a reference to a page p, then any immediately following references to page p will never cause a page fault. Page p will be in memory after the first reference; the immediately following references will not fault." }, { "code": null, "e": 64348, "s": 64124, "text": "If we have a reference to a page p, then any immediately following references to page p will never cause a page fault. Page p will be in memory after the first reference; the immediately following references will not fault." }, { "code": null, "e": 64431, "s": 64348, "text": "For example, consider the following sequence of addresses − 123,215,600,1234,76,96" }, { "code": null, "e": 64514, "s": 64431, "text": "For example, consider the following sequence of addresses − 123,215,600,1234,76,96" }, { "code": null, "e": 64577, "s": 64514, "text": "If page size is 100, then the reference string is 1,2,6,12,0,0" }, { "code": null, "e": 64640, "s": 64577, "text": "If page size is 100, then the reference string is 1,2,6,12,0,0" }, { "code": null, "e": 64718, "s": 64640, "text": "Oldest page in main memory is the one which will be selected for replacement." }, { "code": null, "e": 64796, "s": 64718, "text": "Oldest page in main memory is the one which will be selected for replacement." }, { "code": null, "e": 64887, "s": 64796, "text": "Easy to implement, keep a list, replace pages from the tail and add new pages at the head." }, { "code": null, "e": 64978, "s": 64887, "text": "Easy to implement, keep a list, replace pages from the tail and add new pages at the head." }, { "code": null, "e": 65144, "s": 64978, "text": "An optimal page-replacement algorithm has the lowest page-fault rate of all algorithms. An optimal page-replacement algorithm exists, and has been called OPT or MIN." }, { "code": null, "e": 65310, "s": 65144, "text": "An optimal page-replacement algorithm has the lowest page-fault rate of all algorithms. An optimal page-replacement algorithm exists, and has been called OPT or MIN." }, { "code": null, "e": 65421, "s": 65310, "text": "Replace the page that will not be used for the longest period of time. Use the time when a page is to be used." }, { "code": null, "e": 65532, "s": 65421, "text": "Replace the page that will not be used for the longest period of time. Use the time when a page is to be used." }, { "code": null, "e": 65648, "s": 65532, "text": "Page which has not been used for the longest time in main memory is the one which will be selected for replacement." }, { "code": null, "e": 65764, "s": 65648, "text": "Page which has not been used for the longest time in main memory is the one which will be selected for replacement." }, { "code": null, "e": 65837, "s": 65764, "text": "Easy to implement, keep a list, replace pages by looking back into time." }, { "code": null, "e": 65910, "s": 65837, "text": "Easy to implement, keep a list, replace pages by looking back into time." }, { "code": null, "e": 65970, "s": 65910, "text": "To get a process start quickly, keep a pool of free frames." }, { "code": null, "e": 66015, "s": 65970, "text": "On page fault, select a page to be replaced." }, { "code": null, "e": 66106, "s": 66015, "text": "Write the new page in the frame of free pool, mark the page table and restart the process." }, { "code": null, "e": 66199, "s": 66106, "text": "Now write the dirty page out of disk and place the frame holding replaced page in free pool." }, { "code": null, "e": 66283, "s": 66199, "text": "The page with the smallest count is the one which will be selected for replacement." }, { "code": null, "e": 66367, "s": 66283, "text": "The page with the smallest count is the one which will be selected for replacement." }, { "code": null, "e": 66510, "s": 66367, "text": "This algorithm suffers from the situation in which a page is used heavily during the initial phase of a process, but then is never used again." }, { "code": null, "e": 66653, "s": 66510, "text": "This algorithm suffers from the situation in which a page is used heavily during the initial phase of a process, but then is never used again." }, { "code": null, "e": 66784, "s": 66653, "text": "This algorithm is based on the argument that the page with the smallest count was probably just brought in and has yet to be used." }, { "code": null, "e": 66915, "s": 66784, "text": "This algorithm is based on the argument that the page with the smallest count was probably just brought in and has yet to be used." }, { "code": null, "e": 67194, "s": 66915, "text": "One of the important jobs of an Operating System is to manage various I/O devices including mouse, keyboards, touch pad, disk drives, display adapters, USB devices, Bit-mapped screen, LED, Analog-to-digital converter, On/off switch, network connections, audio I/O, printers etc." }, { "code": null, "e": 67427, "s": 67194, "text": "An I/O system is required to take an application I/O request and send it to the physical device, then take whatever response comes back from the device and send it to the application. I/O devices can be divided into two categories −" }, { "code": null, "e": 67589, "s": 67427, "text": "Block devices − A block device is one with which the driver communicates by sending entire blocks of data. For example, Hard disks, USB cameras, Disk-On-Key etc." }, { "code": null, "e": 67751, "s": 67589, "text": "Block devices − A block device is one with which the driver communicates by sending entire blocks of data. For example, Hard disks, USB cameras, Disk-On-Key etc." }, { "code": null, "e": 67952, "s": 67751, "text": "Character devices − A character device is one with which the driver communicates by sending and receiving single characters (bytes, octets). For example, serial ports, parallel ports, sounds cards etc" }, { "code": null, "e": 68153, "s": 67952, "text": "Character devices − A character device is one with which the driver communicates by sending and receiving single characters (bytes, octets). For example, serial ports, parallel ports, sounds cards etc" }, { "code": null, "e": 68326, "s": 68153, "text": "Device drivers are software modules that can be plugged into an OS to handle a particular device. Operating System takes help from device drivers to handle all I/O devices." }, { "code": null, "e": 68585, "s": 68326, "text": "The Device Controller works like an interface between a device and a device driver. I/O units (Keyboard, mouse, printer, etc.) typically consist of a mechanical component and an electronic component where electronic component is called the device controller." }, { "code": null, "e": 68880, "s": 68585, "text": "There is always a device controller and a device driver for each device to communicate with the Operating Systems. A device controller may be able to handle multiple devices. As an interface its main task is to convert serial bit stream to block of bytes, perform error correction as necessary." }, { "code": null, "e": 69159, "s": 68880, "text": "Any device connected to the computer is connected by a plug and socket, and the socket is connected to a device controller. Following is a model for connecting the CPU, memory, controllers, and I/O devices where CPU and device controllers all use a common bus for communication." }, { "code": null, "e": 69231, "s": 69159, "text": "Synchronous I/O − In this scheme CPU execution waits while I/O proceeds" }, { "code": null, "e": 69303, "s": 69231, "text": "Synchronous I/O − In this scheme CPU execution waits while I/O proceeds" }, { "code": null, "e": 69367, "s": 69303, "text": "Asynchronous I/O − I/O proceeds concurrently with CPU execution" }, { "code": null, "e": 69431, "s": 69367, "text": "Asynchronous I/O − I/O proceeds concurrently with CPU execution" }, { "code": null, "e": 69579, "s": 69431, "text": "The CPU must have a way to pass information to and from an I/O device. There are three approaches available to communicate with the CPU and Device." }, { "code": null, "e": 69603, "s": 69579, "text": "Special Instruction I/O" }, { "code": null, "e": 69621, "s": 69603, "text": "Memory-mapped I/O" }, { "code": null, "e": 69648, "s": 69621, "text": "Direct memory access (DMA)" }, { "code": null, "e": 69827, "s": 69648, "text": "This uses CPU instructions that are specifically made for controlling I/O devices. These instructions typically allow data to be sent to an I/O device or read from an I/O device." }, { "code": null, "e": 70071, "s": 69827, "text": "When using memory-mapped I/O, the same address space is shared by memory and I/O devices. The device is connected directly to certain main memory locations so that I/O device can transfer block of data to/from memory without going through CPU." }, { "code": null, "e": 70273, "s": 70071, "text": "While using memory mapped IO, OS allocates buffer in memory and informs I/O device to use that buffer to send data to the CPU. I/O device operates asynchronously with CPU, interrupts CPU when finished." }, { "code": null, "e": 70488, "s": 70273, "text": "The advantage to this method is that every instruction which can access memory can be used to manipulate an I/O device. Memory mapped IO is used for most high-speed I/O devices like disks, communication interfaces." }, { "code": null, "e": 70826, "s": 70488, "text": "Slow devices like keyboards will generate an interrupt to the main CPU after each byte is transferred. If a fast device such as a disk generated an interrupt for each byte, the operating system would spend most of its time handling these interrupts. So a typical computer uses direct memory access (DMA) hardware to reduce this overhead." }, { "code": null, "e": 71152, "s": 70826, "text": "Direct Memory Access (DMA) means CPU grants I/O module authority to read from or write to memory without involvement. DMA module itself controls exchange of data between main memory and the I/O device. CPU is only involved at the beginning and end of the transfer and interrupted only after entire block has been transferred." }, { "code": null, "e": 71544, "s": 71152, "text": "Direct Memory Access needs a special hardware called DMA controller (DMAC) that manages the data transfers and arbitrates access to the system bus. The controllers are programmed with source and destination pointers (where to read/write the data), counters to track the number of transferred bytes, and settings, which includes I/O and memory types, interrupts and states for the CPU cycles." }, { "code": null, "e": 71600, "s": 71544, "text": "The operating system uses the DMA hardware as follows −" }, { "code": null, "e": 71906, "s": 71600, "text": "A computer must have a way of detecting the arrival of any type of input. There are two ways that this can happen, known as polling and interrupts. Both of these techniques allow the processor to deal with events that can happen at any time and that are not related to the process it is currently running." }, { "code": null, "e": 72231, "s": 71906, "text": "Polling is the simplest way for an I/O device to communicate with the processor. The process of periodically checking status of the device to see if it is time for the next I/O operation, is called polling. The I/O device simply puts the information in a Status register, and the processor must come and get the information." }, { "code": null, "e": 72471, "s": 72231, "text": "Most of the time, devices will not require attention and when one does it will have to wait until it is next interrogated by the polling program. This is an inefficient method and much of the processors time is wasted on unnecessary polls." }, { "code": null, "e": 72702, "s": 72471, "text": "Compare this method to a teacher continually asking every student in a class, one after another, if they need help. Obviously the more efficient method would be for a student to inform the teacher whenever they require assistance." }, { "code": null, "e": 72863, "s": 72702, "text": "An alternative scheme for dealing with I/O is the interrupt-driven method. An interrupt is a signal to the microprocessor from a device that requires attention." }, { "code": null, "e": 73262, "s": 72863, "text": "A device controller puts an interrupt signal on the bus when it needs CPU’s attention when CPU receives an interrupt, It saves its current state and invokes the appropriate interrupt handler using the interrupt vector (addresses of OS routines to handle various events). When the interrupting device has been dealt with, the CPU continues with its original task as if it had never been interrupted." }, { "code": null, "e": 73320, "s": 73262, "text": "I/O software is often organized in the following layers −" }, { "code": null, "e": 73500, "s": 73320, "text": "User Level Libraries − This provides simple interface to the user program to perform input and output. For example, stdio is a library provided by C and C++ programming languages." }, { "code": null, "e": 73680, "s": 73500, "text": "User Level Libraries − This provides simple interface to the user program to perform input and output. For example, stdio is a library provided by C and C++ programming languages." }, { "code": null, "e": 73833, "s": 73680, "text": "Kernel Level Modules − This provides device driver to interact with the device controller and device independent I/O modules used by the device drivers." }, { "code": null, "e": 73986, "s": 73833, "text": "Kernel Level Modules − This provides device driver to interact with the device controller and device independent I/O modules used by the device drivers." }, { "code": null, "e": 74122, "s": 73986, "text": "Hardware − This layer includes actual hardware and hardware controller which interact with the device drivers and makes hardware alive." }, { "code": null, "e": 74258, "s": 74122, "text": "Hardware − This layer includes actual hardware and hardware controller which interact with the device drivers and makes hardware alive." }, { "code": null, "e": 74662, "s": 74258, "text": "A key concept in the design of I/O software is that it should be device independent where it should be possible to write programs that can access any I/O device without having to specify the device in advance. For example, a program that reads a file as input should be able to read a file on a floppy disk, on a hard disk, or on a CD-ROM, without having to modify the program for each different device." }, { "code": null, "e": 75105, "s": 74662, "text": "Device drivers are software modules that can be plugged into an OS to handle a particular device. Operating System takes help from device drivers to handle all I/O devices. Device drivers encapsulate device-dependent code and implement a standard interface in such a way that code contains device-specific register reads/writes. Device driver, is generally written by the device's manufacturer and delivered along with the device on a CD-ROM." }, { "code": null, "e": 75151, "s": 75105, "text": "A device driver performs the following jobs −" }, { "code": null, "e": 75219, "s": 75151, "text": "To accept request from the device independent software above to it." }, { "code": null, "e": 75312, "s": 75219, "text": "Interact with the device controller to take and give I/O and perform required error handling" }, { "code": null, "e": 75366, "s": 75312, "text": "Making sure that the request is executed successfully" }, { "code": null, "e": 75689, "s": 75366, "text": "How a device driver handles a request is as follows: Suppose a request comes to read a block N. If the driver is idle at the time a request arrives, it starts carrying out the request immediately. Otherwise, if the driver is already busy with some other request, it places the new request in the queue of pending requests." }, { "code": null, "e": 75953, "s": 75689, "text": "An interrupt handler, also known as an interrupt service routine or ISR, is a piece of software or more specifically a callback function in an operating system or more specifically in a device driver, whose execution is triggered by the reception of an interrupt." }, { "code": null, "e": 76153, "s": 75953, "text": "When the interrupt happens, the interrupt procedure does whatever it has to in order to handle the interrupt, updates data structures and wakes up process that was waiting for an interrupt to happen." }, { "code": null, "e": 76464, "s": 76153, "text": "The interrupt mechanism accepts an address ─ a number that selects a specific interrupt handling routine/function from a small set. In most architectures, this address is an offset stored in a table called the interrupt vector table. This vector contains the memory addresses of specialized interrupt handlers." }, { "code": null, "e": 76855, "s": 76464, "text": "The basic function of the device-independent software is to perform the I/O functions that are common to all devices and to provide a uniform interface to the user-level software. Though it is difficult to write completely device independent software but we can write some modules which are common among all the devices. Following is a list of functions of device-independent I/O Software −" }, { "code": null, "e": 76894, "s": 76855, "text": "Uniform interfacing for device drivers" }, { "code": null, "e": 76966, "s": 76894, "text": "Device naming - Mnemonic names mapped to Major and Minor device numbers" }, { "code": null, "e": 76984, "s": 76966, "text": "Device protection" }, { "code": null, "e": 77026, "s": 76984, "text": "Providing a device-independent block size" }, { "code": null, "e": 77108, "s": 77026, "text": "Buffering because data coming off a device cannot be stored in final destination." }, { "code": null, "e": 77144, "s": 77108, "text": "Storage allocation on block devices" }, { "code": null, "e": 77187, "s": 77144, "text": "Allocation and releasing dedicated devices" }, { "code": null, "e": 77203, "s": 77187, "text": "Error Reporting" }, { "code": null, "e": 77557, "s": 77203, "text": "These are the libraries which provide richer and simplified interface to access the functionality of the kernel or ultimately interactive with the device drivers. Most of the user-level I/O software consists of library procedures with some exception like spooling system which is a way of dealing with dedicated I/O devices in a multiprogramming system." }, { "code": null, "e": 77800, "s": 77557, "text": "I/O Libraries (e.g., stdio) are in user-space to provide an interface to the OS resident device-independent I/O SW. For example putchar(), getchar(), printf() and scanf() are example of user level I/O library stdio available in C programming." }, { "code": null, "e": 77922, "s": 77800, "text": "Kernel I/O Subsystem is responsible to provide many services related to I/O. Following are some of the services provided." }, { "code": null, "e": 78296, "s": 77922, "text": "Scheduling − Kernel schedules a set of I/O requests to determine a good order in which to execute them. When an application issues a blocking I/O system call, the request is placed on the queue for that device. The Kernel I/O scheduler rearranges the order of the queue to improve the overall system efficiency and the average response time experienced by the applications." }, { "code": null, "e": 78670, "s": 78296, "text": "Scheduling − Kernel schedules a set of I/O requests to determine a good order in which to execute them. When an application issues a blocking I/O system call, the request is placed on the queue for that device. The Kernel I/O scheduler rearranges the order of the queue to improve the overall system efficiency and the average response time experienced by the applications." }, { "code": null, "e": 79026, "s": 78670, "text": "Buffering − Kernel I/O Subsystem maintains a memory area known as buffer that stores data while they are transferred between two devices or between a device with an application operation. Buffering is done to cope with a speed mismatch between the producer and consumer of a data stream or to adapt between devices that have different data transfer sizes." }, { "code": null, "e": 79382, "s": 79026, "text": "Buffering − Kernel I/O Subsystem maintains a memory area known as buffer that stores data while they are transferred between two devices or between a device with an application operation. Buffering is done to cope with a speed mismatch between the producer and consumer of a data stream or to adapt between devices that have different data transfer sizes." }, { "code": null, "e": 79553, "s": 79382, "text": "Caching − Kernel maintains cache memory which is region of fast memory that holds copies of data. Access to the cached copy is more efficient than access to the original." }, { "code": null, "e": 79724, "s": 79553, "text": "Caching − Kernel maintains cache memory which is region of fast memory that holds copies of data. Access to the cached copy is more efficient than access to the original." }, { "code": null, "e": 80095, "s": 79724, "text": "Spooling and Device Reservation − A spool is a buffer that holds output for a device, such as a printer, that cannot accept interleaved data streams. The spooling system copies the queued spool files to the printer one at a time. In some operating systems, spooling is managed by a system daemon process. In other operating systems, it is handled by an in kernel thread." }, { "code": null, "e": 80466, "s": 80095, "text": "Spooling and Device Reservation − A spool is a buffer that holds output for a device, such as a printer, that cannot accept interleaved data streams. The spooling system copies the queued spool files to the printer one at a time. In some operating systems, spooling is managed by a system daemon process. In other operating systems, it is handled by an in kernel thread." }, { "code": null, "e": 80595, "s": 80466, "text": "Error Handling − An operating system that uses protected memory can guard against many kinds of hardware and application errors." }, { "code": null, "e": 80724, "s": 80595, "text": "Error Handling − An operating system that uses protected memory can guard against many kinds of hardware and application errors." }, { "code": null, "e": 80994, "s": 80724, "text": "A file is a named collection of related information that is recorded on secondary storage such as magnetic disks, magnetic tapes and optical disks. In general, a file is a sequence of bits, bytes, lines or records whose meaning is defined by the files creator and user." }, { "code": null, "e": 81094, "s": 80994, "text": "A File Structure should be according to a required format that the operating system can understand." }, { "code": null, "e": 81156, "s": 81094, "text": "A file has a certain defined structure according to its type." }, { "code": null, "e": 81218, "s": 81156, "text": "A file has a certain defined structure according to its type." }, { "code": null, "e": 81280, "s": 81218, "text": "A text file is a sequence of characters organized into lines." }, { "code": null, "e": 81342, "s": 81280, "text": "A text file is a sequence of characters organized into lines." }, { "code": null, "e": 81399, "s": 81342, "text": "A source file is a sequence of procedures and functions." }, { "code": null, "e": 81456, "s": 81399, "text": "A source file is a sequence of procedures and functions." }, { "code": null, "e": 81556, "s": 81456, "text": "An object file is a sequence of bytes organized into blocks that are understandable by the machine." }, { "code": null, "e": 81656, "s": 81556, "text": "An object file is a sequence of bytes organized into blocks that are understandable by the machine." }, { "code": null, "e": 81827, "s": 81656, "text": "When operating system defines different file structures, it also contains the code to support these file structure. Unix, MS-DOS support minimum number of file structure." }, { "code": null, "e": 81998, "s": 81827, "text": "When operating system defines different file structures, it also contains the code to support these file structure. Unix, MS-DOS support minimum number of file structure." }, { "code": null, "e": 82273, "s": 81998, "text": "File type refers to the ability of the operating system to distinguish different types of file such as text files source files and binary files etc. Many operating systems support many types of files. Operating system like MS-DOS and UNIX have the following types of files −" }, { "code": null, "e": 82324, "s": 82273, "text": "These are the files that contain user information." }, { "code": null, "e": 82378, "s": 82324, "text": "These may have text, databases or executable program." }, { "code": null, "e": 82487, "s": 82378, "text": "The user can apply various operations on such files like add, modify, delete or even remove the entire file." }, { "code": null, "e": 82572, "s": 82487, "text": "These files contain list of file names and other information related to these files." }, { "code": null, "e": 82616, "s": 82572, "text": "These files are also known as device files." }, { "code": null, "e": 82713, "s": 82616, "text": "These files represent physical device like disks, terminals, printers, networks, tape drive etc." }, { "code": null, "e": 82744, "s": 82713, "text": "These files are of two types −" }, { "code": null, "e": 82846, "s": 82744, "text": "Character special files − data is handled character by character as in case of terminals or printers." }, { "code": null, "e": 82948, "s": 82846, "text": "Character special files − data is handled character by character as in case of terminals or printers." }, { "code": null, "e": 83032, "s": 82948, "text": "Block special files − data is handled in blocks as in the case of disks and tapes." }, { "code": null, "e": 83116, "s": 83032, "text": "Block special files − data is handled in blocks as in the case of disks and tapes." }, { "code": null, "e": 83248, "s": 83116, "text": "File access mechanism refers to the manner in which the records of a file may be accessed. There are several ways to access files −" }, { "code": null, "e": 83266, "s": 83248, "text": "Sequential access" }, { "code": null, "e": 83287, "s": 83266, "text": "Direct/Random access" }, { "code": null, "e": 83313, "s": 83287, "text": "Indexed sequential access" }, { "code": null, "e": 83581, "s": 83313, "text": "A sequential access is that in which the records are accessed in some sequence, i.e., the information in the file is processed in order, one record after the other. This access method is the most primitive one. Example: Compilers usually access files in this fashion." }, { "code": null, "e": 83655, "s": 83581, "text": "Random access file organization provides, accessing the records directly." }, { "code": null, "e": 83729, "s": 83655, "text": "Random access file organization provides, accessing the records directly." }, { "code": null, "e": 83851, "s": 83729, "text": "Each record has its own address on the file with by the help of which it can be directly accessed for reading or writing." }, { "code": null, "e": 83973, "s": 83851, "text": "Each record has its own address on the file with by the help of which it can be directly accessed for reading or writing." }, { "code": null, "e": 84095, "s": 83973, "text": "The records need not be in any sequence within the file and they need not be in adjacent locations on the storage medium." }, { "code": null, "e": 84217, "s": 84095, "text": "The records need not be in any sequence within the file and they need not be in adjacent locations on the storage medium." }, { "code": null, "e": 84274, "s": 84217, "text": "This mechanism is built up on base of sequential access." }, { "code": null, "e": 84351, "s": 84274, "text": "An index is created for each file which contains pointers to various blocks." }, { "code": null, "e": 84435, "s": 84351, "text": "Index is searched sequentially and its pointer is used to access the file directly." }, { "code": null, "e": 84572, "s": 84435, "text": "Files are allocated disk spaces by operating system. Operating systems deploy following three main ways to allocate disk space to files." }, { "code": null, "e": 84594, "s": 84572, "text": "Contiguous Allocation" }, { "code": null, "e": 84612, "s": 84594, "text": "Linked Allocation" }, { "code": null, "e": 84631, "s": 84612, "text": "Indexed Allocation" }, { "code": null, "e": 84686, "s": 84631, "text": "Each file occupies a contiguous address space on disk." }, { "code": null, "e": 84728, "s": 84686, "text": "Assigned disk address is in linear order." }, { "code": null, "e": 84747, "s": 84728, "text": "Easy to implement." }, { "code": null, "e": 84827, "s": 84747, "text": "External fragmentation is a major issue with this type of allocation technique." }, { "code": null, "e": 84877, "s": 84827, "text": "Each file carries a list of links to disk blocks." }, { "code": null, "e": 84937, "s": 84877, "text": "Directory contains link / pointer to first block of a file." }, { "code": null, "e": 84963, "s": 84937, "text": "No external fragmentation" }, { "code": null, "e": 85007, "s": 84963, "text": "Effectively used in sequential access file." }, { "code": null, "e": 85051, "s": 85007, "text": "Inefficient in case of direct access file." }, { "code": null, "e": 85119, "s": 85051, "text": "Provides solutions to problems of contiguous and linked allocation." }, { "code": null, "e": 85174, "s": 85119, "text": "A index block is created having all pointers to files." }, { "code": null, "e": 85271, "s": 85174, "text": "Each file has its own index block which stores the addresses of disk space occupied by the file." }, { "code": null, "e": 85330, "s": 85271, "text": "Directory contains the addresses of index blocks of files." }, { "code": null, "e": 85826, "s": 85330, "text": "Security refers to providing a protection system to computer system resources such as CPU, memory, disk, software programs and most importantly data/information stored in the computer system. If a computer program is run by an unauthorized user, then he/she may cause severe damage to computer or data stored in it. So a computer system must be protected against unauthorized access, malicious access to system memory, viruses, worms etc. We're going to discuss following topics in this chapter." }, { "code": null, "e": 85841, "s": 85826, "text": "Authentication" }, { "code": null, "e": 85860, "s": 85841, "text": "One Time passwords" }, { "code": null, "e": 85876, "s": 85860, "text": "Program Threats" }, { "code": null, "e": 85891, "s": 85876, "text": "System Threats" }, { "code": null, "e": 85925, "s": 85891, "text": "Computer Security Classifications" }, { "code": null, "e": 86286, "s": 85925, "text": "Authentication refers to identifying each user of the system and associating the executing programs with those users. It is the responsibility of the Operating System to create a protection system which ensures that a user who is running a particular program is authentic. Operating Systems generally identifies/authenticates users using following three ways −" }, { "code": null, "e": 86410, "s": 86286, "text": "Username / Password − User need to enter a registered username and password with Operating system to login into the system." }, { "code": null, "e": 86534, "s": 86410, "text": "Username / Password − User need to enter a registered username and password with Operating system to login into the system." }, { "code": null, "e": 86693, "s": 86534, "text": "User card/key − User need to punch card in card slot, or enter key generated by key generator in option provided by operating system to login into the system." }, { "code": null, "e": 86852, "s": 86693, "text": "User card/key − User need to punch card in card slot, or enter key generated by key generator in option provided by operating system to login into the system." }, { "code": null, "e": 87029, "s": 86852, "text": "User attribute - fingerprint/ eye retina pattern/ signature − User need to pass his/her attribute via designated input device used by operating system to login into the system." }, { "code": null, "e": 87206, "s": 87029, "text": "User attribute - fingerprint/ eye retina pattern/ signature − User need to pass his/her attribute via designated input device used by operating system to login into the system." }, { "code": null, "e": 87509, "s": 87206, "text": "One-time passwords provide additional security along with normal authentication. In One-Time Password system, a unique password is required every time user tries to login into the system. Once a one-time password is used, then it cannot be used again. One-time password are implemented in various ways." }, { "code": null, "e": 87682, "s": 87509, "text": "Random numbers − Users are provided cards having numbers printed along with corresponding alphabets. System asks for numbers corresponding to few alphabets randomly chosen." }, { "code": null, "e": 87855, "s": 87682, "text": "Random numbers − Users are provided cards having numbers printed along with corresponding alphabets. System asks for numbers corresponding to few alphabets randomly chosen." }, { "code": null, "e": 88037, "s": 87855, "text": "Secret key − User are provided a hardware device which can create a secret id mapped with user id. System asks for such secret id which is to be generated every time prior to login." }, { "code": null, "e": 88219, "s": 88037, "text": "Secret key − User are provided a hardware device which can create a secret id mapped with user id. System asks for such secret id which is to be generated every time prior to login." }, { "code": null, "e": 88375, "s": 88219, "text": "Network password − Some commercial applications send one-time passwords to user on registered mobile/ email which is required to be entered prior to login." }, { "code": null, "e": 88531, "s": 88375, "text": "Network password − Some commercial applications send one-time passwords to user on registered mobile/ email which is required to be entered prior to login." }, { "code": null, "e": 88912, "s": 88531, "text": "Operating system's processes and kernel do the designated task as instructed. If a user program made these process do malicious tasks, then it is known as Program Threats. One of the common example of program threat is a program installed in a computer which can store and send user credentials via network to some hacker. Following is the list of some well-known program threats." }, { "code": null, "e": 89079, "s": 88912, "text": "Trojan Horse − Such program traps user login credentials and stores them to send to malicious user who can later on login to computer and can access system resources." }, { "code": null, "e": 89246, "s": 89079, "text": "Trojan Horse − Such program traps user login credentials and stores them to send to malicious user who can later on login to computer and can access system resources." }, { "code": null, "e": 89435, "s": 89246, "text": "Trap Door − If a program which is designed to work as required, have a security hole in its code and perform illegal action without knowledge of user then it is called to have a trap door." }, { "code": null, "e": 89624, "s": 89435, "text": "Trap Door − If a program which is designed to work as required, have a security hole in its code and perform illegal action without knowledge of user then it is called to have a trap door." }, { "code": null, "e": 89787, "s": 89624, "text": "Logic Bomb − Logic bomb is a situation when a program misbehaves only when certain conditions met otherwise it works as a genuine program. It is harder to detect." }, { "code": null, "e": 89950, "s": 89787, "text": "Logic Bomb − Logic bomb is a situation when a program misbehaves only when certain conditions met otherwise it works as a genuine program. It is harder to detect." }, { "code": null, "e": 90285, "s": 89950, "text": "Virus − Virus as name suggest can replicate themselves on computer system. They are highly dangerous and can modify/delete user files, crash systems. A virus is generatlly a small code embedded in a program. As user accesses the program, the virus starts getting embedded in other files/ programs and can make system unusable for user" }, { "code": null, "e": 90620, "s": 90285, "text": "Virus − Virus as name suggest can replicate themselves on computer system. They are highly dangerous and can modify/delete user files, crash systems. A virus is generatlly a small code embedded in a program. As user accesses the program, the virus starts getting embedded in other files/ programs and can make system unusable for user" }, { "code": null, "e": 90977, "s": 90620, "text": "System threats refers to misuse of system services and network connections to put user in trouble. System threats can be used to launch program threats on a complete network called as program attack. System threats creates such an environment that operating system resources/ user files are misused. Following is the list of some well-known system threats." }, { "code": null, "e": 91284, "s": 90977, "text": "Worm − Worm is a process which can choked down a system performance by using system resources to extreme levels. A Worm process generates its multiple copies where each copy uses system resources, prevents all other processes to get required resources. Worms processes can even shut down an entire network." }, { "code": null, "e": 91591, "s": 91284, "text": "Worm − Worm is a process which can choked down a system performance by using system resources to extreme levels. A Worm process generates its multiple copies where each copy uses system resources, prevents all other processes to get required resources. Worms processes can even shut down an entire network." }, { "code": null, "e": 91731, "s": 91591, "text": "Port Scanning − Port scanning is a mechanism or means by which a hacker can detects system vulnerabilities to make an attack on the system." }, { "code": null, "e": 91871, "s": 91731, "text": "Port Scanning − Port scanning is a mechanism or means by which a hacker can detects system vulnerabilities to make an attack on the system." }, { "code": null, "e": 92087, "s": 91871, "text": "Denial of Service − Denial of service attacks normally prevents user to make legitimate use of the system. For example, a user may not be able to use internet if denial of service attacks browser's content settings." }, { "code": null, "e": 92303, "s": 92087, "text": "Denial of Service − Denial of service attacks normally prevents user to make legitimate use of the system. For example, a user may not be able to use internet if denial of service attacks browser's content settings." }, { "code": null, "e": 92632, "s": 92303, "text": "As per the U.S. Department of Defense Trusted Computer System's Evaluation Criteria there are four security classifications in computer systems: A, B, C, and D. This is widely used specifications to determine and model the security of systems and of security solutions. Following is the brief description of each classification." }, { "code": null, "e": 92639, "s": 92632, "text": "Type A" }, { "code": null, "e": 92772, "s": 92639, "text": "Highest Level. Uses formal design specifications and verification techniques. Grants a high degree of assurance of process security." }, { "code": null, "e": 92779, "s": 92772, "text": "Type B" }, { "code": null, "e": 92930, "s": 92779, "text": "Provides mandatory protection system. Have all the properties of a class C2 system. Attaches a sensitivity label to each object. It is of three types." }, { "code": null, "e": 93048, "s": 92930, "text": "B1 − Maintains the security label of each object in the system. Label is used for making decisions to access control." }, { "code": null, "e": 93166, "s": 93048, "text": "B1 − Maintains the security label of each object in the system. Label is used for making decisions to access control." }, { "code": null, "e": 93301, "s": 93166, "text": "B2 − Extends the sensitivity labels to each system resource, such as storage objects, supports covert channels and auditing of events." }, { "code": null, "e": 93436, "s": 93301, "text": "B2 − Extends the sensitivity labels to each system resource, such as storage objects, supports covert channels and auditing of events." }, { "code": null, "e": 93555, "s": 93436, "text": "B3 − Allows creating lists or user groups for access-control to grant access or revoke access to a given named object." }, { "code": null, "e": 93674, "s": 93555, "text": "B3 − Allows creating lists or user groups for access-control to grant access or revoke access to a given named object." }, { "code": null, "e": 93681, "s": 93674, "text": "Type C" }, { "code": null, "e": 93771, "s": 93681, "text": "Provides protection and user accountability using audit capabilities. It is of two types." }, { "code": null, "e": 93955, "s": 93771, "text": "C1 − Incorporates controls so that users can protect their private information and keep other users from accidentally reading / deleting their data. UNIX versions are mostly Cl class." }, { "code": null, "e": 94139, "s": 93955, "text": "C1 − Incorporates controls so that users can protect their private information and keep other users from accidentally reading / deleting their data. UNIX versions are mostly Cl class." }, { "code": null, "e": 94226, "s": 94139, "text": "C2 − Adds an individual-level access control to the capabilities of a Cl level system." }, { "code": null, "e": 94313, "s": 94226, "text": "C2 − Adds an individual-level access control to the capabilities of a Cl level system." }, { "code": null, "e": 94320, "s": 94313, "text": "Type D" }, { "code": null, "e": 94396, "s": 94320, "text": "Lowest level. Minimum protection. MS-DOS, Window 3.1 fall in this category." }, { "code": null, "e": 94639, "s": 94396, "text": "Linux is one of popular version of UNIX operating System. It is open source as its source code is freely available. It is free to use. Linux was designed considering UNIX compatibility. Its functionality list is quite similar to that of UNIX." }, { "code": null, "e": 94693, "s": 94639, "text": "Linux Operating System has primarily three components" }, { "code": null, "e": 95003, "s": 94693, "text": "Kernel − Kernel is the core part of Linux. It is responsible for all major activities of this operating system. It consists of various modules and it interacts directly with the underlying hardware. Kernel provides the required abstraction to hide low level hardware details to system or application programs." }, { "code": null, "e": 95313, "s": 95003, "text": "Kernel − Kernel is the core part of Linux. It is responsible for all major activities of this operating system. It consists of various modules and it interacts directly with the underlying hardware. Kernel provides the required abstraction to hide low level hardware details to system or application programs." }, { "code": null, "e": 95596, "s": 95313, "text": "System Library − System libraries are special functions or programs using which application programs or system utilities accesses Kernel's features. These libraries implement most of the functionalities of the operating system and do not requires kernel module's code access rights." }, { "code": null, "e": 95879, "s": 95596, "text": "System Library − System libraries are special functions or programs using which application programs or system utilities accesses Kernel's features. These libraries implement most of the functionalities of the operating system and do not requires kernel module's code access rights." }, { "code": null, "e": 95979, "s": 95879, "text": "System Utility − System Utility programs are responsible to do specialized, individual level tasks." }, { "code": null, "e": 96079, "s": 95979, "text": "System Utility − System Utility programs are responsible to do specialized, individual level tasks." }, { "code": null, "e": 96479, "s": 96079, "text": "Kernel component code executes in a special privileged mode called kernel mode with full access to all resources of the computer. This code represents a single process, executes in single address space and do not require any context switch and hence is very efficient and fast. Kernel runs each processes and provides system services to processes, provides protected access to hardware to processes." }, { "code": null, "e": 96779, "s": 96479, "text": "Support code which is not required to run in kernel mode is in System Library. User programs and other system programs works in User Mode which has no access to system hardware and kernel code. User programs/ utilities use System libraries to access Kernel functions to get system's low level tasks." }, { "code": null, "e": 96851, "s": 96779, "text": "Following are some of the important features of Linux Operating System." }, { "code": null, "e": 97043, "s": 96851, "text": "Portable − Portability means software can works on different types of hardware in same way. Linux kernel and application programs supports their installation on any kind of hardware platform." }, { "code": null, "e": 97235, "s": 97043, "text": "Portable − Portability means software can works on different types of hardware in same way. Linux kernel and application programs supports their installation on any kind of hardware platform." }, { "code": null, "e": 97456, "s": 97235, "text": "Open Source − Linux source code is freely available and it is community based development project. Multiple teams work in collaboration to enhance the capability of Linux operating system and it is continuously evolving." }, { "code": null, "e": 97677, "s": 97456, "text": "Open Source − Linux source code is freely available and it is community based development project. Multiple teams work in collaboration to enhance the capability of Linux operating system and it is continuously evolving." }, { "code": null, "e": 97820, "s": 97677, "text": "Multi-User − Linux is a multiuser system means multiple users can access system resources like memory/ ram/ application programs at same time." }, { "code": null, "e": 97963, "s": 97820, "text": "Multi-User − Linux is a multiuser system means multiple users can access system resources like memory/ ram/ application programs at same time." }, { "code": null, "e": 98067, "s": 97963, "text": "Multiprogramming − Linux is a multiprogramming system means multiple applications can run at same time." }, { "code": null, "e": 98171, "s": 98067, "text": "Multiprogramming − Linux is a multiprogramming system means multiple applications can run at same time." }, { "code": null, "e": 98287, "s": 98171, "text": "Hierarchical File System − Linux provides a standard file structure in which system files/ user files are arranged." }, { "code": null, "e": 98403, "s": 98287, "text": "Hierarchical File System − Linux provides a standard file structure in which system files/ user files are arranged." }, { "code": null, "e": 98601, "s": 98403, "text": "Shell − Linux provides a special interpreter program which can be used to execute commands of the operating system. It can be used to do various types of operations, call application programs. etc." }, { "code": null, "e": 98799, "s": 98601, "text": "Shell − Linux provides a special interpreter program which can be used to execute commands of the operating system. It can be used to do various types of operations, call application programs. etc." }, { "code": null, "e": 98952, "s": 98799, "text": "Security − Linux provides user security using authentication features like password protection/ controlled access to specific files/ encryption of data." }, { "code": null, "e": 99105, "s": 98952, "text": "Security − Linux provides user security using authentication features like password protection/ controlled access to specific files/ encryption of data." }, { "code": null, "e": 99175, "s": 99105, "text": "The following illustration shows the architecture of a Linux system −" }, { "code": null, "e": 99245, "s": 99175, "text": "The architecture of a Linux System consists of the following layers −" }, { "code": null, "e": 99327, "s": 99245, "text": "Hardware layer − Hardware consists of all peripheral devices (RAM/ HDD/ CPU etc)." }, { "code": null, "e": 99409, "s": 99327, "text": "Hardware layer − Hardware consists of all peripheral devices (RAM/ HDD/ CPU etc)." }, { "code": null, "e": 99553, "s": 99409, "text": "Kernel − It is the core component of Operating System, interacts directly with hardware, provides low level services to upper layer components." }, { "code": null, "e": 99697, "s": 99553, "text": "Kernel − It is the core component of Operating System, interacts directly with hardware, provides low level services to upper layer components." }, { "code": null, "e": 99853, "s": 99697, "text": "Shell − An interface to kernel, hiding complexity of kernel's functions from users. The shell takes commands from the user and executes kernel's functions." }, { "code": null, "e": 100009, "s": 99853, "text": "Shell − An interface to kernel, hiding complexity of kernel's functions from users. The shell takes commands from the user and executes kernel's functions." }, { "code": null, "e": 100113, "s": 100009, "text": "Utilities − Utility programs that provide the user most of the functionalities of an operating systems." }, { "code": null, "e": 100217, "s": 100113, "text": "Utilities − Utility programs that provide the user most of the functionalities of an operating systems." }, { "code": null, "e": 100251, "s": 100217, "text": "\n 86 Lectures \n 10 hours \n" }, { "code": null, "e": 100270, "s": 100251, "text": " Arnab Chakraborty" }, { "code": null, "e": 100304, "s": 100270, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 100321, "s": 100304, "text": " Frahaan Hussain" }, { "code": null, "e": 100352, "s": 100321, "text": "\n 8 Lectures \n 43 mins\n" }, { "code": null, "e": 100372, "s": 100352, "text": " Harshit Srivastava" }, { "code": null, "e": 100407, "s": 100372, "text": "\n 29 Lectures \n 2.5 hours \n" }, { "code": null, "e": 100420, "s": 100407, "text": " Ashraf Said" }, { "code": null, "e": 100454, "s": 100420, "text": "\n 43 Lectures \n 20 hours \n" }, { "code": null, "e": 100470, "s": 100454, "text": " ILANCHEZHIAN K" }, { "code": null, "e": 100504, "s": 100470, "text": "\n 45 Lectures \n 20 hours \n" }, { "code": null, "e": 100520, "s": 100504, "text": " ILANCHEZHIAN K" }, { "code": null, "e": 100527, "s": 100520, "text": " Print" }, { "code": null, "e": 100538, "s": 100527, "text": " Add Notes" } ]
Java Math
The Java Math class has many methods that allows you to perform mathematical tasks on numbers. The Math.max(x,y) method can be used to find the highest value of x and y: Math.max(5, 10); Try it Yourself » The Math.min(x,y) method can be used to find the lowest value of x and y: Math.min(5, 10); Try it Yourself » The Math.sqrt(x) method returns the square root of x: Math.sqrt(64); Try it Yourself » The Math.abs(x) method returns the absolute (positive) value of x: Math.abs(-4.7); Try it Yourself » Math.random() returns a random number between 0.0 (inclusive), and 1.0 (exclusive): Math.random(); Try it Yourself » To get more control over the random number, e.g. you only want a random number between 0 and 100, you can use the following formula: int randomNum = (int)(Math.random() * 101); // 0 to 100 Try it Yourself » For a complete reference of Math methods, go to our Java Math Methods Reference. Use the correct method to find the highest value of x and y. int x = 5; int y = 10; Math.(x, y); Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 95, "s": 0, "text": "The Java Math class has many methods that allows you to perform mathematical tasks on numbers." }, { "code": null, "e": 170, "s": 95, "text": "The Math.max(x,y) method can be used to find the highest value of x and\ny:" }, { "code": null, "e": 188, "s": 170, "text": "Math.max(5, 10);\n" }, { "code": null, "e": 208, "s": 188, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 283, "s": 208, "text": "The Math.min(x,y) method can be used to find the lowest value of x \nand y:" }, { "code": null, "e": 301, "s": 283, "text": "Math.min(5, 10);\n" }, { "code": null, "e": 321, "s": 301, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 375, "s": 321, "text": "The Math.sqrt(x) method returns the square root of x:" }, { "code": null, "e": 391, "s": 375, "text": "Math.sqrt(64);\n" }, { "code": null, "e": 411, "s": 391, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 478, "s": 411, "text": "The Math.abs(x) method returns the absolute (positive) value of x:" }, { "code": null, "e": 495, "s": 478, "text": "Math.abs(-4.7);\n" }, { "code": null, "e": 515, "s": 495, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 599, "s": 515, "text": "Math.random() returns a random number between 0.0 (inclusive), and 1.0 (exclusive):" }, { "code": null, "e": 615, "s": 599, "text": "Math.random();\n" }, { "code": null, "e": 635, "s": 615, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 769, "s": 635, "text": "To get more control over the random number, e.g. you only want a random \nnumber between 0 and 100, you can use the following formula:" }, { "code": null, "e": 826, "s": 769, "text": "int randomNum = (int)(Math.random() * 101); // 0 to 100" }, { "code": null, "e": 846, "s": 826, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 927, "s": 846, "text": "For a complete reference of Math methods, go to our Java Math Methods Reference." }, { "code": null, "e": 988, "s": 927, "text": "Use the correct method to find the highest value of x and y." }, { "code": null, "e": 1025, "s": 988, "text": "int x = 5;\nint y = 10;\nMath.(x, y);\n" }, { "code": null, "e": 1044, "s": 1025, "text": "Start the Exercise" }, { "code": null, "e": 1077, "s": 1044, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1119, "s": 1077, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1226, "s": 1119, "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": 1245, "s": 1226, "text": "help@w3schools.com" } ]
What is a virtual base class in C++?
The virtual base class is used when a derived class has multiple copies of the base class. #include <iostream> using namespace std; class B { public: int b; }; class D1 : public B { public: int d1; }; class D2 : public B { public: int d2; }; class D3 : public D1, public D2 { public: int d3; }; int main() { D3 obj; obj.b = 40; //Statement 1, error will occur obj.b = 30; //statement 2, error will occur obj.d1 = 60; obj.d2 = 70; obj.d3 = 80; cout<< "\n B : "<< obj.b cout<< "\n D1 : "<< obj.d1; cout<< "\n D2: "<< obj.d2; cout<< "\n D3: "<< obj.d3; } In the above example, both D1 & D2 inherit B, they both have a single copy of B. However, D3 inherit both D1 & D2, therefore D3 have two copies of B, one from D1 and another from D2. Statement 1 and 2 in above example will generate error, as compiler can't differentiate between two copies of b in D3. To remove multiple copies of B from D3, we must inherit B in D1 and D3 as virtual class. So, above example using virtual base class will be − Live Demo #include<iostream> using namespace std; class B { public: int b; }; class D1 : virtual public B { public: int d1; }; class D2 : virtual public B { public: int d2; }; class D3 : public D1, public D2 { public: int d3; }; int main() { D3 obj; obj.b = 40; // statement 3 obj.b = 30; // statement 4 obj.d1 = 60; obj.d2 = 70; obj.d3 = 80; cout<< "\n B : "<< obj.b; cout<< "\n D1 : "<< obj.d1; cout<< "\n D2 : "<< obj.d2; cout<< "\n D3 : "<< obj.d3; } B : 30 D1 : 60 D2 : 70 D3 : 80 Now, D3 have only one copy of B and statement 4 will overwrite the value of b, given in statement 3.
[ { "code": null, "e": 1153, "s": 1062, "text": "The virtual base class is used when a derived class has multiple copies of the base class." }, { "code": null, "e": 1662, "s": 1153, "text": "#include <iostream>\nusing namespace std;\nclass B {\n public: int b;\n};\n\nclass D1 : public B {\n public: int d1;\n};\n\nclass D2 : public B {\n public: int d2;\n};\n\nclass D3 : public D1, public D2 {\n public: int d3;\n};\n\nint main() {\n D3 obj;\n\n obj.b = 40; //Statement 1, error will occur\n obj.b = 30; //statement 2, error will occur\n obj.d1 = 60;\n obj.d2 = 70;\n obj.d3 = 80;\n\n cout<< \"\\n B : \"<< obj.b\n cout<< \"\\n D1 : \"<< obj.d1;\n cout<< \"\\n D2: \"<< obj.d2;\n cout<< \"\\n D3: \"<< obj.d3;\n}" }, { "code": null, "e": 1845, "s": 1662, "text": "In the above example, both D1 & D2 inherit B, they both have a single copy of B. However, D3 inherit both D1 & D2, therefore D3 have two copies of B, one from D1 and another from D2." }, { "code": null, "e": 1964, "s": 1845, "text": "Statement 1 and 2 in above example will generate error, as compiler can't differentiate between two copies of b in D3." }, { "code": null, "e": 2053, "s": 1964, "text": "To remove multiple copies of B from D3, we must inherit B in D1 and D3 as virtual class." }, { "code": null, "e": 2106, "s": 2053, "text": "So, above example using virtual base class will be −" }, { "code": null, "e": 2117, "s": 2106, "text": " Live Demo" }, { "code": null, "e": 2611, "s": 2117, "text": "#include<iostream>\nusing namespace std;\nclass B {\n public: int b;\n};\n\nclass D1 : virtual public B {\n public: int d1;\n};\n\nclass D2 : virtual public B {\n public: int d2;\n};\n\nclass D3 : public D1, public D2 {\n public: int d3;\n};\n\nint main() {\n D3 obj;\n\n obj.b = 40; // statement 3\n obj.b = 30; // statement 4\n\n obj.d1 = 60;\n obj.d2 = 70;\n obj.d3 = 80;\n\n cout<< \"\\n B : \"<< obj.b;\n cout<< \"\\n D1 : \"<< obj.d1;\n cout<< \"\\n D2 : \"<< obj.d2;\n cout<< \"\\n D3 : \"<< obj.d3;\n}" }, { "code": null, "e": 2642, "s": 2611, "text": "B : 30\nD1 : 60\nD2 : 70\nD3 : 80" }, { "code": null, "e": 2743, "s": 2642, "text": "Now, D3 have only one copy of B and statement 4 will overwrite the value of b, given in statement 3." } ]
Slope charts with Python’s Matplotlib | by Thiago Carvalho | Towards Data Science
With a straightforward format that can effortlessly illustrate changes and rank variables, Slope charts are more than just an over-glorified line chart. They have earned their place in data visualization and can be a great addition to your reports and dashboards. In this article, we’ll explore how to plot them with Matplotlib, get a look at different ways of designing them and how they compare to other data visualizations. The data we’ll use in the following examples is the GDP per capita from the UN. I used filters to download only 2018 and 2019 data. import pandas as pdimport matplotlib.pyplot as pltdf = pd.read_csv('../data/UNdata_gdp.csv')df.head() Let’s start by plotting a single line chart for a country. temp = df[df['Country or Area'] == 'Switzerland']plt.plot(temp.Year, temp.Value)plt.show() We’ll need to repeat that for a list of countries to plot the other lines. We can also start preparing our visualization layout by adding a figure with a custom size, fixing the x ticks, and increasing the space in the x-axis to add labels. Labels at the start and end of the lines are a distinguishable feature of slope charts; they can display different information to fit our visualization's purpose. countries = ['Ireland', 'Norway', 'Switzerland', 'Cayman Islands', 'China, Macao Special Administrative Region']fig, ax = plt.subplots(1, figsize=(10,10))for i in countries: temp = df[df['Country or Area'] == i] plt.plot(temp.Year, temp.Value) plt.xlim(2017.5,2019.5)plt.xticks([2018, 2019])plt.show() Cool, It’s starting to look more like a Slope chart, but we’re not there yet. Let’s add the labels and format the y-ticks. countries = ['Ireland', 'Norway', 'Switzerland', 'Cayman Islands', 'China, Macao Special Administrative Region']fig, ax = plt.subplots(1, figsize=(10,10))for i in countries: # get a single country from the list temp = df[df['Country or Area'] == i] # plot the lines plt.plot(temp.Year, temp.Value, marker='o', markersize=5) # replace large labels if i == 'China, Macao Special Administrative Region': i = 'Macao (China)' # end label plt.text(temp.Year.values[0]+0.02, temp.Value.values[0], i) # start label plt.text(temp.Year.values[1]-0.02, temp.Value.values[1], i, ha='right') # x limits, x ticks, and y label plt.xlim(2017.5,2019.5)plt.xticks([2018, 2019])# get y ticks, replace 1,000 with k, and draw the ticksyticks = plt.yticks()[0]plt.yticks(yticks, ['{}k'.format(i/1000) for i in yticks])plt.show() That’s it! We have a slope chart. The labels with the names of the countries/ areas make it incredibly easy to follow the information, way more accessible than a legend. It also ranks the variables both before and after the change. Let’s add some more detail to our Slope chart before exploring other applications. We’ll remove the spines, add gridlines, a y-axis label, title, and change some colors. countries = ['Ireland', 'Norway', 'Switzerland', 'Cayman Islands', 'China, Macao Special Administrative Region']colors = ['#769465', '#69BDE0', '#E06D5E', '#2F7694', '#94E069']fig, ax = plt.subplots(1, figsize=(10,10), facecolor='darkgrey')ax.set_facecolor('darkgrey')for i, v in enumerate(countries): # get a single country from the list temp = df[df['Country or Area'] == v] # plot the lines plt.plot(temp.Year, temp.Value, color=colors[i], lw=2.5, marker='o', markersize=5) # replace large labels if v == 'China, Macao Special Administrative Region': v = 'Macao (China)' # end label plt.text(temp.Year.values[0]+0.02, temp.Value.values[0], v) # start label plt.text(temp.Year.values[1]-0.02, temp.Value.values[1], v, ha='right') # x limits, x ticks, and y label plt.xlim(2017.5,2019.5)plt.xticks([2018, 2019])plt.ylabel('USD')# get y ticks, replace 1,000 with k, and draw the ticksyticks = plt.yticks()[0]plt.yticks(yticks[1:-1], ['{}k'.format(i/1000) for i in yticks[1:-1]])# gridax.xaxis.grid(color='black', linestyle='solid', which='both', alpha=0.9)ax.yaxis.grid(color='black', linestyle='dashed', which='both', alpha=0.1)# remove spinesax.spines['right'].set_visible(False)ax.spines['left'].set_visible(False)ax.spines['bottom'].set_visible(False)ax.spines['top'].set_visible(False)plt.title('GDP Per Capta\n', loc='left', fontsize=20)plt.show() The labels are typically used for two main purposes, naming the line or displaying the values. Sometimes, knowing the exact values is essential to our viz, and we might need to sacrifice the names to display them. countries = ['Ireland', 'Norway', 'Switzerland', 'Cayman Islands', 'China, Macao Special Administrative Region']colors = ['#769465', '#69BDE0', '#E06D5E', '#2F7694', '#94E069']fig, ax = plt.subplots(1, figsize=(10,10), facecolor='darkgrey')ax.set_facecolor('darkgrey')for i, v in enumerate(countries): temp = df[df['Country or Area'] == v] plt.plot(temp.Year, temp.Value, color=colors[i], lw=2.5) plt.text(temp.Year.values[0]+0.02, temp.Value.values[0], '{:,.2f}'.format(temp.Value.values[0])) plt.text(temp.Year.values[1]-0.02, temp.Value.values[1], '{:,.2f}'.format(temp.Value.values[1]), va='center', ha='right')plt.xlim(2017.5,2019.5)plt.xticks([2018, 2019])yticks = plt.yticks()[0]plt.yticks([])# gridax.xaxis.grid(color='black', linestyle='solid', which='both', alpha=0.9)# remove spinesax.spines['right'].set_visible(False)ax.spines['left'].set_visible(False)ax.spines['bottom'].set_visible(False)ax.spines['top'].set_visible(False)plt.title('GDP Per Capta\n', loc='left', fontsize=20)for i, v in enumerate(countries): if v == 'China, Macao Special Administrative Region': countries[i] = 'Macao (China)'plt.legend(countries, loc='upper left', frameon=False)plt.show() It’s still easy to understand what each line represents, but the rankings are not so explicit when we use a legend instead of the labels. In some cases, we might be able to have the cake and eat it too, but it depends on the data. That is to say — If the lines are spaced enough you might be able to write the names above or below them. colors = ['#87B38D', '#477998', '#291F1E', '#BC9CB0', '#A3333D']countries = ['Germany', 'Canada', 'Spain', 'Italy', 'France']fig, ax = plt.subplots(1, figsize=(10,10))for i, v in enumerate(countries): temp = df[df['Country or Area'] == v] plt.plot(temp.Year, temp.Value, color=colors[i], lw=2.5) plt.text(temp.Year.values[0]+0.02, temp.Value.values[0], '{:,.2f}'.format(temp.Value.values[0])) plt.text(temp.Year.values[1]-0.02, temp.Value.values[1], '{:,.2f}'.format(temp.Value.values[1]), va='center', ha='right') correction = 0 if v == 'Canada': correction = 500 plt.text(2018.5, temp.Value.values[1] - correction, v, color=colors[i], va='center', ha='center', fontsize=14)plt.xlim(2017.5,2019.5)plt.xticks([2018, 2019])plt.yticks([])# gridax.xaxis.grid(color='black', linestyle='solid', which='both', alpha=0.9)# remove spinesax.spines['right'].set_visible(False)ax.spines['left'].set_visible(False)ax.spines['bottom'].set_visible(False)ax.spines['top'].set_visible(False)plt.title('GDP Per Capta\n', loc='left', fontsize=20)plt.show() Slope charts are generally simple, there are a few different approaches to them, and they may require some tweaks to fit your solution, but overall you can have a meaningful graph with very few elements. There are no doubts you can visualize changes and display this same information with other data visualizations. With bar charts and arrow charts, you can order your data by the initial value, the end value, or amount/ percentage of change. You would need multiple charts to display the rankings before and after, and it just isn’t the same. None can display the rankings so naturally as Slope charts. Even if the order of the variables isn’t essential to your visualization, Slope charts do a great job at communicating changes and adding variety to your reports and dashboards. You can find the code for all the visualizations used in this article here. Thanks for reading my article. I hope you enjoyed it. More Python DataViz tutorials.
[ { "code": null, "e": 325, "s": 172, "text": "With a straightforward format that can effortlessly illustrate changes and rank variables, Slope charts are more than just an over-glorified line chart." }, { "code": null, "e": 436, "s": 325, "text": "They have earned their place in data visualization and can be a great addition to your reports and dashboards." }, { "code": null, "e": 599, "s": 436, "text": "In this article, we’ll explore how to plot them with Matplotlib, get a look at different ways of designing them and how they compare to other data visualizations." }, { "code": null, "e": 731, "s": 599, "text": "The data we’ll use in the following examples is the GDP per capita from the UN. I used filters to download only 2018 and 2019 data." }, { "code": null, "e": 833, "s": 731, "text": "import pandas as pdimport matplotlib.pyplot as pltdf = pd.read_csv('../data/UNdata_gdp.csv')df.head()" }, { "code": null, "e": 892, "s": 833, "text": "Let’s start by plotting a single line chart for a country." }, { "code": null, "e": 983, "s": 892, "text": "temp = df[df['Country or Area'] == 'Switzerland']plt.plot(temp.Year, temp.Value)plt.show()" }, { "code": null, "e": 1224, "s": 983, "text": "We’ll need to repeat that for a list of countries to plot the other lines. We can also start preparing our visualization layout by adding a figure with a custom size, fixing the x ticks, and increasing the space in the x-axis to add labels." }, { "code": null, "e": 1387, "s": 1224, "text": "Labels at the start and end of the lines are a distinguishable feature of slope charts; they can display different information to fit our visualization's purpose." }, { "code": null, "e": 1722, "s": 1387, "text": "countries = ['Ireland', 'Norway', 'Switzerland', 'Cayman Islands', 'China, Macao Special Administrative Region']fig, ax = plt.subplots(1, figsize=(10,10))for i in countries: temp = df[df['Country or Area'] == i] plt.plot(temp.Year, temp.Value) plt.xlim(2017.5,2019.5)plt.xticks([2018, 2019])plt.show()" }, { "code": null, "e": 1800, "s": 1722, "text": "Cool, It’s starting to look more like a Slope chart, but we’re not there yet." }, { "code": null, "e": 1845, "s": 1800, "text": "Let’s add the labels and format the y-ticks." }, { "code": null, "e": 2716, "s": 1845, "text": "countries = ['Ireland', 'Norway', 'Switzerland', 'Cayman Islands', 'China, Macao Special Administrative Region']fig, ax = plt.subplots(1, figsize=(10,10))for i in countries: # get a single country from the list temp = df[df['Country or Area'] == i] # plot the lines plt.plot(temp.Year, temp.Value, marker='o', markersize=5) # replace large labels if i == 'China, Macao Special Administrative Region': i = 'Macao (China)' # end label plt.text(temp.Year.values[0]+0.02, temp.Value.values[0], i) # start label plt.text(temp.Year.values[1]-0.02, temp.Value.values[1], i, ha='right') # x limits, x ticks, and y label plt.xlim(2017.5,2019.5)plt.xticks([2018, 2019])# get y ticks, replace 1,000 with k, and draw the ticksyticks = plt.yticks()[0]plt.yticks(yticks, ['{}k'.format(i/1000) for i in yticks])plt.show()" }, { "code": null, "e": 2750, "s": 2716, "text": "That’s it! We have a slope chart." }, { "code": null, "e": 2948, "s": 2750, "text": "The labels with the names of the countries/ areas make it incredibly easy to follow the information, way more accessible than a legend. It also ranks the variables both before and after the change." }, { "code": null, "e": 3031, "s": 2948, "text": "Let’s add some more detail to our Slope chart before exploring other applications." }, { "code": null, "e": 3118, "s": 3031, "text": "We’ll remove the spines, add gridlines, a y-axis label, title, and change some colors." }, { "code": null, "e": 4562, "s": 3118, "text": "countries = ['Ireland', 'Norway', 'Switzerland', 'Cayman Islands', 'China, Macao Special Administrative Region']colors = ['#769465', '#69BDE0', '#E06D5E', '#2F7694', '#94E069']fig, ax = plt.subplots(1, figsize=(10,10), facecolor='darkgrey')ax.set_facecolor('darkgrey')for i, v in enumerate(countries): # get a single country from the list temp = df[df['Country or Area'] == v] # plot the lines plt.plot(temp.Year, temp.Value, color=colors[i], lw=2.5, marker='o', markersize=5) # replace large labels if v == 'China, Macao Special Administrative Region': v = 'Macao (China)' # end label plt.text(temp.Year.values[0]+0.02, temp.Value.values[0], v) # start label plt.text(temp.Year.values[1]-0.02, temp.Value.values[1], v, ha='right') # x limits, x ticks, and y label plt.xlim(2017.5,2019.5)plt.xticks([2018, 2019])plt.ylabel('USD')# get y ticks, replace 1,000 with k, and draw the ticksyticks = plt.yticks()[0]plt.yticks(yticks[1:-1], ['{}k'.format(i/1000) for i in yticks[1:-1]])# gridax.xaxis.grid(color='black', linestyle='solid', which='both', alpha=0.9)ax.yaxis.grid(color='black', linestyle='dashed', which='both', alpha=0.1)# remove spinesax.spines['right'].set_visible(False)ax.spines['left'].set_visible(False)ax.spines['bottom'].set_visible(False)ax.spines['top'].set_visible(False)plt.title('GDP Per Capta\\n', loc='left', fontsize=20)plt.show()" }, { "code": null, "e": 4657, "s": 4562, "text": "The labels are typically used for two main purposes, naming the line or displaying the values." }, { "code": null, "e": 4776, "s": 4657, "text": "Sometimes, knowing the exact values is essential to our viz, and we might need to sacrifice the names to display them." }, { "code": null, "e": 6065, "s": 4776, "text": "countries = ['Ireland', 'Norway', 'Switzerland', 'Cayman Islands', 'China, Macao Special Administrative Region']colors = ['#769465', '#69BDE0', '#E06D5E', '#2F7694', '#94E069']fig, ax = plt.subplots(1, figsize=(10,10), facecolor='darkgrey')ax.set_facecolor('darkgrey')for i, v in enumerate(countries): temp = df[df['Country or Area'] == v] plt.plot(temp.Year, temp.Value, color=colors[i], lw=2.5) plt.text(temp.Year.values[0]+0.02, temp.Value.values[0], '{:,.2f}'.format(temp.Value.values[0])) plt.text(temp.Year.values[1]-0.02, temp.Value.values[1], '{:,.2f}'.format(temp.Value.values[1]), va='center', ha='right')plt.xlim(2017.5,2019.5)plt.xticks([2018, 2019])yticks = plt.yticks()[0]plt.yticks([])# gridax.xaxis.grid(color='black', linestyle='solid', which='both', alpha=0.9)# remove spinesax.spines['right'].set_visible(False)ax.spines['left'].set_visible(False)ax.spines['bottom'].set_visible(False)ax.spines['top'].set_visible(False)plt.title('GDP Per Capta\\n', loc='left', fontsize=20)for i, v in enumerate(countries): if v == 'China, Macao Special Administrative Region': countries[i] = 'Macao (China)'plt.legend(countries, loc='upper left', frameon=False)plt.show()" }, { "code": null, "e": 6203, "s": 6065, "text": "It’s still easy to understand what each line represents, but the rankings are not so explicit when we use a legend instead of the labels." }, { "code": null, "e": 6402, "s": 6203, "text": "In some cases, we might be able to have the cake and eat it too, but it depends on the data. That is to say — If the lines are spaced enough you might be able to write the names above or below them." }, { "code": null, "e": 7611, "s": 6402, "text": "colors = ['#87B38D', '#477998', '#291F1E', '#BC9CB0', '#A3333D']countries = ['Germany', 'Canada', 'Spain', 'Italy', 'France']fig, ax = plt.subplots(1, figsize=(10,10))for i, v in enumerate(countries): temp = df[df['Country or Area'] == v] plt.plot(temp.Year, temp.Value, color=colors[i], lw=2.5) plt.text(temp.Year.values[0]+0.02, temp.Value.values[0], '{:,.2f}'.format(temp.Value.values[0])) plt.text(temp.Year.values[1]-0.02, temp.Value.values[1], '{:,.2f}'.format(temp.Value.values[1]), va='center', ha='right') correction = 0 if v == 'Canada': correction = 500 plt.text(2018.5, temp.Value.values[1] - correction, v, color=colors[i], va='center', ha='center', fontsize=14)plt.xlim(2017.5,2019.5)plt.xticks([2018, 2019])plt.yticks([])# gridax.xaxis.grid(color='black', linestyle='solid', which='both', alpha=0.9)# remove spinesax.spines['right'].set_visible(False)ax.spines['left'].set_visible(False)ax.spines['bottom'].set_visible(False)ax.spines['top'].set_visible(False)plt.title('GDP Per Capta\\n', loc='left', fontsize=20)plt.show()" }, { "code": null, "e": 7815, "s": 7611, "text": "Slope charts are generally simple, there are a few different approaches to them, and they may require some tweaks to fit your solution, but overall you can have a meaningful graph with very few elements." }, { "code": null, "e": 7927, "s": 7815, "text": "There are no doubts you can visualize changes and display this same information with other data visualizations." }, { "code": null, "e": 8156, "s": 7927, "text": "With bar charts and arrow charts, you can order your data by the initial value, the end value, or amount/ percentage of change. You would need multiple charts to display the rankings before and after, and it just isn’t the same." }, { "code": null, "e": 8216, "s": 8156, "text": "None can display the rankings so naturally as Slope charts." }, { "code": null, "e": 8394, "s": 8216, "text": "Even if the order of the variables isn’t essential to your visualization, Slope charts do a great job at communicating changes and adding variety to your reports and dashboards." }, { "code": null, "e": 8470, "s": 8394, "text": "You can find the code for all the visualizations used in this article here." }, { "code": null, "e": 8524, "s": 8470, "text": "Thanks for reading my article. I hope you enjoyed it." } ]
Sorting Objects in Python. Sorting Objects of the same Class | by Sadrach Pierre, Ph.D. | Towards Data Science
In computer science, classes are blueprints for defining objects with related attributes and methods. A common task in computer science is sorting data structures based on attributes. In this post, we will discuss how to sort objects of the same class based on attribute values. Let’s get started! Suppose we have a class called ‘AppleMusicUser’, with an ‘__init__’ method that initializes an apple user ID: class AppleMusicUser: def __init__(self, apple_id): self.apple_id = apple_id Let’s create an instance of our ‘AppleMusicUser’ class with the email ‘emusk@tesla.com’: user1 = AppleMusicUser("emusk@tesla.com") If we print this object we get: print(user1) Which says the ‘AppleMusicUser’ object is located at the specified memory address. We can change how this object is represented by adding a ‘__repr__’ method: class AppleMusicUser: def __init__(self, apple_id): self.apple_id = apple_id def __repr__(self): return 'AppleID({})'.format(self.apple_id) Now if we print: print(user1) Next, suppose we have a list of ‘AppleMusicUser’ objects: users = [AppleMusicUser("mzuckerberg@facebook.com"), AppleMusicUser("jdorsey@twitter.com"), AppleMusicUser("emusk@tesla.com")] Let’s print the list of objects: print(users) We can sort the list of objects according to the apple ID using the ‘sorted()’ method and a lambda function: print(sorted(users, key = lambda u: u.apple_id)) Alternatively, we can use the ‘attrgetter()’ method in the operator module to define the key in our sorted method: from operator import attrgetterprint(sorted(users, key = attrgetter('appled_id'))) I personally prefer using ‘attrgetter()’ to define the sorting key but using the lambda function also works well. The advantages of using ‘attrgetter()’ are in speed and the ability to pull more than one attribute. For our last example, suppose we have an additional attribute, ‘plays’ , corresponding to the number of songs played: class AppleMusicUser: def __init__(self, apple_id, plays): self.apple_id = apple_id self.plays = plays def __repr__(self): return 'AppleID({}, plays:{})'.format(self.apple_id, self.plays) Let’s redefine our list of objects: users = [AppleMusicUser("mzuckerberg@facebook.com", 100), AppleMusicUser("jdorsey@twitter.com", 20), AppleMusicUser("emusk@tesla.com", 50)]print(users) We can sort the objects according to the number of plays: from operator import attrgetterprint(sorted(users, key = attrgetter('plays'))) I’ll stop here but feel free to play around with the code yourself. To summarize, in this post we discussed how to sort objects in python. First we showed how to sort objects corresponding to instances of the ‘AppleMusicUser’ class according to the attribute ‘apple_id’ using the sorted method and a lambda function. Next, we showed how to perform the same sorting task by using the ‘attrgetter’ method in the operator module. Finally, we showed how to sort according to an additional attribute corresponding to the number of songs played by the user. I hope you found this post useful/interesting. The code from this post is available on GitHub. Thank you for reading!
[ { "code": null, "e": 451, "s": 172, "text": "In computer science, classes are blueprints for defining objects with related attributes and methods. A common task in computer science is sorting data structures based on attributes. In this post, we will discuss how to sort objects of the same class based on attribute values." }, { "code": null, "e": 470, "s": 451, "text": "Let’s get started!" }, { "code": null, "e": 580, "s": 470, "text": "Suppose we have a class called ‘AppleMusicUser’, with an ‘__init__’ method that initializes an apple user ID:" }, { "code": null, "e": 667, "s": 580, "text": "class AppleMusicUser: def __init__(self, apple_id): self.apple_id = apple_id" }, { "code": null, "e": 756, "s": 667, "text": "Let’s create an instance of our ‘AppleMusicUser’ class with the email ‘emusk@tesla.com’:" }, { "code": null, "e": 798, "s": 756, "text": "user1 = AppleMusicUser(\"emusk@tesla.com\")" }, { "code": null, "e": 830, "s": 798, "text": "If we print this object we get:" }, { "code": null, "e": 843, "s": 830, "text": "print(user1)" }, { "code": null, "e": 1002, "s": 843, "text": "Which says the ‘AppleMusicUser’ object is located at the specified memory address. We can change how this object is represented by adding a ‘__repr__’ method:" }, { "code": null, "e": 1162, "s": 1002, "text": "class AppleMusicUser: def __init__(self, apple_id): self.apple_id = apple_id def __repr__(self): return 'AppleID({})'.format(self.apple_id)" }, { "code": null, "e": 1179, "s": 1162, "text": "Now if we print:" }, { "code": null, "e": 1192, "s": 1179, "text": "print(user1)" }, { "code": null, "e": 1250, "s": 1192, "text": "Next, suppose we have a list of ‘AppleMusicUser’ objects:" }, { "code": null, "e": 1377, "s": 1250, "text": "users = [AppleMusicUser(\"mzuckerberg@facebook.com\"), AppleMusicUser(\"jdorsey@twitter.com\"), AppleMusicUser(\"emusk@tesla.com\")]" }, { "code": null, "e": 1410, "s": 1377, "text": "Let’s print the list of objects:" }, { "code": null, "e": 1423, "s": 1410, "text": "print(users)" }, { "code": null, "e": 1532, "s": 1423, "text": "We can sort the list of objects according to the apple ID using the ‘sorted()’ method and a lambda function:" }, { "code": null, "e": 1581, "s": 1532, "text": "print(sorted(users, key = lambda u: u.apple_id))" }, { "code": null, "e": 1696, "s": 1581, "text": "Alternatively, we can use the ‘attrgetter()’ method in the operator module to define the key in our sorted method:" }, { "code": null, "e": 1779, "s": 1696, "text": "from operator import attrgetterprint(sorted(users, key = attrgetter('appled_id')))" }, { "code": null, "e": 1994, "s": 1779, "text": "I personally prefer using ‘attrgetter()’ to define the sorting key but using the lambda function also works well. The advantages of using ‘attrgetter()’ are in speed and the ability to pull more than one attribute." }, { "code": null, "e": 2112, "s": 1994, "text": "For our last example, suppose we have an additional attribute, ‘plays’ , corresponding to the number of songs played:" }, { "code": null, "e": 2328, "s": 2112, "text": "class AppleMusicUser: def __init__(self, apple_id, plays): self.apple_id = apple_id self.plays = plays def __repr__(self): return 'AppleID({}, plays:{})'.format(self.apple_id, self.plays)" }, { "code": null, "e": 2364, "s": 2328, "text": "Let’s redefine our list of objects:" }, { "code": null, "e": 2525, "s": 2364, "text": "users = [AppleMusicUser(\"mzuckerberg@facebook.com\", 100), AppleMusicUser(\"jdorsey@twitter.com\", 20), AppleMusicUser(\"emusk@tesla.com\", 50)]print(users)" }, { "code": null, "e": 2583, "s": 2525, "text": "We can sort the objects according to the number of plays:" }, { "code": null, "e": 2662, "s": 2583, "text": "from operator import attrgetterprint(sorted(users, key = attrgetter('plays')))" }, { "code": null, "e": 2730, "s": 2662, "text": "I’ll stop here but feel free to play around with the code yourself." } ]
Interactive Geospatial Data Visualization with Geoviews in Python | by Abdishakur | Towards Data Science
Interactive Data Visualization has become an integral part of the Data Science process in order to experiment and carry out the first explorative process in data science. There are few options to visualize Geographic data interactively in the Python ecosystem, However, I think Geoviews offers both an easy to use High-level API as well as extensive flexibility. GeoViews is a Python library that makes it easy to explore and visualize geographical, meteorological, and oceanographic datasets, such as those used in weather, climate, and remote sensing research. In this tutorial, we cover the basics components of interactive Geographic data visualization with Geoviews. First, let us import the libraries we use for this tutorial. import pandas as pdimport geopandas as gpdimport geoviews as gvimport geoviews.feature as gffrom geoviews import optsfrom cartopy import crs import geoviews.tile_sources as gtsgv.extension(‘bokeh’, ‘matplotlib’) Next, we start with a simple example showing how to plot coordinates with Geoviews library. Let us create a tuple for these four cities that hold coordinates and the name of the city. stockholm = ( 18.070625,59.320462, “Stockholm”)london = ( -0.135593, 51.507020, “London”)istanbul = ( 28.981856, 41.008327, “Istanbul”)mogadishu = ( 45.299626, 2.042388, “Mogadishu”) We can create simple points using Geoviews functionality. We can also use Pandas but no need for that as well. Once you create a Geoviews feature, you can just pass dframe()to create a DataFrame out of it as shown below. cities = gv.Points([stockholm, london, istanbul, mogadishu], vdims=”City”)cities.dframe() Now, we are ready for our first map with Geoviews. You can simply call the features and it will plot points. However, in this case, we set up some attributes like the colour and size using opts options. cities.opts(opts.Points(global_extent=True, width=500, height=475, size=12, color=’black’)) Below is shown the points map. This is a simple plot and will modify later. However, our points are mapped with their latitude and longitude. However, these points lack a context, and that is where we need base maps. In the next section, we see how to include base maps in the plot. Geoviews offers some neat base maps. Let us see what is available. gv.Layout([ts.relabel(name) for name, ts in gts.tile_sources.items()]).opts( ‘WMTS’, xaxis=None, yaxis=None, width=225, height=225).cols(6) As of this date, there are 19 different base maps you can use in Geoviews, so let us try some of them. gv.tile_sources.OSM.opts( width=800, height=600) The above image shows OpenStreetMap(OSM) base maps for the whole world. Although it is empty right now, it is an interactive map. Next, we overlay the base map and the cities points we created above. (gv.tile_sources.CartoDark * cities).opts(opts.Points(global_extent=True, width=800, height=600, size=8, color=’red’)) In Geoviews, this is as simple as using * to overlay any two (more) features. In our example, we overlay CartoDark base map and city points. As shown in the above map, we can see that city points are in the right position with the help of the base map. In the next section, we cover a very important component in Geographic data science, projections. As we flatten the earth in map making, we introduce some distortions. There are different projections some familiar and others unfamiliar. Let us see how projections distort maps. projections = [crs.RotatedPole, crs.LambertCylindrical, crs.Geostationary, crs.AzimuthalEquidistant, crs.OSGB, crs.EuroPP, crs.Gnomonic, crs.Mollweide, crs.OSNI, crs.Miller, crs.InterruptedGoodeHomolosine, crs.SouthPolarStereo, crs.Orthographic, crs.NorthPolarStereo, crs.Robinson, crs.LambertConformal, crs.AlbersEqualArea]proj_layout = gv.Layout([gf.coastline.relabel(group=p.__name__).opts(projection=p(), backend=’matplotlib’) for p in projections])gv.output(proj_layout, backend=’matplotlib’) The following image shows some of the different projections available to use. We pick the Orthographic (M) projection to visualize distortions. But first, we read the world countries data with Geopandas. Reviews is well integrated with Geopandas library and can be readily used. world = gpd.read_file(gpd.datasets.get_path(‘naturalearth_lowres’))world.head() The world data contains polygon for countries and some other features like pop_estimate, continent etc.. To plot a Polygon data, we just callgv.Polygon() and pass the Geopandas GeodataFrame. world_poly = gv.Polygons(world).opts(color=”gray”, line_color=”white” ) We also create city points but this time with some tweaks. We decrease the point size to 8 and give it a red colour. cities_points = gv.Points(cities).opts(opts.Points(global_extent=True, width=800, height=600, size=8, color=’red’, tools=[‘hover’])) Now, we can overlay the points and polygons. In addition, we provide the projection we want to use in opts parameters. (world_poly * gf.ocean * cities_points).opts(projection=crs.Orthographic(central_longitude=0.1, central_latitude=22), global_extent=True, width=600, tools=[‘hover’]) The following map depicts an Orthographic projection centred in Africa. Next, we learn how to plot Choropoleth map with Geoivews You have already seen how to plot Polygons and we add only one component to plot choropleth map. We only provide the name of the column we want to use for the choropleth. gv.Polygons(world, vdims=[‘name’, ‘pop_est’, ‘gdp_md_est’], label=”World Population”).opts(color=’pop_est’,cmap=’blues’, colorbar=True, xaxis=None, yaxis=None,toolbar=’above’, width=1000, height=700, tools=[‘hover’]) The choropleth map shown below uses a blue colour to classify world population per country. Finally, we cover some neat feature of Geoviews, the interactive widgets. Interactive widgets provide some flexible methods to visualize data. Thanks to Geoviews, you can now create widgets with a lot of complex code. In this example, we learn how to group data and display only one group. Let us say we want to display the continent we like to visualize. First, we group by continent while plotting with gv.Polygon() . coountries_grouped = gv.Polygons(world, vdims=[‘name’, ‘continent’],label=”Continent”).groupby(“continent”) Next, we plot and provide width and height options of the plot. continents = coountries_grouped.opts(width=600, height=400, tools=[‘hover’], infer_projection=True)continents The following GIF shows the widget created with just two lines of code above. Only the selected continent is displayed in the plot. In this tutorial, We have seen how to plot Geospatial data interactively using Geoviews. This tutorial covers some examples showcasing the basics of Geoviews. You might find some interesting tutorials from the official Geoviews gallery, so give it a try. To install Geoviews, You can simply use Conda: conda install -c pyviz geoviews
[ { "code": null, "e": 534, "s": 171, "text": "Interactive Data Visualization has become an integral part of the Data Science process in order to experiment and carry out the first explorative process in data science. There are few options to visualize Geographic data interactively in the Python ecosystem, However, I think Geoviews offers both an easy to use High-level API as well as extensive flexibility." }, { "code": null, "e": 734, "s": 534, "text": "GeoViews is a Python library that makes it easy to explore and visualize geographical, meteorological, and oceanographic datasets, such as those used in weather, climate, and remote sensing research." }, { "code": null, "e": 843, "s": 734, "text": "In this tutorial, we cover the basics components of interactive Geographic data visualization with Geoviews." }, { "code": null, "e": 904, "s": 843, "text": "First, let us import the libraries we use for this tutorial." }, { "code": null, "e": 1116, "s": 904, "text": "import pandas as pdimport geopandas as gpdimport geoviews as gvimport geoviews.feature as gffrom geoviews import optsfrom cartopy import crs import geoviews.tile_sources as gtsgv.extension(‘bokeh’, ‘matplotlib’)" }, { "code": null, "e": 1208, "s": 1116, "text": "Next, we start with a simple example showing how to plot coordinates with Geoviews library." }, { "code": null, "e": 1300, "s": 1208, "text": "Let us create a tuple for these four cities that hold coordinates and the name of the city." }, { "code": null, "e": 1483, "s": 1300, "text": "stockholm = ( 18.070625,59.320462, “Stockholm”)london = ( -0.135593, 51.507020, “London”)istanbul = ( 28.981856, 41.008327, “Istanbul”)mogadishu = ( 45.299626, 2.042388, “Mogadishu”)" }, { "code": null, "e": 1704, "s": 1483, "text": "We can create simple points using Geoviews functionality. We can also use Pandas but no need for that as well. Once you create a Geoviews feature, you can just pass dframe()to create a DataFrame out of it as shown below." }, { "code": null, "e": 1794, "s": 1704, "text": "cities = gv.Points([stockholm, london, istanbul, mogadishu], vdims=”City”)cities.dframe()" }, { "code": null, "e": 1997, "s": 1794, "text": "Now, we are ready for our first map with Geoviews. You can simply call the features and it will plot points. However, in this case, we set up some attributes like the colour and size using opts options." }, { "code": null, "e": 2089, "s": 1997, "text": "cities.opts(opts.Points(global_extent=True, width=500, height=475, size=12, color=’black’))" }, { "code": null, "e": 2231, "s": 2089, "text": "Below is shown the points map. This is a simple plot and will modify later. However, our points are mapped with their latitude and longitude." }, { "code": null, "e": 2372, "s": 2231, "text": "However, these points lack a context, and that is where we need base maps. In the next section, we see how to include base maps in the plot." }, { "code": null, "e": 2439, "s": 2372, "text": "Geoviews offers some neat base maps. Let us see what is available." }, { "code": null, "e": 2579, "s": 2439, "text": "gv.Layout([ts.relabel(name) for name, ts in gts.tile_sources.items()]).opts( ‘WMTS’, xaxis=None, yaxis=None, width=225, height=225).cols(6)" }, { "code": null, "e": 2682, "s": 2579, "text": "As of this date, there are 19 different base maps you can use in Geoviews, so let us try some of them." }, { "code": null, "e": 2731, "s": 2682, "text": "gv.tile_sources.OSM.opts( width=800, height=600)" }, { "code": null, "e": 2861, "s": 2731, "text": "The above image shows OpenStreetMap(OSM) base maps for the whole world. Although it is empty right now, it is an interactive map." }, { "code": null, "e": 2931, "s": 2861, "text": "Next, we overlay the base map and the cities points we created above." }, { "code": null, "e": 3050, "s": 2931, "text": "(gv.tile_sources.CartoDark * cities).opts(opts.Points(global_extent=True, width=800, height=600, size=8, color=’red’))" }, { "code": null, "e": 3191, "s": 3050, "text": "In Geoviews, this is as simple as using * to overlay any two (more) features. In our example, we overlay CartoDark base map and city points." }, { "code": null, "e": 3401, "s": 3191, "text": "As shown in the above map, we can see that city points are in the right position with the help of the base map. In the next section, we cover a very important component in Geographic data science, projections." }, { "code": null, "e": 3581, "s": 3401, "text": "As we flatten the earth in map making, we introduce some distortions. There are different projections some familiar and others unfamiliar. Let us see how projections distort maps." }, { "code": null, "e": 4080, "s": 3581, "text": "projections = [crs.RotatedPole, crs.LambertCylindrical, crs.Geostationary, crs.AzimuthalEquidistant, crs.OSGB, crs.EuroPP, crs.Gnomonic, crs.Mollweide, crs.OSNI, crs.Miller, crs.InterruptedGoodeHomolosine, crs.SouthPolarStereo, crs.Orthographic, crs.NorthPolarStereo, crs.Robinson, crs.LambertConformal, crs.AlbersEqualArea]proj_layout = gv.Layout([gf.coastline.relabel(group=p.__name__).opts(projection=p(), backend=’matplotlib’) for p in projections])gv.output(proj_layout, backend=’matplotlib’)" }, { "code": null, "e": 4158, "s": 4080, "text": "The following image shows some of the different projections available to use." }, { "code": null, "e": 4359, "s": 4158, "text": "We pick the Orthographic (M) projection to visualize distortions. But first, we read the world countries data with Geopandas. Reviews is well integrated with Geopandas library and can be readily used." }, { "code": null, "e": 4439, "s": 4359, "text": "world = gpd.read_file(gpd.datasets.get_path(‘naturalearth_lowres’))world.head()" }, { "code": null, "e": 4544, "s": 4439, "text": "The world data contains polygon for countries and some other features like pop_estimate, continent etc.." }, { "code": null, "e": 4630, "s": 4544, "text": "To plot a Polygon data, we just callgv.Polygon() and pass the Geopandas GeodataFrame." }, { "code": null, "e": 4702, "s": 4630, "text": "world_poly = gv.Polygons(world).opts(color=”gray”, line_color=”white” )" }, { "code": null, "e": 4819, "s": 4702, "text": "We also create city points but this time with some tweaks. We decrease the point size to 8 and give it a red colour." }, { "code": null, "e": 4952, "s": 4819, "text": "cities_points = gv.Points(cities).opts(opts.Points(global_extent=True, width=800, height=600, size=8, color=’red’, tools=[‘hover’]))" }, { "code": null, "e": 5071, "s": 4952, "text": "Now, we can overlay the points and polygons. In addition, we provide the projection we want to use in opts parameters." }, { "code": null, "e": 5237, "s": 5071, "text": "(world_poly * gf.ocean * cities_points).opts(projection=crs.Orthographic(central_longitude=0.1, central_latitude=22), global_extent=True, width=600, tools=[‘hover’])" }, { "code": null, "e": 5309, "s": 5237, "text": "The following map depicts an Orthographic projection centred in Africa." }, { "code": null, "e": 5366, "s": 5309, "text": "Next, we learn how to plot Choropoleth map with Geoivews" }, { "code": null, "e": 5537, "s": 5366, "text": "You have already seen how to plot Polygons and we add only one component to plot choropleth map. We only provide the name of the column we want to use for the choropleth." }, { "code": null, "e": 5754, "s": 5537, "text": "gv.Polygons(world, vdims=[‘name’, ‘pop_est’, ‘gdp_md_est’], label=”World Population”).opts(color=’pop_est’,cmap=’blues’, colorbar=True, xaxis=None, yaxis=None,toolbar=’above’, width=1000, height=700, tools=[‘hover’])" }, { "code": null, "e": 5846, "s": 5754, "text": "The choropleth map shown below uses a blue colour to classify world population per country." }, { "code": null, "e": 5920, "s": 5846, "text": "Finally, we cover some neat feature of Geoviews, the interactive widgets." }, { "code": null, "e": 6202, "s": 5920, "text": "Interactive widgets provide some flexible methods to visualize data. Thanks to Geoviews, you can now create widgets with a lot of complex code. In this example, we learn how to group data and display only one group. Let us say we want to display the continent we like to visualize." }, { "code": null, "e": 6266, "s": 6202, "text": "First, we group by continent while plotting with gv.Polygon() ." }, { "code": null, "e": 6374, "s": 6266, "text": "coountries_grouped = gv.Polygons(world, vdims=[‘name’, ‘continent’],label=”Continent”).groupby(“continent”)" }, { "code": null, "e": 6438, "s": 6374, "text": "Next, we plot and provide width and height options of the plot." }, { "code": null, "e": 6548, "s": 6438, "text": "continents = coountries_grouped.opts(width=600, height=400, tools=[‘hover’], infer_projection=True)continents" }, { "code": null, "e": 6680, "s": 6548, "text": "The following GIF shows the widget created with just two lines of code above. Only the selected continent is displayed in the plot." }, { "code": null, "e": 6935, "s": 6680, "text": "In this tutorial, We have seen how to plot Geospatial data interactively using Geoviews. This tutorial covers some examples showcasing the basics of Geoviews. You might find some interesting tutorials from the official Geoviews gallery, so give it a try." }, { "code": null, "e": 6982, "s": 6935, "text": "To install Geoviews, You can simply use Conda:" } ]
Create your first ETL Pipeline in Apache Spark and Python | by Adnan Siddiqi | Towards Data Science
In this post, I am going to discuss Apache Spark and how you can create simple but robust ETL pipelines in it. You will learn how Spark provides APIs to transform different data format into Data frames and SQL for analysis purpose and how one data source could be transformed into another without any hassle. According to Wikipedia: Apache Spark is an open-source distributed general-purpose cluster-computing framework. Spark provides an interface for programming entire clusters with implicit data parallelism and fault tolerance. From Official Website: Apache SparkTM is a unified analytics engine for large-scale data processing. In short, Apache Spark is a framework which is used for processing, querying and analyzing Big data. Since the computation is done in memory hence it’s multiple fold fasters than the competitors like MapReduce and others. The rate at which terabytes of data is being produced every day, there was a need for a solution that could provide real-time analysis at high speed. Some of the Spark features are: It is 100 times faster than traditional large-scale data processing frameworks. Easy to use as you can write Spark applications in Python, R, and Scala. It provides libraries for SQL, Steaming and Graph computations. It contains the basic functionality of Spark like task scheduling, memory management, interaction with storage, etc. It is a set of libraries used to interact with structured data. It used an SQL like interface to interact with data of various formats like CSV, JSON, Parquet, etc. Spark Streaming is a Spark component that enables the processing of live streams of data. Live streams like Stock data, Weather data, Logs, and various others. MLib is a set of Machine Learning Algorithms offered by Spark for both supervised and unsupervised learning It is Apache Spark’s API for graphs and graph-parallel computation. It extends the Spark RDD API, allowing us to create a directed graph with arbitrary properties attached to each vertex and edge. It provides a uniform tool for ETL, exploratory analysis and iterative graph computations. Spark supports the following resource/cluster managers: Spark Standalone — a simple cluster manager included with Spark Apache Mesos — a general cluster manager that can also run Hadoop applications. Apache Hadoop YARN — the resource manager in Hadoop 2 Kubernetes — an open source system for automating deployment, scaling, and management of containerized applications. Download the binary of Apache Spark from here. You must have Scala installed on the system and its path should also be set. For this tutorial, we are using version 2.4.3 which was released in May 2019. Move the folder in /usr/local mv spark-2.4.3-bin-hadoop2.7 /usr/local/spark And then export the path of both Scala and Spark. #Scala Pathexport PATH="/usr/local/scala/bin:$PATH"#Apache Spark pathexport PATH="/usr/local/spark/bin:$PATH" Invoke the Spark Shell by running the spark-shell command on your terminal. If all goes well, you will see something like below: It loads the Scala based shell. Since we are going to use Python language then we have to install PySpark. pip install pyspark Once it is installed you can invoke it by running the command pyspark in your terminal: You find a typical Python shell but this is loaded with Spark libraries. Let’s start writing our first program. from pyspark.sql import SparkSessionfrom pyspark.sql import SQLContextif __name__ == '__main__': scSpark = SparkSession \ .builder \ .appName("reading csv") \ .getOrCreate() We have imported two libraries: SparkSession and SQLContext. SparkSession is the entry point for programming Spark applications. It let you interact with DataSet and DataFrame APIs provided by Spark. We set the application name by calling appName. The getOrCreate() method either returns a new SparkSession of the app or returns the existing one. Our next objective is to read CSV files. I have created a sample CSV file, called data.csv which looks like below: name,age,countryadnan,40,Pakistanmaaz,9,Pakistanmusab,4,Pakistanayesha,32,Pakistan And the code: if __name__ == '__main__': scSpark = SparkSession \ .builder \ .appName("reading csv") \ .getOrCreate()data_file = '/Development/PetProjects/LearningSpark/data.csv' sdfData = scSpark.read.csv(data_file, header=True, sep=",").cache() print('Total Records = {}'.format(sdfData.count())) sdfData.show() I set the file path and then called .read.csv to read the CSV file. The parameters are self-explanatory. The .cache() caches the returned resultset hence increase the performance. When I run the program it returns something like below: Looks interesting, No? Now, what if I want to read multiple files in a dataframe. Let’s create another file, I call it data1.csv and it looks like below: 1 2 3 4 5 name,age,country noreen,23,England Aamir,9,Pakistan Noman,4,Pakistan Rasheed,12,Pakistan All I have to do this: data_file = '/Development/PetProjects/LearningSpark/data*.csv' and it will read all files starts with dataand of type CSV. What it will do that it’d read all CSV files that match a pattern and dump result: As you can see, it dumps all the data from the CSVs into a single dataframe. Pretty cool huh. But one thing, this dumping will only work if all the CSVs follow a certain schema. If you have a CSV with different column names then it’s gonna return the following message. 19/06/04 18:59:05 WARN CSVDataSource: Number of column in CSV header is not equal to number of fields in the schema: Header length: 3, schema size: 17CSV file: file:///Development/PetProjects/LearningSpark/data.csv As you can see, Spark complains about CSV files that are not the same are unable to be processed. You can perform many operations with DataFrame but Spark provides you much easier and familiar interface to manipulate the data by using SQLContext. It is the gateway to SparkSQL which lets you use SQL like queries to get the desired results. Before we move further, let’s play with some real data. For that purpose, we are using Supermarket’s sales data which I got from Kaggle. Before we try SQL queries, let’s try to group records by Gender. We are dealing with the EXTRACT part of the ETL here. data_file = '/Development/PetProjects/LearningSpark/supermarket_sales.csv'sdfData = scSpark.read.csv(data_file, header=True, sep=",").cache()gender = sdfData.groupBy('Gender').count()print(gender.show()) When you run, it returns something like below: groupBy() groups the data by the given column. In our case, it is the Gender column. SparkSQL allows you to use SQL like queries to access the data. sdfData.registerTempTable("sales")output = scSpark.sql('SELECT * from sales')output.show() First, we create a temporary table out of the dataframe. For that purpose registerTampTable is used. In our case the table name is sales. Once it’s done you can use typical SQL queries on it. In our case it is Select * from sales. Or something like below: output = scSpark.sql('SELECT * from sales WHERE `Unit Price` < 15 AND Quantity < 10')output.show() Or even aggregated values. output = scSpark.sql('SELECT COUNT(*) as total, City from sales GROUP BY City')output.show() Pretty flexible, right? We are just done with the TRANSFORM part of the ETL here. Finally the LOAD part of the ETL. What if you want to save this transformed data? Well, you have many options available, RDBMS, XML or JSON. output.write.format('json').save('filtered.json') When you run it Sparks create the following folder/file structure. It created a folder with the name of the file, in our case it is filtered.json. Then, a file with the name _SUCCESStells whether the operation was a success or not. In case it fails a file with the name _FAILURE is generated. Then, you find multiple files here. The reason for multiple files is that each work is involved in the operation of writing in the file. If you want to create a single file(which is not recommended) then coalesce can be used that collects and reduces the data from all partitions to a single dataframe. output.coalesce(1).write.format('json').save('filtered.json') And it will output the following data: {"total":328,"City":"Naypyitaw"}{"total":332,"City":"Mandalay"}{"total":340,"City":"Yangon"} The above dataframe contains the transformed data. We would like to load this data into MYSQL for further usage like Visualization or showing on an app. First, we need the MySQL connector library to interact with Spark. We will download the connector from MySQL website and put it in a folder. We will amend SparkSession to include the JAR file. scSpark = SparkSession \ .builder \ .appName("reading csv") \ .config("spark.driver.extraClassPath", "/usr/local/spark/jars/mysql-connector-java-8.0.16.jar") \ .getOrCreate() The output now looks like below: output = scSpark.sql('SELECT COUNT(*) as total, City from sales GROUP BY City') output.show() output.write.format('jdbc').options( url='jdbc:mysql://localhost/spark', driver='com.mysql.cj.jdbc.Driver', dbtable='city_info', user='root', password='root').mode('append').save() I created the required Db and table in my DB before running the script. If all goes well you should see the result like below: As you can see, Spark makes it easier to transfer data from One data source to another. Apache Spark is a very demanding and useful Big Data tool that helps to write ETL very easily. You can load the Petabytes of data and can process it without any hassle by setting up a cluster of multiple nodes. This tutorial just gives you the basic idea of Apache Spark’s way of writing ETL. You should check the docs and other resources to dig deeper. This post was originally published here.
[ { "code": null, "e": 480, "s": 171, "text": "In this post, I am going to discuss Apache Spark and how you can create simple but robust ETL pipelines in it. You will learn how Spark provides APIs to transform different data format into Data frames and SQL for analysis purpose and how one data source could be transformed into another without any hassle." }, { "code": null, "e": 504, "s": 480, "text": "According to Wikipedia:" }, { "code": null, "e": 704, "s": 504, "text": "Apache Spark is an open-source distributed general-purpose cluster-computing framework. Spark provides an interface for programming entire clusters with implicit data parallelism and fault tolerance." }, { "code": null, "e": 727, "s": 704, "text": "From Official Website:" }, { "code": null, "e": 805, "s": 727, "text": "Apache SparkTM is a unified analytics engine for large-scale data processing." }, { "code": null, "e": 1209, "s": 805, "text": "In short, Apache Spark is a framework which is used for processing, querying and analyzing Big data. Since the computation is done in memory hence it’s multiple fold fasters than the competitors like MapReduce and others. The rate at which terabytes of data is being produced every day, there was a need for a solution that could provide real-time analysis at high speed. Some of the Spark features are:" }, { "code": null, "e": 1289, "s": 1209, "text": "It is 100 times faster than traditional large-scale data processing frameworks." }, { "code": null, "e": 1362, "s": 1289, "text": "Easy to use as you can write Spark applications in Python, R, and Scala." }, { "code": null, "e": 1426, "s": 1362, "text": "It provides libraries for SQL, Steaming and Graph computations." }, { "code": null, "e": 1543, "s": 1426, "text": "It contains the basic functionality of Spark like task scheduling, memory management, interaction with storage, etc." }, { "code": null, "e": 1708, "s": 1543, "text": "It is a set of libraries used to interact with structured data. It used an SQL like interface to interact with data of various formats like CSV, JSON, Parquet, etc." }, { "code": null, "e": 1868, "s": 1708, "text": "Spark Streaming is a Spark component that enables the processing of live streams of data. Live streams like Stock data, Weather data, Logs, and various others." }, { "code": null, "e": 1976, "s": 1868, "text": "MLib is a set of Machine Learning Algorithms offered by Spark for both supervised and unsupervised learning" }, { "code": null, "e": 2264, "s": 1976, "text": "It is Apache Spark’s API for graphs and graph-parallel computation. It extends the Spark RDD API, allowing us to create a directed graph with arbitrary properties attached to each vertex and edge. It provides a uniform tool for ETL, exploratory analysis and iterative graph computations." }, { "code": null, "e": 2320, "s": 2264, "text": "Spark supports the following resource/cluster managers:" }, { "code": null, "e": 2384, "s": 2320, "text": "Spark Standalone — a simple cluster manager included with Spark" }, { "code": null, "e": 2464, "s": 2384, "text": "Apache Mesos — a general cluster manager that can also run Hadoop applications." }, { "code": null, "e": 2518, "s": 2464, "text": "Apache Hadoop YARN — the resource manager in Hadoop 2" }, { "code": null, "e": 2635, "s": 2518, "text": "Kubernetes — an open source system for automating deployment, scaling, and management of containerized applications." }, { "code": null, "e": 2759, "s": 2635, "text": "Download the binary of Apache Spark from here. You must have Scala installed on the system and its path should also be set." }, { "code": null, "e": 2867, "s": 2759, "text": "For this tutorial, we are using version 2.4.3 which was released in May 2019. Move the folder in /usr/local" }, { "code": null, "e": 2913, "s": 2867, "text": "mv spark-2.4.3-bin-hadoop2.7 /usr/local/spark" }, { "code": null, "e": 2963, "s": 2913, "text": "And then export the path of both Scala and Spark." }, { "code": null, "e": 3073, "s": 2963, "text": "#Scala Pathexport PATH=\"/usr/local/scala/bin:$PATH\"#Apache Spark pathexport PATH=\"/usr/local/spark/bin:$PATH\"" }, { "code": null, "e": 3202, "s": 3073, "text": "Invoke the Spark Shell by running the spark-shell command on your terminal. If all goes well, you will see something like below:" }, { "code": null, "e": 3309, "s": 3202, "text": "It loads the Scala based shell. Since we are going to use Python language then we have to install PySpark." }, { "code": null, "e": 3329, "s": 3309, "text": "pip install pyspark" }, { "code": null, "e": 3417, "s": 3329, "text": "Once it is installed you can invoke it by running the command pyspark in your terminal:" }, { "code": null, "e": 3490, "s": 3417, "text": "You find a typical Python shell but this is loaded with Spark libraries." }, { "code": null, "e": 3529, "s": 3490, "text": "Let’s start writing our first program." }, { "code": null, "e": 3727, "s": 3529, "text": "from pyspark.sql import SparkSessionfrom pyspark.sql import SQLContextif __name__ == '__main__': scSpark = SparkSession \\ .builder \\ .appName(\"reading csv\") \\ .getOrCreate()" }, { "code": null, "e": 3788, "s": 3727, "text": "We have imported two libraries: SparkSession and SQLContext." }, { "code": null, "e": 4074, "s": 3788, "text": "SparkSession is the entry point for programming Spark applications. It let you interact with DataSet and DataFrame APIs provided by Spark. We set the application name by calling appName. The getOrCreate() method either returns a new SparkSession of the app or returns the existing one." }, { "code": null, "e": 4189, "s": 4074, "text": "Our next objective is to read CSV files. I have created a sample CSV file, called data.csv which looks like below:" }, { "code": null, "e": 4272, "s": 4189, "text": "name,age,countryadnan,40,Pakistanmaaz,9,Pakistanmusab,4,Pakistanayesha,32,Pakistan" }, { "code": null, "e": 4286, "s": 4272, "text": "And the code:" }, { "code": null, "e": 4619, "s": 4286, "text": "if __name__ == '__main__': scSpark = SparkSession \\ .builder \\ .appName(\"reading csv\") \\ .getOrCreate()data_file = '/Development/PetProjects/LearningSpark/data.csv' sdfData = scSpark.read.csv(data_file, header=True, sep=\",\").cache() print('Total Records = {}'.format(sdfData.count())) sdfData.show()" }, { "code": null, "e": 4855, "s": 4619, "text": "I set the file path and then called .read.csv to read the CSV file. The parameters are self-explanatory. The .cache() caches the returned resultset hence increase the performance. When I run the program it returns something like below:" }, { "code": null, "e": 5009, "s": 4855, "text": "Looks interesting, No? Now, what if I want to read multiple files in a dataframe. Let’s create another file, I call it data1.csv and it looks like below:" }, { "code": null, "e": 5011, "s": 5009, "text": "1" }, { "code": null, "e": 5013, "s": 5011, "text": "2" }, { "code": null, "e": 5015, "s": 5013, "text": "3" }, { "code": null, "e": 5017, "s": 5015, "text": "4" }, { "code": null, "e": 5019, "s": 5017, "text": "5" }, { "code": null, "e": 5036, "s": 5019, "text": "name,age,country" }, { "code": null, "e": 5054, "s": 5036, "text": "noreen,23,England" }, { "code": null, "e": 5071, "s": 5054, "text": "Aamir,9,Pakistan" }, { "code": null, "e": 5088, "s": 5071, "text": "Noman,4,Pakistan" }, { "code": null, "e": 5108, "s": 5088, "text": "Rasheed,12,Pakistan" }, { "code": null, "e": 5131, "s": 5108, "text": "All I have to do this:" }, { "code": null, "e": 5254, "s": 5131, "text": "data_file = '/Development/PetProjects/LearningSpark/data*.csv' and it will read all files starts with dataand of type CSV." }, { "code": null, "e": 5337, "s": 5254, "text": "What it will do that it’d read all CSV files that match a pattern and dump result:" }, { "code": null, "e": 5431, "s": 5337, "text": "As you can see, it dumps all the data from the CSVs into a single dataframe. Pretty cool huh." }, { "code": null, "e": 5607, "s": 5431, "text": "But one thing, this dumping will only work if all the CSVs follow a certain schema. If you have a CSV with different column names then it’s gonna return the following message." }, { "code": null, "e": 5822, "s": 5607, "text": "19/06/04 18:59:05 WARN CSVDataSource: Number of column in CSV header is not equal to number of fields in the schema: Header length: 3, schema size: 17CSV file: file:///Development/PetProjects/LearningSpark/data.csv" }, { "code": null, "e": 5920, "s": 5822, "text": "As you can see, Spark complains about CSV files that are not the same are unable to be processed." }, { "code": null, "e": 6163, "s": 5920, "text": "You can perform many operations with DataFrame but Spark provides you much easier and familiar interface to manipulate the data by using SQLContext. It is the gateway to SparkSQL which lets you use SQL like queries to get the desired results." }, { "code": null, "e": 6419, "s": 6163, "text": "Before we move further, let’s play with some real data. For that purpose, we are using Supermarket’s sales data which I got from Kaggle. Before we try SQL queries, let’s try to group records by Gender. We are dealing with the EXTRACT part of the ETL here." }, { "code": null, "e": 6623, "s": 6419, "text": "data_file = '/Development/PetProjects/LearningSpark/supermarket_sales.csv'sdfData = scSpark.read.csv(data_file, header=True, sep=\",\").cache()gender = sdfData.groupBy('Gender').count()print(gender.show())" }, { "code": null, "e": 6670, "s": 6623, "text": "When you run, it returns something like below:" }, { "code": null, "e": 6755, "s": 6670, "text": "groupBy() groups the data by the given column. In our case, it is the Gender column." }, { "code": null, "e": 6819, "s": 6755, "text": "SparkSQL allows you to use SQL like queries to access the data." }, { "code": null, "e": 6911, "s": 6819, "text": "sdfData.registerTempTable(\"sales\")output = scSpark.sql('SELECT * from sales')output.show()" }, { "code": null, "e": 7142, "s": 6911, "text": "First, we create a temporary table out of the dataframe. For that purpose registerTampTable is used. In our case the table name is sales. Once it’s done you can use typical SQL queries on it. In our case it is Select * from sales." }, { "code": null, "e": 7167, "s": 7142, "text": "Or something like below:" }, { "code": null, "e": 7266, "s": 7167, "text": "output = scSpark.sql('SELECT * from sales WHERE `Unit Price` < 15 AND Quantity < 10')output.show()" }, { "code": null, "e": 7293, "s": 7266, "text": "Or even aggregated values." }, { "code": null, "e": 7386, "s": 7293, "text": "output = scSpark.sql('SELECT COUNT(*) as total, City from sales GROUP BY City')output.show()" }, { "code": null, "e": 7410, "s": 7386, "text": "Pretty flexible, right?" }, { "code": null, "e": 7468, "s": 7410, "text": "We are just done with the TRANSFORM part of the ETL here." }, { "code": null, "e": 7609, "s": 7468, "text": "Finally the LOAD part of the ETL. What if you want to save this transformed data? Well, you have many options available, RDBMS, XML or JSON." }, { "code": null, "e": 7659, "s": 7609, "text": "output.write.format('json').save('filtered.json')" }, { "code": null, "e": 7726, "s": 7659, "text": "When you run it Sparks create the following folder/file structure." }, { "code": null, "e": 8255, "s": 7726, "text": "It created a folder with the name of the file, in our case it is filtered.json. Then, a file with the name _SUCCESStells whether the operation was a success or not. In case it fails a file with the name _FAILURE is generated. Then, you find multiple files here. The reason for multiple files is that each work is involved in the operation of writing in the file. If you want to create a single file(which is not recommended) then coalesce can be used that collects and reduces the data from all partitions to a single dataframe." }, { "code": null, "e": 8317, "s": 8255, "text": "output.coalesce(1).write.format('json').save('filtered.json')" }, { "code": null, "e": 8356, "s": 8317, "text": "And it will output the following data:" }, { "code": null, "e": 8449, "s": 8356, "text": "{\"total\":328,\"City\":\"Naypyitaw\"}{\"total\":332,\"City\":\"Mandalay\"}{\"total\":340,\"City\":\"Yangon\"}" }, { "code": null, "e": 8602, "s": 8449, "text": "The above dataframe contains the transformed data. We would like to load this data into MYSQL for further usage like Visualization or showing on an app." }, { "code": null, "e": 8795, "s": 8602, "text": "First, we need the MySQL connector library to interact with Spark. We will download the connector from MySQL website and put it in a folder. We will amend SparkSession to include the JAR file." }, { "code": null, "e": 8998, "s": 8795, "text": "scSpark = SparkSession \\ .builder \\ .appName(\"reading csv\") \\ .config(\"spark.driver.extraClassPath\", \"/usr/local/spark/jars/mysql-connector-java-8.0.16.jar\") \\ .getOrCreate()" }, { "code": null, "e": 9031, "s": 8998, "text": "The output now looks like below:" }, { "code": null, "e": 9347, "s": 9031, "text": "output = scSpark.sql('SELECT COUNT(*) as total, City from sales GROUP BY City') output.show() output.write.format('jdbc').options( url='jdbc:mysql://localhost/spark', driver='com.mysql.cj.jdbc.Driver', dbtable='city_info', user='root', password='root').mode('append').save()" }, { "code": null, "e": 9474, "s": 9347, "text": "I created the required Db and table in my DB before running the script. If all goes well you should see the result like below:" }, { "code": null, "e": 9562, "s": 9474, "text": "As you can see, Spark makes it easier to transfer data from One data source to another." }, { "code": null, "e": 9916, "s": 9562, "text": "Apache Spark is a very demanding and useful Big Data tool that helps to write ETL very easily. You can load the Petabytes of data and can process it without any hassle by setting up a cluster of multiple nodes. This tutorial just gives you the basic idea of Apache Spark’s way of writing ETL. You should check the docs and other resources to dig deeper." } ]
Embedding Tableau in Streamlit. How to view your Tableau dashboard on... | by Okoh Anita | Towards Data Science
As 2020 draws to its ends (hopefully along with its chaos), I took a step back to reminisce about all the tools/skills I have picked up this year and all the tools I really didn’t use so much this year. One tool I really didn’t use so much is Tableau. Tableau is a powerful data visualization tool that creates visually-appealing dashboards. I decided to find a dataset to analyze and visualize on Tableau. One tool that I picked up this year and I have used quite frequently is Streamlit. Streamlit is such an awesome tool for data scientists. Instead of visualizing data on Tableau alone, I decided to embed the Tableau dashboard into streamlit in order to interact with the dashboard on Streamlit. N.B: In order to follow along, make sure you have a tableau dashboard or visualization that is already saved on the tableau public website. You can find out how to save your visualization on Tableau Public here. You should also have a basic knowledge of Streamlit. You can find its documentation here. Copy the Tableau Public Dashboard embedded code Copy the Tableau Public Dashboard embedded code On your Tableau Public Dashboard, locate the share button at the bottom right of the dashboard and check on it. You get a pop-up box that looks like this Copy the code in the Embed Code section. 2. Use Streamlit Components This year, Streamlit introduced streamlit components which is a good method to render HTML, CSS, and Javascript output. Learn more about streamlit components here. After importing streamlit and streamlit components, input the copied embed code as a docstring argument into the method: streamlit.components.v1.html() This is what it looks like in code import streamlit as stimport streamlit.components.v1 as componentsdef main(): html_temp = """your embedded code""" components.html(html_temp)if __name__ == "__main__": main() The components.v1.html() also has other argument options that can be used to customize the width and height of the dashboard displayed. You may need to utilize these options especially to display the full size of a tableau dashboard. The Tableau embedding did not seem to work on Streamlit iframes. This is why I didn’t use the streamlit.components.v1.iframe() method 3. Deploy the Streamlit app to a Server One of the things I discovered while working on this project is that the Tableau dashboard on streamlit is rendered as an image when locally host until the app is deployed to a server. This means that the dashboard displayed will not be interactive unless it is publicly hosted either using Heroku or other hosting services. You can find out how to deploy streamlit apps to Heroku here Below is a Video Demo of my visualization results on Streamlit. Clip ID: 493059591 Delivery:application/vnd.vimeo.dash+json Embed Size:692×433 Separate AV:true Dropped Frames:0 / 0 - 0 Playhead / Buffer:0 / 0 / 0 Bandwidth:0(0 Kbps0 Kbps) You can also play around with the above app here and find source code here. The most difficult part of this project was figuring out my dashboard would only be interactive if the app is deployed on a server. This has to do with the Javascript API from Tableau which was outputting an error in the localhost and returning a static dashboard. Want to be informed on my next project ideas? Fill this form to get notified
[ { "code": null, "e": 424, "s": 172, "text": "As 2020 draws to its ends (hopefully along with its chaos), I took a step back to reminisce about all the tools/skills I have picked up this year and all the tools I really didn’t use so much this year. One tool I really didn’t use so much is Tableau." }, { "code": null, "e": 514, "s": 424, "text": "Tableau is a powerful data visualization tool that creates visually-appealing dashboards." }, { "code": null, "e": 579, "s": 514, "text": "I decided to find a dataset to analyze and visualize on Tableau." }, { "code": null, "e": 662, "s": 579, "text": "One tool that I picked up this year and I have used quite frequently is Streamlit." }, { "code": null, "e": 717, "s": 662, "text": "Streamlit is such an awesome tool for data scientists." }, { "code": null, "e": 873, "s": 717, "text": "Instead of visualizing data on Tableau alone, I decided to embed the Tableau dashboard into streamlit in order to interact with the dashboard on Streamlit." }, { "code": null, "e": 1175, "s": 873, "text": "N.B: In order to follow along, make sure you have a tableau dashboard or visualization that is already saved on the tableau public website. You can find out how to save your visualization on Tableau Public here. You should also have a basic knowledge of Streamlit. You can find its documentation here." }, { "code": null, "e": 1223, "s": 1175, "text": "Copy the Tableau Public Dashboard embedded code" }, { "code": null, "e": 1271, "s": 1223, "text": "Copy the Tableau Public Dashboard embedded code" }, { "code": null, "e": 1425, "s": 1271, "text": "On your Tableau Public Dashboard, locate the share button at the bottom right of the dashboard and check on it. You get a pop-up box that looks like this" }, { "code": null, "e": 1466, "s": 1425, "text": "Copy the code in the Embed Code section." }, { "code": null, "e": 1494, "s": 1466, "text": "2. Use Streamlit Components" }, { "code": null, "e": 1658, "s": 1494, "text": "This year, Streamlit introduced streamlit components which is a good method to render HTML, CSS, and Javascript output. Learn more about streamlit components here." }, { "code": null, "e": 1810, "s": 1658, "text": "After importing streamlit and streamlit components, input the copied embed code as a docstring argument into the method: streamlit.components.v1.html()" }, { "code": null, "e": 1845, "s": 1810, "text": "This is what it looks like in code" }, { "code": null, "e": 2033, "s": 1845, "text": "import streamlit as stimport streamlit.components.v1 as componentsdef main(): html_temp = \"\"\"your embedded code\"\"\" components.html(html_temp)if __name__ == \"__main__\": main()" }, { "code": null, "e": 2267, "s": 2033, "text": "The components.v1.html() also has other argument options that can be used to customize the width and height of the dashboard displayed. You may need to utilize these options especially to display the full size of a tableau dashboard." }, { "code": null, "e": 2401, "s": 2267, "text": "The Tableau embedding did not seem to work on Streamlit iframes. This is why I didn’t use the streamlit.components.v1.iframe() method" }, { "code": null, "e": 2441, "s": 2401, "text": "3. Deploy the Streamlit app to a Server" }, { "code": null, "e": 2766, "s": 2441, "text": "One of the things I discovered while working on this project is that the Tableau dashboard on streamlit is rendered as an image when locally host until the app is deployed to a server. This means that the dashboard displayed will not be interactive unless it is publicly hosted either using Heroku or other hosting services." }, { "code": null, "e": 2827, "s": 2766, "text": "You can find out how to deploy streamlit apps to Heroku here" }, { "code": null, "e": 2891, "s": 2827, "text": "Below is a Video Demo of my visualization results on Streamlit." }, { "code": null, "e": 2910, "s": 2891, "text": "Clip ID: 493059591" }, { "code": null, "e": 2951, "s": 2910, "text": "Delivery:application/vnd.vimeo.dash+json" }, { "code": null, "e": 2971, "s": 2951, "text": "Embed Size:692×433 " }, { "code": null, "e": 2988, "s": 2971, "text": "Separate AV:true" }, { "code": null, "e": 3013, "s": 2988, "text": "Dropped Frames:0 / 0 - 0" }, { "code": null, "e": 3041, "s": 3013, "text": "Playhead / Buffer:0 / 0 / 0" }, { "code": null, "e": 3067, "s": 3041, "text": "Bandwidth:0(0 Kbps0 Kbps)" }, { "code": null, "e": 3143, "s": 3067, "text": "You can also play around with the above app here and find source code here." }, { "code": null, "e": 3408, "s": 3143, "text": "The most difficult part of this project was figuring out my dashboard would only be interactive if the app is deployed on a server. This has to do with the Javascript API from Tableau which was outputting an error in the localhost and returning a static dashboard." } ]
How to Get Data from APIs with Python 🐍 | by Jeff Hale | Towards Data Science
It’s a bit of a cliche to say that data is the new oil. I like to think of it more as a renewable resource like wind.💨 Whatever energy source you choose as your metaphor, you want to harness some of its power! ⚡️ Ideally, you have direct access to the data you want in a file or a database you control. When that’s not the case, if you’re lucky, the data will be available through a public-facing an API. ☘️ In this article, I’ll show you the steps to get the data from a public API using Python. 🐍 First I’ll show you how and where to look for a Python API wrapper and share the largest repository of Python API wrappers. 🎉 Then I’ll show you how to use the requests library to get the data you want from an API that doesn’t have a Python wrapper. If the data you want is on a website, but not available through a public-facing API, there are several options for scraping it. When to use which scraping package is a whole other article I have in the works. Follow me to make sure you don’t miss it! 😁 Let’s drill down! An external facing Application Programming Interface (API) is often intended to provide data in large chunks. You just need to know how to work with the API. An organization creates a public-facing API with the intent that you use it. Their motivations vary from idealistic to mercenary and might include the following: Hoping you’ll build something that will improve the world. 🌍Hoping you’ll use their free plan and then need so much data or need the data so frequently you’ll pay them for access to more data. 💵Figuring you’ll scrape the data from the website if they don’t give you a direct line to it, so they might as well reduce their server overhead and make your experience better. 😀 Hoping you’ll build something that will improve the world. 🌍 Hoping you’ll use their free plan and then need so much data or need the data so frequently you’ll pay them for access to more data. 💵 Figuring you’ll scrape the data from the website if they don’t give you a direct line to it, so they might as well reduce their server overhead and make your experience better. 😀 APIs can be documented well, poorly, or somewhere in between. If you’re lucky, they are well-documented. If you’re really lucky there is a Python wrapper for the API that works and is well documented. 🎉 It can be tricky to find Python wrappers for the API you need. Here’s my suggested approach. I am maintaining what I believe is the largest list of Python API wrappers over at GitHub. Real Python made a nice list that was forked and updated by johnwmiller. I cleaned the list up a bit and then, given that coronavirus quarantine ended my children’s ability to earn money from soccer refereeing ⚽️ and cat sitting 🐈, I paid them to help improve the list. We updated and augmented this outdated list because I couldn’t find a good list of functioning API wrappers elsewhere. 😀 If you find a Python API wrapper that is missing from the list, please edit the ReadMe file and submit a pull request. Here’s a quick guide to editing GitHub Markdown files in the GUI, if you’re new to this: Click the pencil icon in the right corner and make changes (here’s a lovely Markdown tutorial if you need it). Then click the green Propose file change button at the bottom of the page. Then click on the green Create pull request button, summarize the changes, and click on the green Create pull request button at the bottom. Thank you! 🎉 FYI, I often highlight Python packages on my Data Awesome mailing list. In the next installment I’ll be highlighting yfinance by Ran Aroussi. yfinance wraps the Yahoo Finance API. You can use it to read stock market data into a pandas DataFrame with one line of code. 🚀 If the Python API wrapper list doesn’t have what you need, I suggest you use the usual method for finding things on the interwebs. 🕸 A good search engine is a developer or data scientist’s best friend 😁 Specifically, I would search for Python wrapper the_name_of_the_api_I’m_looking_for. GitHub links are likely to be the most fruitful. If a repo hasn’t been updated in the past several years or has been archived, your odds of being able to successfully use the wrapper aren’t high. In that case, I suggest you keep looking. 👓 If you’re lucky, the website for the API you are using might list wrappers available in various programming languages. It’s worth a try. 😃 When there isn’t an API wrapper, you have toto query the API directly. I suggest you use the Python requests library. The venerable requests library is the battle-tested way to get information from an API. Requests was created by Kenneth Reitz and is protected by the Python Software Foundation. It’s the most downloaded Python package as of this writing. 👍 Install requests into your environment from the command line with pip install requests Then import it and use it. Use the HTTP verbs get and post as methods to return the information you desire. Mostly, you’ll use get. Here’s how to query the GitHub API: import requestsr = requests.get('https://api.github.com/events') You can pass parameters to the get method as a dictionary. Here’s the quick start guide. You’ll often get back JSON when you make a get request. You can use the requests .json() method to change JSON into a dictionary quickly. my_dict = r.json() Requests uses the urllib3 library under the hood and enhances it. There are other libraries you could use, but requests is super solid, is nice to use, and is familiar to most Python coders. I suggest you use requests whenever you want to make an API call and the API doesn’t have a Python wrapper. Speaking of which, if your favorite API doesn’t have a Python wrapper, I encourage you to considering making one. 👍 Making a an API wrapper is a great way to learn Python packaging skills. Here’s a guide I wrote to get you started with making a Python package and releasing it on PyPi. I created Pybraries, a Python wrapper for the Libraries.io API. Making it was a great learning experience, and it was cool to give back to the open source community that I’ve benefited from. 🚀 API keys, rate limits, and cURL are three other terms you should be familiar with. You’ll often need an API key to query the API. The API docs should make it clear how you can procure a key. Most of the time, you can get one for free by signing up at the website of the organization whose data you want. If you want a lot of data or want it frequently, you might have to pay for the privilege. You can store your API key in an environment variable. Here’s a guide for setting up environment variables on Mac, Linux, and Windows. Environment variable names are ALL CAPS by convention. Speaking of all caps: ⚠️ DO NOT, UNDER ANY CIRCUMSTANCES, STORE AN API KEY IN GITHUB OR ANOTHER PUBLICLY ACCESSIBLE ONLINE VERSION CONTROL SYSTEM. ⚠️ Your key could get stolen and abused — especially if your account has a credit card attached to it. ☹️ To access the environment variable that holds your API key in Python, import the os module and get the value from the dictionary with the key that matches the name of your environment variable. For example: import osos.environ.get('MYENVIRONMENTVARIABLE') This code returns the value of your MYENVIRONMENTVARIABLE environment variable. If you will be using your key in applications on the cloud, you should look into secrets management, as discussed here. Speaking of staying out of trouble, let’s discuss rate limits. Many APIs limit how many times you can ping them in a given amount of time to avoid needing to pay for lots of extra servers. To avoid going over these limits, you can use the Python time library and put your request into a loop. For example, here’s a brief snippet of code that waits for five seconds between requests. import timeimport requestst = 0my_url = 'https://example.com'while t < 100: r = requests.get(my_url) time.sleep(5) # wait five seconds t += 1 print(r.json()) The point of this code is to show you how you can use time.sleep() to avoid nonstop API endpoint pings that might push you over a rate limit. In a real use case, you would probably want to save your data in some way and use a try...except block. This is a guide for using Python with APIs, but you should know that you can query an API from the command line with the popular cURL program. cURL is included on Macs and machines running recent Windows 10 versions by default. If you want to learn cURL, I suggest you check out the free ebook Conquering the Command Line, by Mark Bates. 🚀 If you want to get data from an API, try to find a Python wrapper first. Check out the list of Python wrappers here. Google search if that fails, and check out the API website. If you find a Python wrapper missing from my list on GitHub please add it. 😀 If there isn’t a Python wrapper for an API, use the requests library. If you have the time, consider creating a wrapper so all Python users can benefit. ❤️ Don’t forget to keep your API keys safe and avoid hitting rate limits. 🔑 You’ve learned a workflow for finding and using APIs with Python. You’re on your way to getting the data you need to do awesome things! 🚀 I hope you found this guide to using APIs with Python useful. If you did, please share it on your favorite social media so other folks can find it, too. 👍 I write about Python, SQL, Docker, data science, and other tech topics. If any of that’s of interest to you, follow me and read more here. 😀
[ { "code": null, "e": 384, "s": 171, "text": "It’s a bit of a cliche to say that data is the new oil. I like to think of it more as a renewable resource like wind.💨 Whatever energy source you choose as your metaphor, you want to harness some of its power! ⚡️" }, { "code": null, "e": 579, "s": 384, "text": "Ideally, you have direct access to the data you want in a file or a database you control. When that’s not the case, if you’re lucky, the data will be available through a public-facing an API. ☘️" }, { "code": null, "e": 796, "s": 579, "text": "In this article, I’ll show you the steps to get the data from a public API using Python. 🐍 First I’ll show you how and where to look for a Python API wrapper and share the largest repository of Python API wrappers. 🎉" }, { "code": null, "e": 920, "s": 796, "text": "Then I’ll show you how to use the requests library to get the data you want from an API that doesn’t have a Python wrapper." }, { "code": null, "e": 1173, "s": 920, "text": "If the data you want is on a website, but not available through a public-facing API, there are several options for scraping it. When to use which scraping package is a whole other article I have in the works. Follow me to make sure you don’t miss it! 😁" }, { "code": null, "e": 1191, "s": 1173, "text": "Let’s drill down!" }, { "code": null, "e": 1349, "s": 1191, "text": "An external facing Application Programming Interface (API) is often intended to provide data in large chunks. You just need to know how to work with the API." }, { "code": null, "e": 1511, "s": 1349, "text": "An organization creates a public-facing API with the intent that you use it. Their motivations vary from idealistic to mercenary and might include the following:" }, { "code": null, "e": 1884, "s": 1511, "text": "Hoping you’ll build something that will improve the world. 🌍Hoping you’ll use their free plan and then need so much data or need the data so frequently you’ll pay them for access to more data. 💵Figuring you’ll scrape the data from the website if they don’t give you a direct line to it, so they might as well reduce their server overhead and make your experience better. 😀" }, { "code": null, "e": 1945, "s": 1884, "text": "Hoping you’ll build something that will improve the world. 🌍" }, { "code": null, "e": 2080, "s": 1945, "text": "Hoping you’ll use their free plan and then need so much data or need the data so frequently you’ll pay them for access to more data. 💵" }, { "code": null, "e": 2259, "s": 2080, "text": "Figuring you’ll scrape the data from the website if they don’t give you a direct line to it, so they might as well reduce their server overhead and make your experience better. 😀" }, { "code": null, "e": 2462, "s": 2259, "text": "APIs can be documented well, poorly, or somewhere in between. If you’re lucky, they are well-documented. If you’re really lucky there is a Python wrapper for the API that works and is well documented. 🎉" }, { "code": null, "e": 2555, "s": 2462, "text": "It can be tricky to find Python wrappers for the API you need. Here’s my suggested approach." }, { "code": null, "e": 3037, "s": 2555, "text": "I am maintaining what I believe is the largest list of Python API wrappers over at GitHub. Real Python made a nice list that was forked and updated by johnwmiller. I cleaned the list up a bit and then, given that coronavirus quarantine ended my children’s ability to earn money from soccer refereeing ⚽️ and cat sitting 🐈, I paid them to help improve the list. We updated and augmented this outdated list because I couldn’t find a good list of functioning API wrappers elsewhere. 😀" }, { "code": null, "e": 3245, "s": 3037, "text": "If you find a Python API wrapper that is missing from the list, please edit the ReadMe file and submit a pull request. Here’s a quick guide to editing GitHub Markdown files in the GUI, if you’re new to this:" }, { "code": null, "e": 3584, "s": 3245, "text": "Click the pencil icon in the right corner and make changes (here’s a lovely Markdown tutorial if you need it). Then click the green Propose file change button at the bottom of the page. Then click on the green Create pull request button, summarize the changes, and click on the green Create pull request button at the bottom. Thank you! 🎉" }, { "code": null, "e": 3854, "s": 3584, "text": "FYI, I often highlight Python packages on my Data Awesome mailing list. In the next installment I’ll be highlighting yfinance by Ran Aroussi. yfinance wraps the Yahoo Finance API. You can use it to read stock market data into a pandas DataFrame with one line of code. 🚀" }, { "code": null, "e": 3987, "s": 3854, "text": "If the Python API wrapper list doesn’t have what you need, I suggest you use the usual method for finding things on the interwebs. 🕸" }, { "code": null, "e": 4057, "s": 3987, "text": "A good search engine is a developer or data scientist’s best friend 😁" }, { "code": null, "e": 4382, "s": 4057, "text": "Specifically, I would search for Python wrapper the_name_of_the_api_I’m_looking_for. GitHub links are likely to be the most fruitful. If a repo hasn’t been updated in the past several years or has been archived, your odds of being able to successfully use the wrapper aren’t high. In that case, I suggest you keep looking. 👓" }, { "code": null, "e": 4521, "s": 4382, "text": "If you’re lucky, the website for the API you are using might list wrappers available in various programming languages. It’s worth a try. 😃" }, { "code": null, "e": 4639, "s": 4521, "text": "When there isn’t an API wrapper, you have toto query the API directly. I suggest you use the Python requests library." }, { "code": null, "e": 4879, "s": 4639, "text": "The venerable requests library is the battle-tested way to get information from an API. Requests was created by Kenneth Reitz and is protected by the Python Software Foundation. It’s the most downloaded Python package as of this writing. 👍" }, { "code": null, "e": 4966, "s": 4879, "text": "Install requests into your environment from the command line with pip install requests" }, { "code": null, "e": 5134, "s": 4966, "text": "Then import it and use it. Use the HTTP verbs get and post as methods to return the information you desire. Mostly, you’ll use get. Here’s how to query the GitHub API:" }, { "code": null, "e": 5199, "s": 5134, "text": "import requestsr = requests.get('https://api.github.com/events')" }, { "code": null, "e": 5288, "s": 5199, "text": "You can pass parameters to the get method as a dictionary. Here’s the quick start guide." }, { "code": null, "e": 5426, "s": 5288, "text": "You’ll often get back JSON when you make a get request. You can use the requests .json() method to change JSON into a dictionary quickly." }, { "code": null, "e": 5445, "s": 5426, "text": "my_dict = r.json()" }, { "code": null, "e": 5744, "s": 5445, "text": "Requests uses the urllib3 library under the hood and enhances it. There are other libraries you could use, but requests is super solid, is nice to use, and is familiar to most Python coders. I suggest you use requests whenever you want to make an API call and the API doesn’t have a Python wrapper." }, { "code": null, "e": 5860, "s": 5744, "text": "Speaking of which, if your favorite API doesn’t have a Python wrapper, I encourage you to considering making one. 👍" }, { "code": null, "e": 6030, "s": 5860, "text": "Making a an API wrapper is a great way to learn Python packaging skills. Here’s a guide I wrote to get you started with making a Python package and releasing it on PyPi." }, { "code": null, "e": 6223, "s": 6030, "text": "I created Pybraries, a Python wrapper for the Libraries.io API. Making it was a great learning experience, and it was cool to give back to the open source community that I’ve benefited from. 🚀" }, { "code": null, "e": 6306, "s": 6223, "text": "API keys, rate limits, and cURL are three other terms you should be familiar with." }, { "code": null, "e": 6617, "s": 6306, "text": "You’ll often need an API key to query the API. The API docs should make it clear how you can procure a key. Most of the time, you can get one for free by signing up at the website of the organization whose data you want. If you want a lot of data or want it frequently, you might have to pay for the privilege." }, { "code": null, "e": 6829, "s": 6617, "text": "You can store your API key in an environment variable. Here’s a guide for setting up environment variables on Mac, Linux, and Windows. Environment variable names are ALL CAPS by convention. Speaking of all caps:" }, { "code": null, "e": 6957, "s": 6829, "text": "⚠️ DO NOT, UNDER ANY CIRCUMSTANCES, STORE AN API KEY IN GITHUB OR ANOTHER PUBLICLY ACCESSIBLE ONLINE VERSION CONTROL SYSTEM. ⚠️" }, { "code": null, "e": 7060, "s": 6957, "text": "Your key could get stolen and abused — especially if your account has a credit card attached to it. ☹️" }, { "code": null, "e": 7267, "s": 7060, "text": "To access the environment variable that holds your API key in Python, import the os module and get the value from the dictionary with the key that matches the name of your environment variable. For example:" }, { "code": null, "e": 7316, "s": 7267, "text": "import osos.environ.get('MYENVIRONMENTVARIABLE')" }, { "code": null, "e": 7396, "s": 7316, "text": "This code returns the value of your MYENVIRONMENTVARIABLE environment variable." }, { "code": null, "e": 7516, "s": 7396, "text": "If you will be using your key in applications on the cloud, you should look into secrets management, as discussed here." }, { "code": null, "e": 7579, "s": 7516, "text": "Speaking of staying out of trouble, let’s discuss rate limits." }, { "code": null, "e": 7899, "s": 7579, "text": "Many APIs limit how many times you can ping them in a given amount of time to avoid needing to pay for lots of extra servers. To avoid going over these limits, you can use the Python time library and put your request into a loop. For example, here’s a brief snippet of code that waits for five seconds between requests." }, { "code": null, "e": 8080, "s": 7899, "text": "import timeimport requestst = 0my_url = 'https://example.com'while t < 100: r = requests.get(my_url) time.sleep(5) # wait five seconds t += 1 print(r.json())" }, { "code": null, "e": 8326, "s": 8080, "text": "The point of this code is to show you how you can use time.sleep() to avoid nonstop API endpoint pings that might push you over a rate limit. In a real use case, you would probably want to save your data in some way and use a try...except block." }, { "code": null, "e": 8666, "s": 8326, "text": "This is a guide for using Python with APIs, but you should know that you can query an API from the command line with the popular cURL program. cURL is included on Macs and machines running recent Windows 10 versions by default. If you want to learn cURL, I suggest you check out the free ebook Conquering the Command Line, by Mark Bates. 🚀" }, { "code": null, "e": 8920, "s": 8666, "text": "If you want to get data from an API, try to find a Python wrapper first. Check out the list of Python wrappers here. Google search if that fails, and check out the API website. If you find a Python wrapper missing from my list on GitHub please add it. 😀" }, { "code": null, "e": 9076, "s": 8920, "text": "If there isn’t a Python wrapper for an API, use the requests library. If you have the time, consider creating a wrapper so all Python users can benefit. ❤️" }, { "code": null, "e": 9149, "s": 9076, "text": "Don’t forget to keep your API keys safe and avoid hitting rate limits. 🔑" }, { "code": null, "e": 9287, "s": 9149, "text": "You’ve learned a workflow for finding and using APIs with Python. You’re on your way to getting the data you need to do awesome things! 🚀" }, { "code": null, "e": 9442, "s": 9287, "text": "I hope you found this guide to using APIs with Python useful. If you did, please share it on your favorite social media so other folks can find it, too. 👍" } ]
Kth Smallest Element in a BST in Python
Suppose we have a binary search tree. We have to find the Kth smallest element in that BST. So if the tree is like − So if we want to find 3rd smallest element, then k = 3, and result will be 7. To solve this, we will follow these steps − create one empty list called nodes call solve(root, nodes) return k – 1th element of nodes the solve method is created, this takes root and nodes array, this will work as follows − if root is null, then return solve(left of root, nodes) add value of root into the nodes array solve(right of root, nodes) Let us see the following implementation to get better understanding − Live Demo class TreeNode: def __init__(self, data, left = None, right = None): self.data = data self.left = left self.right = right def insert(temp,data): que = [] que.append(temp) while (len(que)): temp = que[0] que.pop(0) if (not temp.left): temp.left = TreeNode(data) break else: que.append(temp.left) if (not temp.right): temp.right = TreeNode(data) break else: que.append(temp.right) def make_tree(elements): Tree = TreeNode(elements[0]) for element in elements[1:]: insert(Tree, element) return Tree class Solution(object): def kthSmallest(self, root, k): nodes = [] self.solve(root,nodes) return nodes[k-1] def solve(self, root,nodes): if root == None: return self.solve(root.left,nodes) nodes.append(root.data) self.solve(root.right,nodes) ob1 = Solution() tree = make_tree([10,5,15,2,7,13]) print(ob1.kthSmallest(tree, 3)) [10,5,15,2,7,13] 3 7
[ { "code": null, "e": 1179, "s": 1062, "text": "Suppose we have a binary search tree. We have to find the Kth smallest element in that BST. So if the tree is like −" }, { "code": null, "e": 1257, "s": 1179, "text": "So if we want to find 3rd smallest element, then k = 3, and result will be 7." }, { "code": null, "e": 1301, "s": 1257, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1336, "s": 1301, "text": "create one empty list called nodes" }, { "code": null, "e": 1360, "s": 1336, "text": "call solve(root, nodes)" }, { "code": null, "e": 1392, "s": 1360, "text": "return k – 1th element of nodes" }, { "code": null, "e": 1482, "s": 1392, "text": "the solve method is created, this takes root and nodes array, this will work as follows −" }, { "code": null, "e": 1511, "s": 1482, "text": "if root is null, then return" }, { "code": null, "e": 1538, "s": 1511, "text": "solve(left of root, nodes)" }, { "code": null, "e": 1577, "s": 1538, "text": "add value of root into the nodes array" }, { "code": null, "e": 1605, "s": 1577, "text": "solve(right of root, nodes)" }, { "code": null, "e": 1675, "s": 1605, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 1686, "s": 1675, "text": " Live Demo" }, { "code": null, "e": 2700, "s": 1686, "text": "class TreeNode:\n def __init__(self, data, left = None, right = None):\n self.data = data\n self.left = left\n self.right = right\ndef insert(temp,data):\n que = []\n que.append(temp)\n while (len(que)):\n temp = que[0]\n que.pop(0)\n if (not temp.left):\n temp.left = TreeNode(data)\n break\n else:\n que.append(temp.left)\n if (not temp.right):\n temp.right = TreeNode(data)\n break\n else:\n que.append(temp.right)\ndef make_tree(elements):\n Tree = TreeNode(elements[0])\n for element in elements[1:]:\n insert(Tree, element)\n return Tree\nclass Solution(object):\n def kthSmallest(self, root, k):\n nodes = []\n self.solve(root,nodes)\n return nodes[k-1]\n def solve(self, root,nodes):\n if root == None:\n return\n self.solve(root.left,nodes)\n nodes.append(root.data)\n self.solve(root.right,nodes)\nob1 = Solution()\ntree = make_tree([10,5,15,2,7,13])\nprint(ob1.kthSmallest(tree, 3))" }, { "code": null, "e": 2719, "s": 2700, "text": "[10,5,15,2,7,13]\n3" }, { "code": null, "e": 2721, "s": 2719, "text": "7" } ]
How to Sort an ArrayList of Objects by Property in Java? - GeeksforGeeks
28 Dec, 2020 ArrayList in Java (equivalent to vector in C++) having a dynamic size. It can be shrinked or expanded based on size. ArrayList is a part of the collection framework and is present in java.util package. ArrayList <E> list = new ArrayList <> (); Approach 1: In the below program, we’ve defined a CustomObject class with a String property, customProperty.We’ve also added a constructor that initializes the property, and a getter function getCustomProperty() which returns customProperty.In the main() method, we’ve created an array list of custom objects list, initialized with 5 objects.For sorting the list with the given property, we use the list‘s sort() method.The sort() method takes the list to be sorted (final sorted list is also the same) and a comparator. In the below program, we’ve defined a CustomObject class with a String property, customProperty. We’ve also added a constructor that initializes the property, and a getter function getCustomProperty() which returns customProperty. In the main() method, we’ve created an array list of custom objects list, initialized with 5 objects. For sorting the list with the given property, we use the list‘s sort() method. The sort() method takes the list to be sorted (final sorted list is also the same) and a comparator. In our case, the comparator is a lambda which- Takes two objects from the list o1 and o2, Compares the two object’s customProperty using compareTo() method, And finally returns a positive number if o1’s property is greater than o2’s, negative if o1’s property is lesser than o2’s, and zero if they are equal. Based on this, the list is sorted based on the least property to greatest and stored back to list. Code: Java // Java program to sort the ArrayList// of objects by property import java.util.*; // Define a custom class with custom property// It takes and stores custom objectsclass CustomObject { private String customProperty; public CustomObject(String property) { this.customProperty = property; } public String getCustomProperty() { return this.customProperty; }} public class GFG { // printing sorted ArrayList objects using enchanced // for loop public static void print(ArrayList<CustomObject> list) { for (CustomObject obj : list) { System.out.println(obj.getCustomProperty()); } } // Comparison done using compareTo function public static void sort(ArrayList<CustomObject> list) { list.sort((o1, o2) -> o1.getCustomProperty().compareTo( o2.getCustomProperty())); } // Adding custom objects public static void add(ArrayList<CustomObject> list) { list.add(new CustomObject("Z")); list.add(new CustomObject("A")); list.add(new CustomObject("B")); list.add(new CustomObject("X")); list.add(new CustomObject("Aa")); } public static void main(String[] args) { // Declare ArrayList with custom class ArrayList<CustomObject> list = new ArrayList<>(); add(list); sort(list); print(list); }} A Aa B X Z Approach 2: Using Comparable and comparator When the ArrayList is of a custom object type, then in this case we use two sorting methods by either Comparator or Comparable and in this case Collections.sort() cannot be used directly as it will give error because it sorts only specific data-types and not user-defined types. Sorting ArrayList with Comparable: The custom object type class which is Student here will implement the Comparable class<Student>.This will override the compareTo() method of Comparable class which takes the object of class Student as a parameter, and we need to compare the values/ attributes by which we want to sort the list and return accordingly in the compareTo() function. The custom object type class which is Student here will implement the Comparable class<Student>. This will override the compareTo() method of Comparable class which takes the object of class Student as a parameter, and we need to compare the values/ attributes by which we want to sort the list and return accordingly in the compareTo() function. Java // Java program to sort ArrayList of// custom object using Comparable class import java.util.*;class ArrayListSorting { public static void main(String args[]) { ArrayList<Student> arraylist = new ArrayList<Student>(); arraylist.add(new Student(12, "Riya", 15)); arraylist.add(new Student(14, "Mahima", 16)); arraylist.add(new Student(13, "Shubhi", 15)); Collections.sort(arraylist); for (Student str : arraylist) { System.out.println(str); } }} public class Student implements Comparable<Student> { private String studentname; private int rollno; private int studentage; public Student(int rollno, String studentname, int studentage) { this.rollno = rollno; this.studentname = studentname; this.studentage = studentage; } // getter and setter functions public String getStudentname() { return studentname; } public void setStudentname(String studentname) { this.studentname = studentname; } public int getRollno() { return rollno; } public void setRollno(int rollno) { this.rollno = rollno; } public int getStudentage() { return studentage; } public void setStudentage(int studentage) { this.studentage = studentage; } // overriding the compareTo method of Comparable class @Override public int compareTo(Student comparestu) { int compareage = ((Student)comparestu).getStudentage(); // For Ascending order return this.studentage - compareage; // For Descending order do like this // return compareage-this.studentage; } @Override public String toString() { return "[ rollno=" + rollno + ", name=" + studentname + ", age=" + studentage + "]"; }} [ rollno=12, name=Riya, age=15] [ rollno=13, name=Shubhi, age=15] [ rollno=14, name=Mahima, age=16] Sorting ArrayList with Comparator: We will define another class that will implement the Comparator class of type of our custom object. For eg, in the below code, our custom class is Student so another class that we have defined will implement Comparatot<Student>.This class will override the compare method of the Comparator class which accepts two objects of the Student class as parameters and returns the comparison value according to our requirement whether we want to sort the array in ascending or descending order and on which attribute, we want to sort the list. We will define another class that will implement the Comparator class of type of our custom object. For eg, in the below code, our custom class is Student so another class that we have defined will implement Comparatot<Student>. This class will override the compare method of the Comparator class which accepts two objects of the Student class as parameters and returns the comparison value according to our requirement whether we want to sort the array in ascending or descending order and on which attribute, we want to sort the list. Java // Java program to sort the ArrayList// of custom object using Comparator class import java.util.*;import java.util.Comparator;public class Student { private String studentname; private int rollno; private int studentage; public Student(int rollno, String studentname, int studentage) { this.rollno = rollno; this.studentname = studentname; this.studentage = studentage; } // getter and setter functions public String getStudentname() { return studentname; } public void setStudentname(String studentname) { this.studentname = studentname; } public int getRollno() { return rollno; } public void setRollno(int rollno) { this.rollno = rollno; } public int getStudentage() { return studentage; } public void setStudentage(int studentage) { this.studentage = studentage; } public static Comparator<Student> StuNameComparator = new Comparator<Student>() { public int compare(Student s1, Student s2) { String StudentName1 = s1.getStudentname().toUpperCase(); String StudentName2 = s2.getStudentname().toUpperCase(); // ascending order return StudentName1.compareTo( StudentName2); // descending order // return // StudentName2.compareTo(StudentName1); } }; // Comparator for sorting the list by roll no public static Comparator<Student> StuRollno = new Comparator<Student>() { public int compare(Student s1, Student s2) { int rollno1 = s1.getRollno(); int rollno2 = s2.getRollno(); // For ascending order return rollno1 - rollno2; // For descending order // rollno2-rollno1; } }; @Override public String toString() { return "[ rollno=" + rollno + ", name=" + studentname + ", age=" + studentage + "]"; }} class Details { public static void main(String args[]) { ArrayList<Student> arraylist = new ArrayList<Student>(); arraylist.add(new Student(101, "Zues", 26)); arraylist.add(new Student(505, "Abey", 24)); arraylist.add(new Student(809, "Vignesh", 32)); // Sorting based on Student Name System.out.println("Student Name Sorting:"); Collections.sort(arraylist, Student.StuNameComparator); for (Student str : arraylist) { System.out.println(str); } // Sorting on Rollno property System.out.println("RollNum Sorting:"); Collections.sort(arraylist, Student.StuRollno); for (Student str : arraylist) { System.out.println(str); } }} Student Name Sorting: [ rollno=505, name=Abey, age=24] [ rollno=809, name=Vignesh, age=32] [ rollno=101, name=Zues, age=26] RollNum Sorting: [ rollno=101, name=Zues, age=26] [ rollno=505, name=Abey, age=24] [ rollno=809, name=Vignesh, age=32] Java-ArrayList Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Functional Interfaces in Java Stream In Java Constructors in Java Different ways of Reading a text file in Java Exceptions in Java Convert a String to Character array in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java?
[ { "code": null, "e": 23581, "s": 23553, "text": "\n28 Dec, 2020" }, { "code": null, "e": 23783, "s": 23581, "text": "ArrayList in Java (equivalent to vector in C++) having a dynamic size. It can be shrinked or expanded based on size. ArrayList is a part of the collection framework and is present in java.util package." }, { "code": null, "e": 23825, "s": 23783, "text": "ArrayList <E> list = new ArrayList <> ();" }, { "code": null, "e": 23837, "s": 23825, "text": "Approach 1:" }, { "code": null, "e": 24346, "s": 23837, "text": "In the below program, we’ve defined a CustomObject class with a String property, customProperty.We’ve also added a constructor that initializes the property, and a getter function getCustomProperty() which returns customProperty.In the main() method, we’ve created an array list of custom objects list, initialized with 5 objects.For sorting the list with the given property, we use the list‘s sort() method.The sort() method takes the list to be sorted (final sorted list is also the same) and a comparator." }, { "code": null, "e": 24443, "s": 24346, "text": "In the below program, we’ve defined a CustomObject class with a String property, customProperty." }, { "code": null, "e": 24577, "s": 24443, "text": "We’ve also added a constructor that initializes the property, and a getter function getCustomProperty() which returns customProperty." }, { "code": null, "e": 24679, "s": 24577, "text": "In the main() method, we’ve created an array list of custom objects list, initialized with 5 objects." }, { "code": null, "e": 24758, "s": 24679, "text": "For sorting the list with the given property, we use the list‘s sort() method." }, { "code": null, "e": 24859, "s": 24758, "text": "The sort() method takes the list to be sorted (final sorted list is also the same) and a comparator." }, { "code": null, "e": 24906, "s": 24859, "text": "In our case, the comparator is a lambda which-" }, { "code": null, "e": 24949, "s": 24906, "text": "Takes two objects from the list o1 and o2," }, { "code": null, "e": 25016, "s": 24949, "text": "Compares the two object’s customProperty using compareTo() method," }, { "code": null, "e": 25168, "s": 25016, "text": "And finally returns a positive number if o1’s property is greater than o2’s, negative if o1’s property is lesser than o2’s, and zero if they are equal." }, { "code": null, "e": 25267, "s": 25168, "text": "Based on this, the list is sorted based on the least property to greatest and stored back to list." }, { "code": null, "e": 25273, "s": 25267, "text": "Code:" }, { "code": null, "e": 25278, "s": 25273, "text": "Java" }, { "code": "// Java program to sort the ArrayList// of objects by property import java.util.*; // Define a custom class with custom property// It takes and stores custom objectsclass CustomObject { private String customProperty; public CustomObject(String property) { this.customProperty = property; } public String getCustomProperty() { return this.customProperty; }} public class GFG { // printing sorted ArrayList objects using enchanced // for loop public static void print(ArrayList<CustomObject> list) { for (CustomObject obj : list) { System.out.println(obj.getCustomProperty()); } } // Comparison done using compareTo function public static void sort(ArrayList<CustomObject> list) { list.sort((o1, o2) -> o1.getCustomProperty().compareTo( o2.getCustomProperty())); } // Adding custom objects public static void add(ArrayList<CustomObject> list) { list.add(new CustomObject(\"Z\")); list.add(new CustomObject(\"A\")); list.add(new CustomObject(\"B\")); list.add(new CustomObject(\"X\")); list.add(new CustomObject(\"Aa\")); } public static void main(String[] args) { // Declare ArrayList with custom class ArrayList<CustomObject> list = new ArrayList<>(); add(list); sort(list); print(list); }}", "e": 26710, "s": 25278, "text": null }, { "code": null, "e": 26721, "s": 26710, "text": "A\nAa\nB\nX\nZ" }, { "code": null, "e": 26765, "s": 26721, "text": "Approach 2: Using Comparable and comparator" }, { "code": null, "e": 27044, "s": 26765, "text": "When the ArrayList is of a custom object type, then in this case we use two sorting methods by either Comparator or Comparable and in this case Collections.sort() cannot be used directly as it will give error because it sorts only specific data-types and not user-defined types." }, { "code": null, "e": 27079, "s": 27044, "text": "Sorting ArrayList with Comparable:" }, { "code": null, "e": 27425, "s": 27079, "text": "The custom object type class which is Student here will implement the Comparable class<Student>.This will override the compareTo() method of Comparable class which takes the object of class Student as a parameter, and we need to compare the values/ attributes by which we want to sort the list and return accordingly in the compareTo() function." }, { "code": null, "e": 27522, "s": 27425, "text": "The custom object type class which is Student here will implement the Comparable class<Student>." }, { "code": null, "e": 27772, "s": 27522, "text": "This will override the compareTo() method of Comparable class which takes the object of class Student as a parameter, and we need to compare the values/ attributes by which we want to sort the list and return accordingly in the compareTo() function." }, { "code": null, "e": 27777, "s": 27772, "text": "Java" }, { "code": "// Java program to sort ArrayList of// custom object using Comparable class import java.util.*;class ArrayListSorting { public static void main(String args[]) { ArrayList<Student> arraylist = new ArrayList<Student>(); arraylist.add(new Student(12, \"Riya\", 15)); arraylist.add(new Student(14, \"Mahima\", 16)); arraylist.add(new Student(13, \"Shubhi\", 15)); Collections.sort(arraylist); for (Student str : arraylist) { System.out.println(str); } }} public class Student implements Comparable<Student> { private String studentname; private int rollno; private int studentage; public Student(int rollno, String studentname, int studentage) { this.rollno = rollno; this.studentname = studentname; this.studentage = studentage; } // getter and setter functions public String getStudentname() { return studentname; } public void setStudentname(String studentname) { this.studentname = studentname; } public int getRollno() { return rollno; } public void setRollno(int rollno) { this.rollno = rollno; } public int getStudentage() { return studentage; } public void setStudentage(int studentage) { this.studentage = studentage; } // overriding the compareTo method of Comparable class @Override public int compareTo(Student comparestu) { int compareage = ((Student)comparestu).getStudentage(); // For Ascending order return this.studentage - compareage; // For Descending order do like this // return compareage-this.studentage; } @Override public String toString() { return \"[ rollno=\" + rollno + \", name=\" + studentname + \", age=\" + studentage + \"]\"; }}", "e": 29647, "s": 27777, "text": null }, { "code": null, "e": 29747, "s": 29647, "text": "[ rollno=12, name=Riya, age=15]\n[ rollno=13, name=Shubhi, age=15]\n[ rollno=14, name=Mahima, age=16]" }, { "code": null, "e": 29782, "s": 29747, "text": "Sorting ArrayList with Comparator:" }, { "code": null, "e": 30318, "s": 29782, "text": "We will define another class that will implement the Comparator class of type of our custom object. For eg, in the below code, our custom class is Student so another class that we have defined will implement Comparatot<Student>.This class will override the compare method of the Comparator class which accepts two objects of the Student class as parameters and returns the comparison value according to our requirement whether we want to sort the array in ascending or descending order and on which attribute, we want to sort the list." }, { "code": null, "e": 30547, "s": 30318, "text": "We will define another class that will implement the Comparator class of type of our custom object. For eg, in the below code, our custom class is Student so another class that we have defined will implement Comparatot<Student>." }, { "code": null, "e": 30855, "s": 30547, "text": "This class will override the compare method of the Comparator class which accepts two objects of the Student class as parameters and returns the comparison value according to our requirement whether we want to sort the array in ascending or descending order and on which attribute, we want to sort the list." }, { "code": null, "e": 30860, "s": 30855, "text": "Java" }, { "code": "// Java program to sort the ArrayList// of custom object using Comparator class import java.util.*;import java.util.Comparator;public class Student { private String studentname; private int rollno; private int studentage; public Student(int rollno, String studentname, int studentage) { this.rollno = rollno; this.studentname = studentname; this.studentage = studentage; } // getter and setter functions public String getStudentname() { return studentname; } public void setStudentname(String studentname) { this.studentname = studentname; } public int getRollno() { return rollno; } public void setRollno(int rollno) { this.rollno = rollno; } public int getStudentage() { return studentage; } public void setStudentage(int studentage) { this.studentage = studentage; } public static Comparator<Student> StuNameComparator = new Comparator<Student>() { public int compare(Student s1, Student s2) { String StudentName1 = s1.getStudentname().toUpperCase(); String StudentName2 = s2.getStudentname().toUpperCase(); // ascending order return StudentName1.compareTo( StudentName2); // descending order // return // StudentName2.compareTo(StudentName1); } }; // Comparator for sorting the list by roll no public static Comparator<Student> StuRollno = new Comparator<Student>() { public int compare(Student s1, Student s2) { int rollno1 = s1.getRollno(); int rollno2 = s2.getRollno(); // For ascending order return rollno1 - rollno2; // For descending order // rollno2-rollno1; } }; @Override public String toString() { return \"[ rollno=\" + rollno + \", name=\" + studentname + \", age=\" + studentage + \"]\"; }} class Details { public static void main(String args[]) { ArrayList<Student> arraylist = new ArrayList<Student>(); arraylist.add(new Student(101, \"Zues\", 26)); arraylist.add(new Student(505, \"Abey\", 24)); arraylist.add(new Student(809, \"Vignesh\", 32)); // Sorting based on Student Name System.out.println(\"Student Name Sorting:\"); Collections.sort(arraylist, Student.StuNameComparator); for (Student str : arraylist) { System.out.println(str); } // Sorting on Rollno property System.out.println(\"RollNum Sorting:\"); Collections.sort(arraylist, Student.StuRollno); for (Student str : arraylist) { System.out.println(str); } }}", "e": 33865, "s": 30860, "text": null }, { "code": null, "e": 34108, "s": 33865, "text": "Student Name Sorting:\n[ rollno=505, name=Abey, age=24]\n[ rollno=809, name=Vignesh, age=32]\n[ rollno=101, name=Zues, age=26]\nRollNum Sorting:\n[ rollno=101, name=Zues, age=26]\n[ rollno=505, name=Abey, age=24]\n[ rollno=809, name=Vignesh, age=32]" }, { "code": null, "e": 34123, "s": 34108, "text": "Java-ArrayList" }, { "code": null, "e": 34130, "s": 34123, "text": "Picked" }, { "code": null, "e": 34135, "s": 34130, "text": "Java" }, { "code": null, "e": 34149, "s": 34135, "text": "Java Programs" }, { "code": null, "e": 34154, "s": 34149, "text": "Java" }, { "code": null, "e": 34252, "s": 34154, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34261, "s": 34252, "text": "Comments" }, { "code": null, "e": 34274, "s": 34261, "text": "Old Comments" }, { "code": null, "e": 34304, "s": 34274, "text": "Functional Interfaces in Java" }, { "code": null, "e": 34319, "s": 34304, "text": "Stream In Java" }, { "code": null, "e": 34340, "s": 34319, "text": "Constructors in Java" }, { "code": null, "e": 34386, "s": 34340, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 34405, "s": 34386, "text": "Exceptions in Java" }, { "code": null, "e": 34449, "s": 34405, "text": "Convert a String to Character array in Java" }, { "code": null, "e": 34475, "s": 34449, "text": "Java Programming Examples" }, { "code": null, "e": 34509, "s": 34475, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 34556, "s": 34509, "text": "Implementing a Linked List in Java using Class" } ]
Max sum in the configuration | Practice | GeeksforGeeks
Given an array(0-based indexing), you have to find the max sum of i*A[i] where A[i] is the element at index i in the array. The only operation allowed is to rotate(clock-wise or counter clock-wise) the array any number of times. Example 1: Input: N = 4 A[] = {8,3,1,2} Output: 29 Explanation: Above the configuration possible by rotating elements are 3 1 2 8 here sum is 3*0+1*1+2*2+8*3 = 29 1 2 8 3 here sum is 1*0+2*1+8*2+3*3 = 27 2 8 3 1 here sum is 2*0+8*1+3*2+1*3 = 17 8 3 1 2 here sum is 8*0+3*1+1*2+2*3 = 11 Here the max sum is 29 Your Task: Your task is to complete the function max_sum which takes two arguments which is the array A [ ] and its size and returns an integer value denoting the required max sum. Expected Time Complexity: O(N). Expected Auxiliary Space: O(1). Constraints: 1<=N<=104 1<=A[]<1000 0 tapanmanu20003 weeks ago int max_sum(int arr[],int n){ int sum = 0; int sum2 = 0; int maxsum = INT_MIN; for(int j = 0; j < n; j ++){ sum += arr[j] * j; sum2 += arr[j]; } for(int i = 0; i < n; i++){ sum2 -= arr[i]; sum = sum - sum2; sum = sum + (n-1)*arr[i]; maxsum = max(sum,maxsum); sum2 += arr[i]; } return maxsum; } 0 geminicode3 weeks ago Here is my approach in Python. def max_sum(a,n): productsum = 0 for i in range(n): productsum += a[i]*i sumi = sum(a) ans = productsum for i in range(n): productsum = productsum + sumi - n*(a[n-i-1]) if productsum > ans: ans = productsum return ans +1 namastecoding3 weeks ago int max_sum(int A[],int N){ int sum=0; int s0=0; for(int i=0;i<N;i++){ sum += A[i]; s0 += A[i]*i; } int max=s0; int si=s0; for(int i=0;i<N-1;i++){ int sip1=si + sum - N * A[N-i-1]; // Main Formula For Rotating and Maxify // sip1 = S_i+1(subscript) if(sip1>max) max=sip1; si=sip1; } return max;} -1 anujmagotra203 weeks ago int max_sum(int arr[], int n) {int max = 0; int sum = 0; for (int i = 0; i < arr.length; i++) { sum = sum + (arr[i] * i); } if (max < sum) { max = sum; } for (int i = 0 ; i< arr.length-1;i++){ sum = 0; rotate(arr); for (int j = 0; j< arr.length; j++) { sum = sum + (arr[j] * j); } if (max < sum) { max = sum; } } return max; } static void rotate(int [] arr){ int last = arr[arr.length - 1]; for (int i = arr.length - 1; i > 0; i--) { arr[i] = arr[i - 1]; } arr[0] = last; } +1 sritesh8564 weeks ago SIMPLE SOLUTION int max_sum(int array[], int n){ int maxProd = 0; int maxSum = 0; for(int i=1; i<array.length; i++)maxSum += array[i]; for(int i=0; i<array.length; i++)maxProd += array[i]*i; int result = Integer.MIN_VALUE; result = Math.max(maxProd, result); for(int i=1; i<array.length; i++) { maxProd = maxProd - maxSum + (array[i-1]*(array.length-1)); maxSum = maxSum - array[i]+array[i-1]; result = Math.max(maxProd, result); } return result; } +1 taiphanvan24031 month ago int max_sum(int a[],int n) { int sumArr=0,kq=0; for(int i=0;i<n;i++){ sumArr+=a[i]; kq+=i*a[i]; } int Max=kq; for(int i=1;i<n;i++){ kq=kq-sumArr+n*a[i-1]; if(kq>Max) Max=kq; } return Max; } 0 sachin1810201 month ago Help me optimize this Java code class GfG{ int max_sum(int A[], int n) {// Your code here// Finding Solutionint[] ans = new int[n];for(int i = 0; i< n; i++){ rotateby1(A, n); ans[i] = sum(A,n);}Arrays.sort(ans);return ans[n-1]; } int sum(int[] A,int n ){ int sum = 0; for(int i =0; i< n; i++) { sum = sum + A[i]*i; } return sum; } int[] rotateby1(int[] A, int n ) { int ans = A[0]; for( int i =0; i< n-1 ; i++) { A[i] = A[i+1]; } A[n-1] = ans; return A; }} 0 im_kira1 month ago //Javascript o(n) class Solution { computeRotatedSum(e,circularSum,sum,a){ let maxCircularSum=circularSum; while(e>0){ circularSum=circularSum+(sum-(a[e]*a.length)); maxCircularSum= Math.max(maxCircularSum,circularSum) e--; } return maxCircularSum; } max_sum(a, n) { let circularSum=0; let e=n-1; let sum=a.reduce((el,acc)=>el+acc,0); let i=0; for(let i=0;i<n;i++){ circularSum+=a[i]*i; } return this.computeRotatedSum(e,circularSum,sum,a) }} 0 yuktaarya240420002 months ago class GfG{ int max_sum(int A[], int n) {// Your code hereint sum=0;int rot=1;for(int i=0;i<n;i++){ sum+=A[i]*i;}int max=sum;while(rot<=n-1){ int sum1=0; int temp=A[0]; for(int i=1;i<=n-1;i++){ A[i-1]=A[i]; sum1+=A[i-1]*(i-1); } A[n-1]=temp; sum1+=A[n-1]*(n-1); if(sum1>max){ max=sum1; rot++; }else{ rot++; } }return max; } }//shows TLE can u please suggest how to optimize this code? +1 jayesh292 months ago Easy Java Solution :- int max_sum(int arr[], int n){ // regSum = Regular iterative summ of rray // pSum = Sum acc. to the pattern int regSum = arr[0] , pSum = 0; for(int i=1;i<n;i++){ regSum+=arr[i]; pSum += (i*arr[i]); } int maxSum = pSum; for(int i=1;i<n;i++){ int x = pSum-regSum+arr[i-1]+((n-1)*arr[i-1]); maxSum = Math.max(maxSum,x); pSum = x; } return maxSum; } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 467, "s": 238, "text": "Given an array(0-based indexing), you have to find the max sum of i*A[i] where A[i] is the element at index i in the array. The only operation allowed is to rotate(clock-wise or counter clock-wise) the array any number of times." }, { "code": null, "e": 478, "s": 467, "text": "Example 1:" }, { "code": null, "e": 778, "s": 478, "text": "Input:\nN = 4\nA[] = {8,3,1,2}\nOutput: 29\nExplanation: Above the configuration\npossible by rotating elements are\n3 1 2 8 here sum is 3*0+1*1+2*2+8*3 = 29\n1 2 8 3 here sum is 1*0+2*1+8*2+3*3 = 27\n2 8 3 1 here sum is 2*0+8*1+3*2+1*3 = 17\n8 3 1 2 here sum is 8*0+3*1+1*2+2*3 = 11\nHere the max sum is 29 \n" }, { "code": null, "e": 959, "s": 778, "text": "Your Task:\nYour task is to complete the function max_sum which takes two arguments which is the array A [ ] and its size and returns an integer value denoting the required max sum." }, { "code": null, "e": 1023, "s": 959, "text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(1)." }, { "code": null, "e": 1058, "s": 1023, "text": "Constraints:\n1<=N<=104\n1<=A[]<1000" }, { "code": null, "e": 1060, "s": 1058, "text": "0" }, { "code": null, "e": 1085, "s": 1060, "text": "tapanmanu20003 weeks ago" }, { "code": null, "e": 1467, "s": 1085, "text": "int max_sum(int arr[],int n){\n int sum = 0;\n int sum2 = 0;\n int maxsum = INT_MIN;\n for(int j = 0; j < n; j ++){\n sum += arr[j] * j;\n sum2 += arr[j];\n }\n for(int i = 0; i < n; i++){\n sum2 -= arr[i];\n sum = sum - sum2;\n sum = sum + (n-1)*arr[i];\n maxsum = max(sum,maxsum);\n sum2 += arr[i];\n }\n return maxsum;\n}" }, { "code": null, "e": 1469, "s": 1467, "text": "0" }, { "code": null, "e": 1491, "s": 1469, "text": "geminicode3 weeks ago" }, { "code": null, "e": 1522, "s": 1491, "text": "Here is my approach in Python." }, { "code": null, "e": 1801, "s": 1522, "text": "def max_sum(a,n):\n productsum = 0\n for i in range(n):\n productsum += a[i]*i\n sumi = sum(a)\n ans = productsum\n for i in range(n):\n productsum = productsum + sumi - n*(a[n-i-1])\n if productsum > ans:\n ans = productsum\n return ans" }, { "code": null, "e": 1804, "s": 1801, "text": "+1" }, { "code": null, "e": 1829, "s": 1804, "text": "namastecoding3 weeks ago" }, { "code": null, "e": 2247, "s": 1829, "text": "int max_sum(int A[],int N){ int sum=0; int s0=0; for(int i=0;i<N;i++){ sum += A[i]; s0 += A[i]*i; } int max=s0; int si=s0; for(int i=0;i<N-1;i++){ int sip1=si + sum - N * A[N-i-1]; // Main Formula For Rotating and Maxify // sip1 = S_i+1(subscript) if(sip1>max) max=sip1; si=sip1; } return max;}" }, { "code": null, "e": 2250, "s": 2247, "text": "-1" }, { "code": null, "e": 2275, "s": 2250, "text": "anujmagotra203 weeks ago" }, { "code": null, "e": 2385, "s": 2275, "text": "int max_sum(int arr[], int n) {int max = 0; int sum = 0; for (int i = 0; i < arr.length; i++) {" }, { "code": null, "e": 2742, "s": 2385, "text": " sum = sum + (arr[i] * i); } if (max < sum) { max = sum; } for (int i = 0 ; i< arr.length-1;i++){ sum = 0; rotate(arr); for (int j = 0; j< arr.length; j++) { sum = sum + (arr[j] * j); } if (max < sum) { max = sum; } }" }, { "code": null, "e": 2917, "s": 2742, "text": " return max; } static void rotate(int [] arr){ int last = arr[arr.length - 1]; for (int i = arr.length - 1; i > 0; i--) { arr[i] = arr[i - 1];" }, { "code": null, "e": 2947, "s": 2917, "text": " } arr[0] = last;" }, { "code": null, "e": 2952, "s": 2947, "text": " }" }, { "code": null, "e": 2955, "s": 2952, "text": "+1" }, { "code": null, "e": 2977, "s": 2955, "text": "sritesh8564 weeks ago" }, { "code": null, "e": 2993, "s": 2977, "text": "SIMPLE SOLUTION" }, { "code": null, "e": 3453, "s": 2993, "text": "int max_sum(int array[], int n){ int maxProd = 0; int maxSum = 0; for(int i=1; i<array.length; i++)maxSum += array[i]; for(int i=0; i<array.length; i++)maxProd += array[i]*i; int result = Integer.MIN_VALUE; result = Math.max(maxProd, result); for(int i=1; i<array.length; i++) { maxProd = maxProd - maxSum + (array[i-1]*(array.length-1)); maxSum = maxSum - array[i]+array[i-1]; result = Math.max(maxProd, result); } return result; }" }, { "code": null, "e": 3456, "s": 3453, "text": "+1" }, { "code": null, "e": 3482, "s": 3456, "text": "taiphanvan24031 month ago" }, { "code": null, "e": 3744, "s": 3482, "text": "int max_sum(int a[],int n)\n{\n int sumArr=0,kq=0;\n for(int i=0;i<n;i++){\n sumArr+=a[i];\n kq+=i*a[i];\n }\n int Max=kq;\n for(int i=1;i<n;i++){\n kq=kq-sumArr+n*a[i-1];\n if(kq>Max)\n Max=kq;\n }\n return Max;\n}" }, { "code": null, "e": 3746, "s": 3744, "text": "0" }, { "code": null, "e": 3770, "s": 3746, "text": "sachin1810201 month ago" }, { "code": null, "e": 3803, "s": 3770, "text": "Help me optimize this Java code " }, { "code": null, "e": 4346, "s": 3805, "text": "class GfG{ int max_sum(int A[], int n) {// Your code here// Finding Solutionint[] ans = new int[n];for(int i = 0; i< n; i++){ rotateby1(A, n); ans[i] = sum(A,n);}Arrays.sort(ans);return ans[n-1]; } int sum(int[] A,int n ){ int sum = 0; for(int i =0; i< n; i++) { sum = sum + A[i]*i; } return sum; } int[] rotateby1(int[] A, int n ) { int ans = A[0]; for( int i =0; i< n-1 ; i++) { A[i] = A[i+1]; } A[n-1] = ans; return A; }} " }, { "code": null, "e": 4348, "s": 4346, "text": "0" }, { "code": null, "e": 4367, "s": 4348, "text": "im_kira1 month ago" }, { "code": null, "e": 4385, "s": 4367, "text": "//Javascript o(n)" }, { "code": null, "e": 4895, "s": 4385, "text": "class Solution { computeRotatedSum(e,circularSum,sum,a){ let maxCircularSum=circularSum; while(e>0){ circularSum=circularSum+(sum-(a[e]*a.length)); maxCircularSum= Math.max(maxCircularSum,circularSum) e--; } return maxCircularSum; } max_sum(a, n) { let circularSum=0; let e=n-1; let sum=a.reduce((el,acc)=>el+acc,0); let i=0; for(let i=0;i<n;i++){ circularSum+=a[i]*i; } return this.computeRotatedSum(e,circularSum,sum,a)" }, { "code": null, "e": 4901, "s": 4895, "text": " }}" }, { "code": null, "e": 4903, "s": 4901, "text": "0" }, { "code": null, "e": 4933, "s": 4903, "text": "yuktaarya240420002 months ago" }, { "code": null, "e": 5390, "s": 4933, "text": "class GfG{ int max_sum(int A[], int n) {// Your code hereint sum=0;int rot=1;for(int i=0;i<n;i++){ sum+=A[i]*i;}int max=sum;while(rot<=n-1){ int sum1=0; int temp=A[0]; for(int i=1;i<=n-1;i++){ A[i-1]=A[i]; sum1+=A[i-1]*(i-1); } A[n-1]=temp; sum1+=A[n-1]*(n-1); if(sum1>max){ max=sum1; rot++; }else{ rot++; } }return max; } }//shows TLE can u please suggest how to optimize this code?" }, { "code": null, "e": 5393, "s": 5390, "text": "+1" }, { "code": null, "e": 5414, "s": 5393, "text": "jayesh292 months ago" }, { "code": null, "e": 5436, "s": 5414, "text": "Easy Java Solution :-" }, { "code": null, "e": 5885, "s": 5436, "text": " int max_sum(int arr[], int n){\n // regSum = Regular iterative summ of rray\n\t // pSum = Sum acc. to the pattern\n\t int regSum = arr[0] , pSum = 0;\n\t for(int i=1;i<n;i++){\n\t regSum+=arr[i];\n\t pSum += (i*arr[i]);\n\t }\n\t int maxSum = pSum;\n\t for(int i=1;i<n;i++){\n\t int x = pSum-regSum+arr[i-1]+((n-1)*arr[i-1]);\n\t maxSum = Math.max(maxSum,x);\n\t pSum = x;\n\t }\n\t return maxSum;\n }\t" }, { "code": null, "e": 6031, "s": 5885, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 6067, "s": 6031, "text": " Login to access your submissions. " }, { "code": null, "e": 6077, "s": 6067, "text": "\nProblem\n" }, { "code": null, "e": 6087, "s": 6077, "text": "\nContest\n" }, { "code": null, "e": 6150, "s": 6087, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6298, "s": 6150, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 6506, "s": 6298, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 6612, "s": 6506, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Sentiment Analysis of Twitter’s US Airlines Data using KNN Classification | by Momin Mehmood Butt | Towards Data Science
Sentiment analysis refers to the use of natural language processing, text analysis, and computational linguistics to systematically identify, extract, quantify, and study effective states and subjective information. Sentiment analysis is widely applied to customer materials such as reviews and survey responses. The most common type of sentiment analysis is ‘polarity detection’ and involves classifying customer materials/reviews as positive, negative or neutral. Performing sentiment analysis on Twitter data usually involves four steps: Gather Twitter dataPreprocess and prepare the dataTrain and test a Sentiment Analysis modelVisualize and verify the results Gather Twitter data Preprocess and prepare the data Train and test a Sentiment Analysis model Visualize and verify the results By the end of this article, we would have breezed through a hands-on experience of developing our very own ‘Tweet Sentiment Analyzer’ in Python. We will build a k-nearest neighbors classifier from scratch, evaluate and verify our model’s performance results by comparing it with Scikit-learn’s built-in classifier and, finally, enhance our model’s performance by tinkering with the input features. We are given a Twitter US Airline Sentiment dataset that contains around 14,601 tweets about each major U.S. airline. The tweets are labelled as positive, negative, or neutral based on the nature of the respective Twitter user’s feedback regarding the airline. The dataset is further segregated into training and test sets in a stratified fashion. Train set contains 11,680 tweets whereas the test set contains 2,921 tweets. Our task is to develop and train a k-nearest neighbors classifier on the training set and use it to predict sentiment classes of the tweets present in the test set. Here is a sneak-peek into the training dataset that we have got at our hands: As can be gauged from the image above, there is a lot of cleaning and preprocessing that needs to be done before we get into the features extraction part. In short, we have to remove the stop words, punctuation marks and other unwanted characters from the tweets and convert them to lower case. The preprocess function shown above is how I ensure that the Tweet column in the training set is adequately preprocessed. I have used the string and regex modules for this purpose. Once the necessary cleaning is done, our training dataset now looks something like this: In the feature extraction step, we will need to represent each tweet as a bag-of-words (BoW), i.e. an unordered set of words with their positions ignored and all of the emphasis placed on the respective frequencies of each word. For example, consider these two tweets: T1 = Welcome to machine learning, machine! T2 = kNN is a powerful machine learning algorithm. The bag-of-words representation (ignoring case and punctuation) for the above two tweets are: In order to create this bag-of-words representation, we would first need to extract out the unique words from all of our tweets in the training dataset. This is done in the following code snippet: # Finding all the unique words in training data's Tweet columntrain_unique =(list(set(trained['Tweet'].str.findall("\w+").sum()))) train_unique_words = len(train_unique) There are a total of 10,033 unique words in the Tweet column of the training dataset. Next, we need to create a feature matrix and populate it with the respective features for every single training data instance. One way to do that is shown below: #Training Data: Extracting features and storing them into the training feature matrixfor sentence in trained['Tweet']: train_featurevec = [] word = sentence.split() for w in train_unique: train_featurevec.append(word.count(w)) train_matrix.append(train_featurevec) We create a feature vector for a tweet and using nested for loops, we loop over the entirety of the training dataset to formulate a holistic matrix containing features for all the tweets. Before we slide into the implementation of k-nearest neighbors algorithm for this particular problem, it is imperative to note that the aforementioned preprocessing and feature extraction needs to be done on the test dataset, too. Hence, we will have a test feature matrix and a training feature matrix once the above steps are replicated on the test set. Shape of Training Matrix: (11680 , 10033) Shape of Test Matrix: (2921 , 10033) The way that the classification algorithm will work is that for a given tweet in the test dataset (d), we will compute Euclidean distance between d and every sample in the training dataset (D). We will then choose k samples that are nearest to d, i.e. those samples which have the smallest distances from d. From among these k samples, we will extract out the class that is assigned to a majority of the samples and assign that label to the test instance. Steps: Compute the distance between d and every sample in D.  Choose the k samples from D that are nearest to d; denote the set by Sd ∈ D.  Assign d the label y of the majority class in Sd. To calculate the distances, we make use of SciPy’s cdist function which returns a 2D vector, consisting of all the required distances: #Calculating distances between every test instance with all the train instances. This returns a 2D distances vector.dists = cdist(test_matrix,train_matrix,'euclidean') We also define a function called get_mode that returns the mode of the list and if there are more than one modes, it randomly returns any of them. This will be useful when evaluating the frequency of the two classes in our k samples. Ties can also be handled by back-tracking to k-1 neighbors but in this case, we use the randomized method of selecting the class if there is no one apparent mode. def get_mode(l): counting = Counter(l) max_count = max(counting.values()) return choice([ks for ks in counting if counting[ks] == max_count]) The code pasted in the snippet below is one way of manually creating and running a KNN classifier to predict the labels of tweets present in the dataset. As can be seen in the code, the predicted labels are assigned to their respective test samples within the for loop. Now, in order to evaluate the performance of our classifier, we can report classification accuracy, macro-average (precision, recall, and F1) and confusion matrix on the test set for different values of k. We can create a temporary data-frame that stores frequencies or value counts for each tuple of instances, e.g. (positive, positive = 265) and so on for all other seven instances. The resultant data-frame is as follows: The frequency data-frame can then be used to not only compute performance measures but also produce the confusion matrix for every k. As illustrated in the screenshot above, the classification accuracy slightly decreases as we increase the number of nearest neighbors. The graphs depict that choosing k = 5 is by far the ideal number of nearest neighbors in our scenario but the variation in performance measures is not too drastic for other values of k. In order to verify our results in the implementation process penned down above, we use Scikit-learn’s kNN implementation to train and test the k nearest neighbor classifier on the provided dataset and compare its performance measures with the ones we got above. A short glimpse at the classification reports computed by Scikit-learn suggests that there is not a whole lot of difference between the two classifiers. In fact, the accuracies, more or less, lie within the same range, i.e. between 49% and 52%. However, the results are not particularly impressive and there is a significant room for improvement as far as our ability to predict the correct labels is concerned. One thing that we can do is enhance our input features is that instead of using sparse bag-of-words representations, we can use a 300-dimensional dense vector representation also known as Word2Vec. Word2Vec is a popular representation of text and is capable of capturing linguistic contexts of words. The algorithm uses neural networks to learn word associations from a large corpus of text. Once trained, such a model can detect synonymous words or suggest additional words for a partial sentence. As the name implies, word2vec represents each distinct word with a particular list of numbers, i.e. a vector. At first, we need to download pre-trained 300-dimensional word2vec representations and install and import gensim to use these representations: import gensimfrom gensim.models import KeyedVectorsword2vec = KeyedVectors.load_word2vec_format("GoogleNews-vectors-negative300.bin.gz", binary=True) We will not delve deeper into the intricacies involved in Word2Vec’s implementation in this article. But there’s a brilliant, visualization-based piece on the topic going by the title ‘The Illustrated Word2Vec’. Be sure to check it out. In short, switching to Word2Vec certainly enhances our classifier’s performance, as depicted above. The classification accuracy is bolstered to nearly 74% - a more than 20% increase to our previous model’s results that used BoW representations. You can view and download the full project for your convenience from my GitHub. Federico Pascual. (June 8th, 2019). Twitter Sentiment Analysis with Machine Learninghttps://monkeylearn.com/blog/sentiment-analysis-of-twitter/Jay Alammar. The Illustrated Word2vechttp://jalammar.github.io/illustrated-word2vec/Wikipedia. Word2vechttps://en.wikipedia.org/wiki/Word2vecKaggle. Twitter US Airline Sentimenthttps://www.kaggle.com/crowdflower/twitter-airline-sentiment Federico Pascual. (June 8th, 2019). Twitter Sentiment Analysis with Machine Learninghttps://monkeylearn.com/blog/sentiment-analysis-of-twitter/ Jay Alammar. The Illustrated Word2vechttp://jalammar.github.io/illustrated-word2vec/ Wikipedia. Word2vechttps://en.wikipedia.org/wiki/Word2vec Kaggle. Twitter US Airline Sentimenthttps://www.kaggle.com/crowdflower/twitter-airline-sentiment
[ { "code": null, "e": 637, "s": 171, "text": "Sentiment analysis refers to the use of natural language processing, text analysis, and computational linguistics to systematically identify, extract, quantify, and study effective states and subjective information. Sentiment analysis is widely applied to customer materials such as reviews and survey responses. The most common type of sentiment analysis is ‘polarity detection’ and involves classifying customer materials/reviews as positive, negative or neutral." }, { "code": null, "e": 712, "s": 637, "text": "Performing sentiment analysis on Twitter data usually involves four steps:" }, { "code": null, "e": 836, "s": 712, "text": "Gather Twitter dataPreprocess and prepare the dataTrain and test a Sentiment Analysis modelVisualize and verify the results" }, { "code": null, "e": 856, "s": 836, "text": "Gather Twitter data" }, { "code": null, "e": 888, "s": 856, "text": "Preprocess and prepare the data" }, { "code": null, "e": 930, "s": 888, "text": "Train and test a Sentiment Analysis model" }, { "code": null, "e": 963, "s": 930, "text": "Visualize and verify the results" }, { "code": null, "e": 1361, "s": 963, "text": "By the end of this article, we would have breezed through a hands-on experience of developing our very own ‘Tweet Sentiment Analyzer’ in Python. We will build a k-nearest neighbors classifier from scratch, evaluate and verify our model’s performance results by comparing it with Scikit-learn’s built-in classifier and, finally, enhance our model’s performance by tinkering with the input features." }, { "code": null, "e": 1786, "s": 1361, "text": "We are given a Twitter US Airline Sentiment dataset that contains around 14,601 tweets about each major U.S. airline. The tweets are labelled as positive, negative, or neutral based on the nature of the respective Twitter user’s feedback regarding the airline. The dataset is further segregated into training and test sets in a stratified fashion. Train set contains 11,680 tweets whereas the test set contains 2,921 tweets." }, { "code": null, "e": 2029, "s": 1786, "text": "Our task is to develop and train a k-nearest neighbors classifier on the training set and use it to predict sentiment classes of the tweets present in the test set. Here is a sneak-peek into the training dataset that we have got at our hands:" }, { "code": null, "e": 2324, "s": 2029, "text": "As can be gauged from the image above, there is a lot of cleaning and preprocessing that needs to be done before we get into the features extraction part. In short, we have to remove the stop words, punctuation marks and other unwanted characters from the tweets and convert them to lower case." }, { "code": null, "e": 2594, "s": 2324, "text": "The preprocess function shown above is how I ensure that the Tweet column in the training set is adequately preprocessed. I have used the string and regex modules for this purpose. Once the necessary cleaning is done, our training dataset now looks something like this:" }, { "code": null, "e": 2863, "s": 2594, "text": "In the feature extraction step, we will need to represent each tweet as a bag-of-words (BoW), i.e. an unordered set of words with their positions ignored and all of the emphasis placed on the respective frequencies of each word. For example, consider these two tweets:" }, { "code": null, "e": 2957, "s": 2863, "text": "T1 = Welcome to machine learning, machine! T2 = kNN is a powerful machine learning algorithm." }, { "code": null, "e": 3051, "s": 2957, "text": "The bag-of-words representation (ignoring case and punctuation) for the above two tweets are:" }, { "code": null, "e": 3248, "s": 3051, "text": "In order to create this bag-of-words representation, we would first need to extract out the unique words from all of our tweets in the training dataset. This is done in the following code snippet:" }, { "code": null, "e": 3418, "s": 3248, "text": "# Finding all the unique words in training data's Tweet columntrain_unique =(list(set(trained['Tweet'].str.findall(\"\\w+\").sum()))) train_unique_words = len(train_unique)" }, { "code": null, "e": 3666, "s": 3418, "text": "There are a total of 10,033 unique words in the Tweet column of the training dataset. Next, we need to create a feature matrix and populate it with the respective features for every single training data instance. One way to do that is shown below:" }, { "code": null, "e": 3938, "s": 3666, "text": "#Training Data: Extracting features and storing them into the training feature matrixfor sentence in trained['Tweet']: train_featurevec = [] word = sentence.split() for w in train_unique: train_featurevec.append(word.count(w)) train_matrix.append(train_featurevec)" }, { "code": null, "e": 4126, "s": 3938, "text": "We create a feature vector for a tweet and using nested for loops, we loop over the entirety of the training dataset to formulate a holistic matrix containing features for all the tweets." }, { "code": null, "e": 4482, "s": 4126, "text": "Before we slide into the implementation of k-nearest neighbors algorithm for this particular problem, it is imperative to note that the aforementioned preprocessing and feature extraction needs to be done on the test dataset, too. Hence, we will have a test feature matrix and a training feature matrix once the above steps are replicated on the test set." }, { "code": null, "e": 4561, "s": 4482, "text": "Shape of Training Matrix: (11680 , 10033) Shape of Test Matrix: (2921 , 10033)" }, { "code": null, "e": 5017, "s": 4561, "text": "The way that the classification algorithm will work is that for a given tweet in the test dataset (d), we will compute Euclidean distance between d and every sample in the training dataset (D). We will then choose k samples that are nearest to d, i.e. those samples which have the smallest distances from d. From among these k samples, we will extract out the class that is assigned to a majority of the samples and assign that label to the test instance." }, { "code": null, "e": 5024, "s": 5017, "text": "Steps:" }, { "code": null, "e": 5080, "s": 5024, "text": "Compute the distance between d and every sample in D. " }, { "code": null, "e": 5159, "s": 5080, "text": "Choose the k samples from D that are nearest to d; denote the set by Sd ∈ D. " }, { "code": null, "e": 5209, "s": 5159, "text": "Assign d the label y of the majority class in Sd." }, { "code": null, "e": 5344, "s": 5209, "text": "To calculate the distances, we make use of SciPy’s cdist function which returns a 2D vector, consisting of all the required distances:" }, { "code": null, "e": 5512, "s": 5344, "text": "#Calculating distances between every test instance with all the train instances. This returns a 2D distances vector.dists = cdist(test_matrix,train_matrix,'euclidean')" }, { "code": null, "e": 5909, "s": 5512, "text": "We also define a function called get_mode that returns the mode of the list and if there are more than one modes, it randomly returns any of them. This will be useful when evaluating the frequency of the two classes in our k samples. Ties can also be handled by back-tracking to k-1 neighbors but in this case, we use the randomized method of selecting the class if there is no one apparent mode." }, { "code": null, "e": 6054, "s": 5909, "text": "def get_mode(l): counting = Counter(l) max_count = max(counting.values()) return choice([ks for ks in counting if counting[ks] == max_count])" }, { "code": null, "e": 6324, "s": 6054, "text": "The code pasted in the snippet below is one way of manually creating and running a KNN classifier to predict the labels of tweets present in the dataset. As can be seen in the code, the predicted labels are assigned to their respective test samples within the for loop." }, { "code": null, "e": 6749, "s": 6324, "text": "Now, in order to evaluate the performance of our classifier, we can report classification accuracy, macro-average (precision, recall, and F1) and confusion matrix on the test set for different values of k. We can create a temporary data-frame that stores frequencies or value counts for each tuple of instances, e.g. (positive, positive = 265) and so on for all other seven instances. The resultant data-frame is as follows:" }, { "code": null, "e": 6883, "s": 6749, "text": "The frequency data-frame can then be used to not only compute performance measures but also produce the confusion matrix for every k." }, { "code": null, "e": 7204, "s": 6883, "text": "As illustrated in the screenshot above, the classification accuracy slightly decreases as we increase the number of nearest neighbors. The graphs depict that choosing k = 5 is by far the ideal number of nearest neighbors in our scenario but the variation in performance measures is not too drastic for other values of k." }, { "code": null, "e": 7466, "s": 7204, "text": "In order to verify our results in the implementation process penned down above, we use Scikit-learn’s kNN implementation to train and test the k nearest neighbor classifier on the provided dataset and compare its performance measures with the ones we got above." }, { "code": null, "e": 7711, "s": 7466, "text": "A short glimpse at the classification reports computed by Scikit-learn suggests that there is not a whole lot of difference between the two classifiers. In fact, the accuracies, more or less, lie within the same range, i.e. between 49% and 52%." }, { "code": null, "e": 8076, "s": 7711, "text": "However, the results are not particularly impressive and there is a significant room for improvement as far as our ability to predict the correct labels is concerned. One thing that we can do is enhance our input features is that instead of using sparse bag-of-words representations, we can use a 300-dimensional dense vector representation also known as Word2Vec." }, { "code": null, "e": 8487, "s": 8076, "text": "Word2Vec is a popular representation of text and is capable of capturing linguistic contexts of words. The algorithm uses neural networks to learn word associations from a large corpus of text. Once trained, such a model can detect synonymous words or suggest additional words for a partial sentence. As the name implies, word2vec represents each distinct word with a particular list of numbers, i.e. a vector." }, { "code": null, "e": 8630, "s": 8487, "text": "At first, we need to download pre-trained 300-dimensional word2vec representations and install and import gensim to use these representations:" }, { "code": null, "e": 8780, "s": 8630, "text": "import gensimfrom gensim.models import KeyedVectorsword2vec = KeyedVectors.load_word2vec_format(\"GoogleNews-vectors-negative300.bin.gz\", binary=True)" }, { "code": null, "e": 9017, "s": 8780, "text": "We will not delve deeper into the intricacies involved in Word2Vec’s implementation in this article. But there’s a brilliant, visualization-based piece on the topic going by the title ‘The Illustrated Word2Vec’. Be sure to check it out." }, { "code": null, "e": 9262, "s": 9017, "text": "In short, switching to Word2Vec certainly enhances our classifier’s performance, as depicted above. The classification accuracy is bolstered to nearly 74% - a more than 20% increase to our previous model’s results that used BoW representations." }, { "code": null, "e": 9342, "s": 9262, "text": "You can view and download the full project for your convenience from my GitHub." }, { "code": null, "e": 9723, "s": 9342, "text": "Federico Pascual. (June 8th, 2019). Twitter Sentiment Analysis with Machine Learninghttps://monkeylearn.com/blog/sentiment-analysis-of-twitter/Jay Alammar. The Illustrated Word2vechttp://jalammar.github.io/illustrated-word2vec/Wikipedia. Word2vechttps://en.wikipedia.org/wiki/Word2vecKaggle. Twitter US Airline Sentimenthttps://www.kaggle.com/crowdflower/twitter-airline-sentiment" }, { "code": null, "e": 9867, "s": 9723, "text": "Federico Pascual. (June 8th, 2019). Twitter Sentiment Analysis with Machine Learninghttps://monkeylearn.com/blog/sentiment-analysis-of-twitter/" }, { "code": null, "e": 9952, "s": 9867, "text": "Jay Alammar. The Illustrated Word2vechttp://jalammar.github.io/illustrated-word2vec/" }, { "code": null, "e": 10010, "s": 9952, "text": "Wikipedia. Word2vechttps://en.wikipedia.org/wiki/Word2vec" } ]
What is activation function ?. One of most important parts of neural... | by Christophe Pere | Towards Data Science
The activation function defines the output of a neuron / node given an input or set of input (output of multiple neurons). It’s the mimic of the stimulation of a biological neuron. The output of the activation function to the next layer (in shallow neural network: input layer and output layer, and in deep network to the next hidden layer) is called forward propagation (information propagation). It’s considered as a non linearity transformation of a neural network. A notebook with all the code are available here: GitHub Binary Linear Sigmoid Tanh ReLU Leaky ReLU (LReLU) Parametric ReLU (PReLU) Exponential Linear Unit (eLU) ReLU-6 Softplus Softsign Softmax Swish The binary activation function is the simpliest. It’s based on binary classifier, the output is 0 if values are negatives else 1. See this activation function as a threshold in binary classification. The code for a binary activation function is: def binary_active_function(x): return 0 if x < 0 else 1 What is the output of this function ? for i in [-5, -3, -1, 0, 2, 5]: print(binary_active_function(i))output: 0 0 0 1 1 1 Or visualy: Pro: Binary classification Cons: Doesn’t work in multilabel classification The derivative for the gradient calculation is always 0 so impossible to update weights The next step after the binary function is to use a linear function instead of a step. The output is proportional to the input. The corresponding code is: def linear_active_function(a, x): return a*x We can compute it for different values of “a”: $ x = numpy.linspace(-10, 10, 5000)$ y_1 = [linear_active_function(1, i) for i in x] # a = 1$ y_2 = [linear_active_function(2, i) for i in x] # a = 2$ y_1> [-10.0, -9.9, -9.8, -9.7, ..., 9.7, 9.8, 9.9, 10.0] If we plot the results for a = 1, 2, 4 and 10: Pros: Binary and multiclass classification Highly interpretable Cons: The derivative correspond to “a” so the update of weights and biaises during the backprogation will be constant. Not efficient if the gradient is always the same. Sigmoid is the most used activation function with ReLU and tanh. It’s a non-linear activation function also called logistic function. The output of this activation function vary between 0 and 1. All the output of neurons will be positive. The corresponding code is as follow: def sigmoid_active_function(x): return 1./(1+numpy.exp(-x)) A quick computation: $ x = numpy.linspace(-10, 10, 5000)$ y = [sigmoid_active_function(i) for i in x] $ y> [4.5397868702434395e-05, 4.5854103946941324e-05, ... , 0.9999532196250409, 0.9999536850759906, 0.9999541458960531] If we plot the results: Cons: The problem of this function is that the output of each neuron can saturate. Values greater than 1 are shape as 1 and values smaller than 0 are shape as 0. The best sensitivity for the sigmoid function is around the central point (0, 0.5). A big problem appear during the saturation, the algorithm can not learn during this position (it’s the source of the vanishing gradient problem, corresponding to the absence of direction in the gradient). The tangent hyperbolic function (tanh) is similar to the sigmoïd function in the way that their form are similar. Tanh is symmetric in 0 and the values are in the range -1 and 1. As the sigmoid they are very sensitive in the central point (0, 0) but they saturate for very large number (positive and negative). This symmetry make them better than the sigmoid function. The corresponding code to apply a tanh function is: def tanh_active_function(x): return 2*sigmoid_active_function(2*x)-1 Compute the y values: $ x = numpy.linspace(-10, 10, 5000)$ y = [tanh_active_function(i) for i in x] $ y> [-0.9999999958776927, -0.9999999957944167, ... , 0.9999999956227836, 0.9999999957094583, 0.9999999957944166] And the corresponding result: Pros: Range between -1 and 1 The gradient is stronger than sigmoid ( derivatives are steeper) Cons: Like sigmoid, tanh also has a vanishing gradient problem Saturation The REctified Linear Unit was develop to avoid the saturation with big positive numbers. The non-linearity permit to conserve and learn the patterns inside the data and the linear part (>0 — also called piecewise linear function) make them easily interpretable. The function below shows how to implement the ReLU function: def relu_active_function(x): return numpy.array([0, x]).max() y computation: $ x = numpy.linspace(-10, 10, 5000)$ y = [relu_active_function(i) for i in x] $ y> [0.0, 0.0, ... , 9.97, 9.98, 9.99] The results: Pros: Easy to implement and very fast True 0 value Optimization are easy when activation function are linear Most used in the neural networks ecosystem Cons: The function can not be differentiable when x = 0. The gradient descent can’t be computed for this point but, in practice that has not an influence. The linear part correspond to a slope with value 1 and the negative part is equal to zero. “dying ReLU problem”: corresponds to the inactive part of the neurons if the output are 0. There no gradient when neurons are not active so if a large part of neurons are not activated it can result of poor performance of the model Not appropriate for RNN class algorithm (RNN, LSTM, GRU) This activation function is a modification of the ReLU activation function to avoid the “dying problem”. The function return a linear slope where a=0.01 which permit to keep neurons activated with a gradient flow. See the code below: def leaky_relu_active_function(x): return 0.01*x if x < 0 else x Compute the y axis to plot the results: $ x = numpy.linspace(-10, 10, 5000)$ y = [leaky_relu_active_function(i) for i in x] $ y> [-0.1, -0.0999, ... , 9.97, 9.98, 9.99] Plot the results: Pros: Correct the “dying ReLU problem” Same comportement of the ReLU activation function for the part y=x After the Leaky ReLU there is another activation function created to avoid the “dying ReLU problem”, the parametric or parametrised ReLU. The coefficient a is not lock at 0.01 (Leaky ReLU) but it free to estimate. It’s a generalization of the ReLU, the algorithm learn the rectifier parameter. The code: def parametric_relu_active_function(a, x): return a*x if x < 0 else x Compute the results for different a values: $ x = numpy.linspace(-10, 10, 5000)$ y_1 = [parametric_relu_active_function(0.25, i) for i in x] $ y_2 = [parametric_relu_active_function(0.5, i) for i in x]$ y_3 = [parametric_relu_active_function(0.75, i) for i in x]$ y_4 = [parametric_relu_active_function(1, i) for i in x]$ y_1> [-2.5, -2.4975, ... , 9.97, 9.98, 9.99] Plot the results for a = 0.25, 0.5, 0.75, 1: If a = 0 the parametric ReLU is equivalent to the ReLU activation function. If a=0.01 the parametric ReLU correspond to the Leaky ReLU. Pros: Generalize the ReLU activation function Avoid the “dying ReLU problem” The parameter “a” is learned by the neural network eLU is another variation of the ReLU function. The negative part of the function is handled by the exponential function with a slow smooth. The corresponding function: def elu_active_function(a, x): return a*(numpy.exp(x)-1) if x < 0 else x y computation: $ x = numpy.linspace(-10, 10, 5000)$ y_1 = [elu_active_function(0.1, i) for i in x] $ y_2 = [elu_active_function(1, i) for i in x]$ y_3 = [elu_active_function(2, i) for i in x]$ y_4 = [elu_active_function(5, i) for i in x]$ y_1> [-0.09999546000702375, -0.09999541437933579, ... , 9.97, 9.98, 9.99] Plot the results for a = 0.1, 1, 2, 4: Pros: ELU becomes smooth slowly until its output equal to -α whereas RELU sharply smoothes. ELU is a strong alternative to ReLU. Unlike to ReLU, ELU can produce negative outputs. Cons: For x > 0, it can blow up the activation with the output range of [0, inf]. Another variation of the ReLU function is the ReLU-6, 6 is an arbitrary parameter fixed by hand. The advantage is to shape the output for large positive number to the 6 value. The corresponding code: def relu_6_active_function(x): return numpy.array([0, x]).max() if x<6 else 6 The y computation: $ y = [relu_6_active_function(i) for i in x] Plot the results: The softplus activation function is an alternative of sigmoid and tanh functions. This functions have limits (upper, lower) but softplus is in the range (0, +inf). The corresponding code: def softplus_active_function(x): return math.log(1+numpy.exp(x)) y computation: $ y = [softplus_active_function(i) for i in x] Plot the results: This activation function is a variation of tanh but is not very used in practice. tanh and softsign functions are closely related, tanh converges exponentially whereas softsign converges polynomially. The corresponding code: def softsign_active_function(x): return x / (1 + abs(x) )$ y = [softsign_active_function(i) for i in x] Plot the results: The softmax activation function is different from the other because it compute the probability distribution. The sum of the output is equal to 1. The corresponding code: def softmax_active_function(x): return numpy.exp(x)/numpy.sum(numpy.exp(x)) Compute the output is different because it’s a probability distribution taking into account the sum of exponential, the function needed all the x points to compute the output y. $ x = [0.8, 1.2, 2.4, 4.6]$ y = softmax_active_function(x)$ y> [0.01917691, 0.02860859, 0.09498386, 0.85723064]$ numpy.sum(y)> 1.0 Swish is the newer activation function, published by Google in 2017 it improves the performances of ReLU on deeper models. This function is a variation of sigmoid function because it can be expressed by: x*sigmoid(x). Swish has the properties of one-sided boundedness at zero, smoothness, and non-monotonicity, which may play a role in the observed efficacy of Swish and similar activation functions.SWISH: A SELF-GATED ACTIVATION FUNCTION, Prajit Ramachandran∗ , Barret Zoph, Quoc V. Le, 2017 The corresponding codes: def swish_active_function(x): return x/(1+numpy.exp(-x)) Or: def swish_active_function(x): return x*sigmoid_active_function(x) Compute the values: $ x = numpy.linspace(-10, 10, 5000)$ y = [swish_active_function(i) for i in x]$ y> [-0.0004539786870243439, -0.0004967044303692657, ..., 9.699405586525717, 9.799456604457717, 9.89950329556963] Plot the results: Pros: Differentiable on each point compare to ReLU Here are presented some activation functions (most popular) with their code and representation. Hope this visualisation could permit to everyone to understand the output of neurons and determined which function is better for the problem they work on. The last plot corresponds to the activation functions stack in one graphic. https://medium.com/r/?url=https%3A%2F%2Fml-cheatsheet.readthedocs.io%2Fen%2Flatest%2Factivation_functions.html https://machinelearningmastery.com/rectified-linear-activation-function-for-deep-learning-neural-networks/ Ian Goodfellow, Joshua Bengio and Aaron courville, Deep Learning (2016), MIT Kevin Jarrett et al., What is the best multi-stage architecture for object recognition? (2009), IEEE Vinod Nair and Geoffrey Hinton, Rectified Linear Units Improve Restricted Boltzmann Machines (2010), ACM Xavier Glorot, Antoine Bordes, Yoshua Bengio, Deep Sparse Rectifier Neural Networks (2011), Proceedings of Machine Learning Research Andrew L. Maas, Awni Y. Hannun and Andrew Y. Ng, Rectifier Nonlinearities Improve Neural Network Acoustic Models (2013), Stanford Xavier Glorot, Yoshua Bengio, Understanding the difficulty of training deep feedforward neural networks (2010), Proceedings of Machine Learning Research Kaiming He et al., Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification (2015), arxiv.org Activation function, Wikipedia Vanishing gradient problem, Wikipedia Rectifier (neural networks), Wikipedia Piecewise Linear Function, Wikipedia https://medium.com/@danqing/a-practical-guide-to-relu-b83ca804f1f7 Wenling Shang, Kihyuk Sohn, Diogo Almeida, Honglak Lee, Understanding and Improving Convolutional Neural Networks via Concatenated Rectified Linear Units (2016), arxiv.org Softmax function, Wikipedia https://medium.com/@himanshuxd/activation-functions-sigmoid-relu-leaky-relu-and-softmax-basics-for-neural-networks-and-deep-8d9c70eed91e Prajit Ramachandran, Barret Zoph, Quoc V. Le, Searching for activation functions (2017), arxiv.org
[ { "code": null, "e": 352, "s": 171, "text": "The activation function defines the output of a neuron / node given an input or set of input (output of multiple neurons). It’s the mimic of the stimulation of a biological neuron." }, { "code": null, "e": 640, "s": 352, "text": "The output of the activation function to the next layer (in shallow neural network: input layer and output layer, and in deep network to the next hidden layer) is called forward propagation (information propagation). It’s considered as a non linearity transformation of a neural network." }, { "code": null, "e": 696, "s": 640, "text": "A notebook with all the code are available here: GitHub" }, { "code": null, "e": 703, "s": 696, "text": "Binary" }, { "code": null, "e": 710, "s": 703, "text": "Linear" }, { "code": null, "e": 718, "s": 710, "text": "Sigmoid" }, { "code": null, "e": 723, "s": 718, "text": "Tanh" }, { "code": null, "e": 728, "s": 723, "text": "ReLU" }, { "code": null, "e": 747, "s": 728, "text": "Leaky ReLU (LReLU)" }, { "code": null, "e": 771, "s": 747, "text": "Parametric ReLU (PReLU)" }, { "code": null, "e": 801, "s": 771, "text": "Exponential Linear Unit (eLU)" }, { "code": null, "e": 808, "s": 801, "text": "ReLU-6" }, { "code": null, "e": 817, "s": 808, "text": "Softplus" }, { "code": null, "e": 826, "s": 817, "text": "Softsign" }, { "code": null, "e": 834, "s": 826, "text": "Softmax" }, { "code": null, "e": 840, "s": 834, "text": "Swish" }, { "code": null, "e": 1040, "s": 840, "text": "The binary activation function is the simpliest. It’s based on binary classifier, the output is 0 if values are negatives else 1. See this activation function as a threshold in binary classification." }, { "code": null, "e": 1086, "s": 1040, "text": "The code for a binary activation function is:" }, { "code": null, "e": 1145, "s": 1086, "text": "def binary_active_function(x): return 0 if x < 0 else 1" }, { "code": null, "e": 1183, "s": 1145, "text": "What is the output of this function ?" }, { "code": null, "e": 1288, "s": 1183, "text": "for i in [-5, -3, -1, 0, 2, 5]: print(binary_active_function(i))output: 0 0 0 1 1 1" }, { "code": null, "e": 1300, "s": 1288, "text": "Or visualy:" }, { "code": null, "e": 1305, "s": 1300, "text": "Pro:" }, { "code": null, "e": 1327, "s": 1305, "text": "Binary classification" }, { "code": null, "e": 1333, "s": 1327, "text": "Cons:" }, { "code": null, "e": 1375, "s": 1333, "text": "Doesn’t work in multilabel classification" }, { "code": null, "e": 1463, "s": 1375, "text": "The derivative for the gradient calculation is always 0 so impossible to update weights" }, { "code": null, "e": 1591, "s": 1463, "text": "The next step after the binary function is to use a linear function instead of a step. The output is proportional to the input." }, { "code": null, "e": 1618, "s": 1591, "text": "The corresponding code is:" }, { "code": null, "e": 1666, "s": 1618, "text": "def linear_active_function(a, x): return a*x" }, { "code": null, "e": 1713, "s": 1666, "text": "We can compute it for different values of “a”:" }, { "code": null, "e": 1921, "s": 1713, "text": "$ x = numpy.linspace(-10, 10, 5000)$ y_1 = [linear_active_function(1, i) for i in x] # a = 1$ y_2 = [linear_active_function(2, i) for i in x] # a = 2$ y_1> [-10.0, -9.9, -9.8, -9.7, ..., 9.7, 9.8, 9.9, 10.0]" }, { "code": null, "e": 1968, "s": 1921, "text": "If we plot the results for a = 1, 2, 4 and 10:" }, { "code": null, "e": 1974, "s": 1968, "text": "Pros:" }, { "code": null, "e": 2011, "s": 1974, "text": "Binary and multiclass classification" }, { "code": null, "e": 2032, "s": 2011, "text": "Highly interpretable" }, { "code": null, "e": 2038, "s": 2032, "text": "Cons:" }, { "code": null, "e": 2151, "s": 2038, "text": "The derivative correspond to “a” so the update of weights and biaises during the backprogation will be constant." }, { "code": null, "e": 2201, "s": 2151, "text": "Not efficient if the gradient is always the same." }, { "code": null, "e": 2440, "s": 2201, "text": "Sigmoid is the most used activation function with ReLU and tanh. It’s a non-linear activation function also called logistic function. The output of this activation function vary between 0 and 1. All the output of neurons will be positive." }, { "code": null, "e": 2477, "s": 2440, "text": "The corresponding code is as follow:" }, { "code": null, "e": 2540, "s": 2477, "text": "def sigmoid_active_function(x): return 1./(1+numpy.exp(-x))" }, { "code": null, "e": 2561, "s": 2540, "text": "A quick computation:" }, { "code": null, "e": 2762, "s": 2561, "text": "$ x = numpy.linspace(-10, 10, 5000)$ y = [sigmoid_active_function(i) for i in x] $ y> [4.5397868702434395e-05, 4.5854103946941324e-05, ... , 0.9999532196250409, 0.9999536850759906, 0.9999541458960531]" }, { "code": null, "e": 2786, "s": 2762, "text": "If we plot the results:" }, { "code": null, "e": 2792, "s": 2786, "text": "Cons:" }, { "code": null, "e": 2948, "s": 2792, "text": "The problem of this function is that the output of each neuron can saturate. Values greater than 1 are shape as 1 and values smaller than 0 are shape as 0." }, { "code": null, "e": 3032, "s": 2948, "text": "The best sensitivity for the sigmoid function is around the central point (0, 0.5)." }, { "code": null, "e": 3237, "s": 3032, "text": "A big problem appear during the saturation, the algorithm can not learn during this position (it’s the source of the vanishing gradient problem, corresponding to the absence of direction in the gradient)." }, { "code": null, "e": 3607, "s": 3237, "text": "The tangent hyperbolic function (tanh) is similar to the sigmoïd function in the way that their form are similar. Tanh is symmetric in 0 and the values are in the range -1 and 1. As the sigmoid they are very sensitive in the central point (0, 0) but they saturate for very large number (positive and negative). This symmetry make them better than the sigmoid function." }, { "code": null, "e": 3659, "s": 3607, "text": "The corresponding code to apply a tanh function is:" }, { "code": null, "e": 3731, "s": 3659, "text": "def tanh_active_function(x): return 2*sigmoid_active_function(2*x)-1" }, { "code": null, "e": 3753, "s": 3731, "text": "Compute the y values:" }, { "code": null, "e": 3945, "s": 3753, "text": "$ x = numpy.linspace(-10, 10, 5000)$ y = [tanh_active_function(i) for i in x] $ y> [-0.9999999958776927, -0.9999999957944167, ... , 0.9999999956227836, 0.9999999957094583, 0.9999999957944166]" }, { "code": null, "e": 3975, "s": 3945, "text": "And the corresponding result:" }, { "code": null, "e": 3981, "s": 3975, "text": "Pros:" }, { "code": null, "e": 4004, "s": 3981, "text": "Range between -1 and 1" }, { "code": null, "e": 4069, "s": 4004, "text": "The gradient is stronger than sigmoid ( derivatives are steeper)" }, { "code": null, "e": 4075, "s": 4069, "text": "Cons:" }, { "code": null, "e": 4132, "s": 4075, "text": "Like sigmoid, tanh also has a vanishing gradient problem" }, { "code": null, "e": 4143, "s": 4132, "text": "Saturation" }, { "code": null, "e": 4405, "s": 4143, "text": "The REctified Linear Unit was develop to avoid the saturation with big positive numbers. The non-linearity permit to conserve and learn the patterns inside the data and the linear part (>0 — also called piecewise linear function) make them easily interpretable." }, { "code": null, "e": 4466, "s": 4405, "text": "The function below shows how to implement the ReLU function:" }, { "code": null, "e": 4531, "s": 4466, "text": "def relu_active_function(x): return numpy.array([0, x]).max()" }, { "code": null, "e": 4546, "s": 4531, "text": "y computation:" }, { "code": null, "e": 4664, "s": 4546, "text": "$ x = numpy.linspace(-10, 10, 5000)$ y = [relu_active_function(i) for i in x] $ y> [0.0, 0.0, ... , 9.97, 9.98, 9.99]" }, { "code": null, "e": 4677, "s": 4664, "text": "The results:" }, { "code": null, "e": 4683, "s": 4677, "text": "Pros:" }, { "code": null, "e": 4715, "s": 4683, "text": "Easy to implement and very fast" }, { "code": null, "e": 4728, "s": 4715, "text": "True 0 value" }, { "code": null, "e": 4786, "s": 4728, "text": "Optimization are easy when activation function are linear" }, { "code": null, "e": 4829, "s": 4786, "text": "Most used in the neural networks ecosystem" }, { "code": null, "e": 4835, "s": 4829, "text": "Cons:" }, { "code": null, "e": 5075, "s": 4835, "text": "The function can not be differentiable when x = 0. The gradient descent can’t be computed for this point but, in practice that has not an influence. The linear part correspond to a slope with value 1 and the negative part is equal to zero." }, { "code": null, "e": 5307, "s": 5075, "text": "“dying ReLU problem”: corresponds to the inactive part of the neurons if the output are 0. There no gradient when neurons are not active so if a large part of neurons are not activated it can result of poor performance of the model" }, { "code": null, "e": 5364, "s": 5307, "text": "Not appropriate for RNN class algorithm (RNN, LSTM, GRU)" }, { "code": null, "e": 5578, "s": 5364, "text": "This activation function is a modification of the ReLU activation function to avoid the “dying problem”. The function return a linear slope where a=0.01 which permit to keep neurons activated with a gradient flow." }, { "code": null, "e": 5598, "s": 5578, "text": "See the code below:" }, { "code": null, "e": 5666, "s": 5598, "text": "def leaky_relu_active_function(x): return 0.01*x if x < 0 else x" }, { "code": null, "e": 5706, "s": 5666, "text": "Compute the y axis to plot the results:" }, { "code": null, "e": 5835, "s": 5706, "text": "$ x = numpy.linspace(-10, 10, 5000)$ y = [leaky_relu_active_function(i) for i in x] $ y> [-0.1, -0.0999, ... , 9.97, 9.98, 9.99]" }, { "code": null, "e": 5853, "s": 5835, "text": "Plot the results:" }, { "code": null, "e": 5859, "s": 5853, "text": "Pros:" }, { "code": null, "e": 5892, "s": 5859, "text": "Correct the “dying ReLU problem”" }, { "code": null, "e": 5959, "s": 5892, "text": "Same comportement of the ReLU activation function for the part y=x" }, { "code": null, "e": 6253, "s": 5959, "text": "After the Leaky ReLU there is another activation function created to avoid the “dying ReLU problem”, the parametric or parametrised ReLU. The coefficient a is not lock at 0.01 (Leaky ReLU) but it free to estimate. It’s a generalization of the ReLU, the algorithm learn the rectifier parameter." }, { "code": null, "e": 6263, "s": 6253, "text": "The code:" }, { "code": null, "e": 6336, "s": 6263, "text": "def parametric_relu_active_function(a, x): return a*x if x < 0 else x" }, { "code": null, "e": 6380, "s": 6336, "text": "Compute the results for different a values:" }, { "code": null, "e": 6705, "s": 6380, "text": "$ x = numpy.linspace(-10, 10, 5000)$ y_1 = [parametric_relu_active_function(0.25, i) for i in x] $ y_2 = [parametric_relu_active_function(0.5, i) for i in x]$ y_3 = [parametric_relu_active_function(0.75, i) for i in x]$ y_4 = [parametric_relu_active_function(1, i) for i in x]$ y_1> [-2.5, -2.4975, ... , 9.97, 9.98, 9.99]" }, { "code": null, "e": 6750, "s": 6705, "text": "Plot the results for a = 0.25, 0.5, 0.75, 1:" }, { "code": null, "e": 6886, "s": 6750, "text": "If a = 0 the parametric ReLU is equivalent to the ReLU activation function. If a=0.01 the parametric ReLU correspond to the Leaky ReLU." }, { "code": null, "e": 6892, "s": 6886, "text": "Pros:" }, { "code": null, "e": 6932, "s": 6892, "text": "Generalize the ReLU activation function" }, { "code": null, "e": 6963, "s": 6932, "text": "Avoid the “dying ReLU problem”" }, { "code": null, "e": 7014, "s": 6963, "text": "The parameter “a” is learned by the neural network" }, { "code": null, "e": 7154, "s": 7014, "text": "eLU is another variation of the ReLU function. The negative part of the function is handled by the exponential function with a slow smooth." }, { "code": null, "e": 7182, "s": 7154, "text": "The corresponding function:" }, { "code": null, "e": 7258, "s": 7182, "text": "def elu_active_function(a, x): return a*(numpy.exp(x)-1) if x < 0 else x" }, { "code": null, "e": 7273, "s": 7258, "text": "y computation:" }, { "code": null, "e": 7573, "s": 7273, "text": "$ x = numpy.linspace(-10, 10, 5000)$ y_1 = [elu_active_function(0.1, i) for i in x] $ y_2 = [elu_active_function(1, i) for i in x]$ y_3 = [elu_active_function(2, i) for i in x]$ y_4 = [elu_active_function(5, i) for i in x]$ y_1> [-0.09999546000702375, -0.09999541437933579, ... , 9.97, 9.98, 9.99]" }, { "code": null, "e": 7612, "s": 7573, "text": "Plot the results for a = 0.1, 1, 2, 4:" }, { "code": null, "e": 7618, "s": 7612, "text": "Pros:" }, { "code": null, "e": 7704, "s": 7618, "text": "ELU becomes smooth slowly until its output equal to -α whereas RELU sharply smoothes." }, { "code": null, "e": 7741, "s": 7704, "text": "ELU is a strong alternative to ReLU." }, { "code": null, "e": 7791, "s": 7741, "text": "Unlike to ReLU, ELU can produce negative outputs." }, { "code": null, "e": 7797, "s": 7791, "text": "Cons:" }, { "code": null, "e": 7873, "s": 7797, "text": "For x > 0, it can blow up the activation with the output range of [0, inf]." }, { "code": null, "e": 8049, "s": 7873, "text": "Another variation of the ReLU function is the ReLU-6, 6 is an arbitrary parameter fixed by hand. The advantage is to shape the output for large positive number to the 6 value." }, { "code": null, "e": 8073, "s": 8049, "text": "The corresponding code:" }, { "code": null, "e": 8154, "s": 8073, "text": "def relu_6_active_function(x): return numpy.array([0, x]).max() if x<6 else 6" }, { "code": null, "e": 8173, "s": 8154, "text": "The y computation:" }, { "code": null, "e": 8218, "s": 8173, "text": "$ y = [relu_6_active_function(i) for i in x]" }, { "code": null, "e": 8236, "s": 8218, "text": "Plot the results:" }, { "code": null, "e": 8400, "s": 8236, "text": "The softplus activation function is an alternative of sigmoid and tanh functions. This functions have limits (upper, lower) but softplus is in the range (0, +inf)." }, { "code": null, "e": 8424, "s": 8400, "text": "The corresponding code:" }, { "code": null, "e": 8492, "s": 8424, "text": "def softplus_active_function(x): return math.log(1+numpy.exp(x))" }, { "code": null, "e": 8507, "s": 8492, "text": "y computation:" }, { "code": null, "e": 8554, "s": 8507, "text": "$ y = [softplus_active_function(i) for i in x]" }, { "code": null, "e": 8572, "s": 8554, "text": "Plot the results:" }, { "code": null, "e": 8773, "s": 8572, "text": "This activation function is a variation of tanh but is not very used in practice. tanh and softsign functions are closely related, tanh converges exponentially whereas softsign converges polynomially." }, { "code": null, "e": 8797, "s": 8773, "text": "The corresponding code:" }, { "code": null, "e": 8904, "s": 8797, "text": "def softsign_active_function(x): return x / (1 + abs(x) )$ y = [softsign_active_function(i) for i in x]" }, { "code": null, "e": 8922, "s": 8904, "text": "Plot the results:" }, { "code": null, "e": 9068, "s": 8922, "text": "The softmax activation function is different from the other because it compute the probability distribution. The sum of the output is equal to 1." }, { "code": null, "e": 9092, "s": 9068, "text": "The corresponding code:" }, { "code": null, "e": 9171, "s": 9092, "text": "def softmax_active_function(x): return numpy.exp(x)/numpy.sum(numpy.exp(x))" }, { "code": null, "e": 9349, "s": 9171, "text": "Compute the output is different because it’s a probability distribution taking into account the sum of exponential, the function needed all the x points to compute the output y." }, { "code": null, "e": 9480, "s": 9349, "text": "$ x = [0.8, 1.2, 2.4, 4.6]$ y = softmax_active_function(x)$ y> [0.01917691, 0.02860859, 0.09498386, 0.85723064]$ numpy.sum(y)> 1.0" }, { "code": null, "e": 9698, "s": 9480, "text": "Swish is the newer activation function, published by Google in 2017 it improves the performances of ReLU on deeper models. This function is a variation of sigmoid function because it can be expressed by: x*sigmoid(x)." }, { "code": null, "e": 9974, "s": 9698, "text": "Swish has the properties of one-sided boundedness at zero, smoothness, and non-monotonicity, which may play a role in the observed efficacy of Swish and similar activation functions.SWISH: A SELF-GATED ACTIVATION FUNCTION, Prajit Ramachandran∗ , Barret Zoph, Quoc V. Le, 2017" }, { "code": null, "e": 9999, "s": 9974, "text": "The corresponding codes:" }, { "code": null, "e": 10059, "s": 9999, "text": "def swish_active_function(x): return x/(1+numpy.exp(-x))" }, { "code": null, "e": 10063, "s": 10059, "text": "Or:" }, { "code": null, "e": 10132, "s": 10063, "text": "def swish_active_function(x): return x*sigmoid_active_function(x)" }, { "code": null, "e": 10152, "s": 10132, "text": "Compute the values:" }, { "code": null, "e": 10345, "s": 10152, "text": "$ x = numpy.linspace(-10, 10, 5000)$ y = [swish_active_function(i) for i in x]$ y> [-0.0004539786870243439, -0.0004967044303692657, ..., 9.699405586525717, 9.799456604457717, 9.89950329556963]" }, { "code": null, "e": 10363, "s": 10345, "text": "Plot the results:" }, { "code": null, "e": 10369, "s": 10363, "text": "Pros:" }, { "code": null, "e": 10414, "s": 10369, "text": "Differentiable on each point compare to ReLU" }, { "code": null, "e": 10665, "s": 10414, "text": "Here are presented some activation functions (most popular) with their code and representation. Hope this visualisation could permit to everyone to understand the output of neurons and determined which function is better for the problem they work on." }, { "code": null, "e": 10741, "s": 10665, "text": "The last plot corresponds to the activation functions stack in one graphic." }, { "code": null, "e": 10852, "s": 10741, "text": "https://medium.com/r/?url=https%3A%2F%2Fml-cheatsheet.readthedocs.io%2Fen%2Flatest%2Factivation_functions.html" }, { "code": null, "e": 10959, "s": 10852, "text": "https://machinelearningmastery.com/rectified-linear-activation-function-for-deep-learning-neural-networks/" }, { "code": null, "e": 11036, "s": 10959, "text": "Ian Goodfellow, Joshua Bengio and Aaron courville, Deep Learning (2016), MIT" }, { "code": null, "e": 11137, "s": 11036, "text": "Kevin Jarrett et al., What is the best multi-stage architecture for object recognition? (2009), IEEE" }, { "code": null, "e": 11242, "s": 11137, "text": "Vinod Nair and Geoffrey Hinton, Rectified Linear Units Improve Restricted Boltzmann Machines (2010), ACM" }, { "code": null, "e": 11375, "s": 11242, "text": "Xavier Glorot, Antoine Bordes, Yoshua Bengio, Deep Sparse Rectifier Neural Networks (2011), Proceedings of Machine Learning Research" }, { "code": null, "e": 11505, "s": 11375, "text": "Andrew L. Maas, Awni Y. Hannun and Andrew Y. Ng, Rectifier Nonlinearities Improve Neural Network Acoustic Models (2013), Stanford" }, { "code": null, "e": 11658, "s": 11505, "text": "Xavier Glorot, Yoshua Bengio, Understanding the difficulty of training deep feedforward neural networks (2010), Proceedings of Machine Learning Research" }, { "code": null, "e": 11787, "s": 11658, "text": "Kaiming He et al., Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification (2015), arxiv.org" }, { "code": null, "e": 11818, "s": 11787, "text": "Activation function, Wikipedia" }, { "code": null, "e": 11856, "s": 11818, "text": "Vanishing gradient problem, Wikipedia" }, { "code": null, "e": 11895, "s": 11856, "text": "Rectifier (neural networks), Wikipedia" }, { "code": null, "e": 11932, "s": 11895, "text": "Piecewise Linear Function, Wikipedia" }, { "code": null, "e": 11999, "s": 11932, "text": "https://medium.com/@danqing/a-practical-guide-to-relu-b83ca804f1f7" }, { "code": null, "e": 12171, "s": 11999, "text": "Wenling Shang, Kihyuk Sohn, Diogo Almeida, Honglak Lee, Understanding and Improving Convolutional Neural Networks via Concatenated Rectified Linear Units (2016), arxiv.org" }, { "code": null, "e": 12199, "s": 12171, "text": "Softmax function, Wikipedia" }, { "code": null, "e": 12336, "s": 12199, "text": "https://medium.com/@himanshuxd/activation-functions-sigmoid-relu-leaky-relu-and-softmax-basics-for-neural-networks-and-deep-8d9c70eed91e" } ]
Python Identity Operators Example
Identity operators compare the memory locations of two objects. There are two Identity operators as explained below − #!/usr/bin/python a = 20 b = 20 if ( a is b ): print "Line 1 - a and b have same identity" else: print "Line 1 - a and b do not have same identity" if ( id(a) == id(b) ): print "Line 2 - a and b have same identity" else: print "Line 2 - a and b do not have same identity" b = 30 if ( a is b ): print "Line 3 - a and b have same identity" else: print "Line 3 - a and b do not have same identity" if ( a is not b ): print "Line 4 - a and b do not have same identity" else: print "Line 4 - a and b have same identity" When you execute the above program it produces the following result − Line 1 - a and b have same identity Line 2 - a and b have same identity Line 3 - a and b do not have same identity Line 4 - a and b do not have same identity 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2362, "s": 2244, "text": "Identity operators compare the memory locations of two objects. There are two Identity operators as explained below −" }, { "code": null, "e": 2907, "s": 2362, "text": "#!/usr/bin/python\n\na = 20\nb = 20\n\nif ( a is b ):\n print \"Line 1 - a and b have same identity\"\nelse:\n print \"Line 1 - a and b do not have same identity\"\n\nif ( id(a) == id(b) ):\n print \"Line 2 - a and b have same identity\"\nelse:\n print \"Line 2 - a and b do not have same identity\"\n\nb = 30\nif ( a is b ):\n print \"Line 3 - a and b have same identity\"\nelse:\n print \"Line 3 - a and b do not have same identity\"\n\nif ( a is not b ):\n print \"Line 4 - a and b do not have same identity\"\nelse:\n print \"Line 4 - a and b have same identity\"\n" }, { "code": null, "e": 2977, "s": 2907, "text": "When you execute the above program it produces the following result −" }, { "code": null, "e": 3136, "s": 2977, "text": "Line 1 - a and b have same identity\nLine 2 - a and b have same identity\nLine 3 - a and b do not have same identity\nLine 4 - a and b do not have same identity\n" }, { "code": null, "e": 3173, "s": 3136, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3189, "s": 3173, "text": " Malhar Lathkar" }, { "code": null, "e": 3222, "s": 3189, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3241, "s": 3222, "text": " Arnab Chakraborty" }, { "code": null, "e": 3276, "s": 3241, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3298, "s": 3276, "text": " In28Minutes Official" }, { "code": null, "e": 3332, "s": 3298, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3360, "s": 3332, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3395, "s": 3360, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3409, "s": 3395, "text": " Lets Kode It" }, { "code": null, "e": 3442, "s": 3409, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3459, "s": 3442, "text": " Abhilash Nelson" }, { "code": null, "e": 3466, "s": 3459, "text": " Print" }, { "code": null, "e": 3477, "s": 3466, "text": " Add Notes" } ]
Creating SVG Image using PyCairo - GeeksforGeeks
12 Nov, 2020 In this article we will see how we can create SVG file using PyCairo in Python. SVG : An SVG file is a graphics file that uses a two-dimensional graphic vector format that defines images using an XML-based text format. As a standard format for showing vector graphics on the web, SVG files are developed. PyCairo : It is a Python module providing bindings for the cairo graphics library.This library is used for creating SVG i.e vector files in python. In order to install the pycairo module we will use the command given below Installation: pip install pycairo Opening SVG file : The easiest and quickest way to open an SVG file to view it (read only) is with a modern web browser like Chrome, Firefox, Edge, or Internet Explorer—nearly all of them should provide some sort of rendering support for the SVG format. Steps-by-step Approach: 1. Import the cairo module. 2. Create an SVG surface and add context to it. 3. For creating a small face add two rectangles for eyes. 4. Add a curve line for the smile. 5. Set the color and width of the context. Below is the complete program based on the above approach: Python3 # importing pycairoimport cairo # creating a SVG surface# here geek is file name & 700, 700 is dimensionwith cairo.SVGSurface("geek.svg", 700, 700) as surface: # creating a cairo context object context = cairo.Context(surface) # creating a rectangle(square) for left eye context.rectangle(100, 100, 100, 100) # creating a rectangle(square) for right eye context.rectangle(500, 100, 100, 100) # creating position for the curves x, y, x1, y1 = 0.1, 0.5, 0.4, 0.9 x2, y2, x3, y3 = 0.4, 0.1, 0.9, 0.6 # setting scale of the context context.scale(700, 700) # setting line width of the context context.set_line_width(0.04) # move the context to x,y position context.move_to(x, y) # draw the curve for smile context.curve_to(x1, y1, x2, y2, x3, y3) # setting color of the context context.set_source_rgba(0.4, 1, 0.4, 1) # stroke out the color and width property context.stroke() # printing message when file is savedprint("File Saved") Output: Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists Python program to convert a list to string Reading and Writing to text files in Python sum() function in Python
[ { "code": null, "e": 24190, "s": 24162, "text": "\n12 Nov, 2020" }, { "code": null, "e": 24271, "s": 24190, "text": "In this article we will see how we can create SVG file using PyCairo in Python. " }, { "code": null, "e": 24496, "s": 24271, "text": "SVG : An SVG file is a graphics file that uses a two-dimensional graphic vector format that defines images using an XML-based text format. As a standard format for showing vector graphics on the web, SVG files are developed." }, { "code": null, "e": 24721, "s": 24496, "text": "PyCairo : It is a Python module providing bindings for the cairo graphics library.This library is used for creating SVG i.e vector files in python. In order to install the pycairo module we will use the command given below " }, { "code": null, "e": 24735, "s": 24721, "text": "Installation:" }, { "code": null, "e": 24756, "s": 24735, "text": "pip install pycairo\n" }, { "code": null, "e": 25012, "s": 24756, "text": "Opening SVG file : The easiest and quickest way to open an SVG file to view it (read only) is with a modern web browser like Chrome, Firefox, Edge, or Internet Explorer—nearly all of them should provide some sort of rendering support for the SVG format. " }, { "code": null, "e": 25250, "s": 25012, "text": "Steps-by-step Approach: 1. Import the cairo module. 2. Create an SVG surface and add context to it. 3. For creating a small face add two rectangles for eyes. 4. Add a curve line for the smile. 5. Set the color and width of the context. " }, { "code": null, "e": 25309, "s": 25250, "text": "Below is the complete program based on the above approach:" }, { "code": null, "e": 25317, "s": 25309, "text": "Python3" }, { "code": "# importing pycairoimport cairo # creating a SVG surface# here geek is file name & 700, 700 is dimensionwith cairo.SVGSurface(\"geek.svg\", 700, 700) as surface: # creating a cairo context object context = cairo.Context(surface) # creating a rectangle(square) for left eye context.rectangle(100, 100, 100, 100) # creating a rectangle(square) for right eye context.rectangle(500, 100, 100, 100) # creating position for the curves x, y, x1, y1 = 0.1, 0.5, 0.4, 0.9 x2, y2, x3, y3 = 0.4, 0.1, 0.9, 0.6 # setting scale of the context context.scale(700, 700) # setting line width of the context context.set_line_width(0.04) # move the context to x,y position context.move_to(x, y) # draw the curve for smile context.curve_to(x1, y1, x2, y2, x3, y3) # setting color of the context context.set_source_rgba(0.4, 1, 0.4, 1) # stroke out the color and width property context.stroke() # printing message when file is savedprint(\"File Saved\")", "e": 26333, "s": 25317, "text": null }, { "code": null, "e": 26343, "s": 26333, "text": "Output: " }, { "code": null, "e": 26350, "s": 26343, "text": "Python" }, { "code": null, "e": 26448, "s": 26350, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26483, "s": 26448, "text": "Read a file line by line in Python" }, { "code": null, "e": 26505, "s": 26483, "text": "Enumerate() in Python" }, { "code": null, "e": 26537, "s": 26505, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26567, "s": 26537, "text": "Iterate over a list in Python" }, { "code": null, "e": 26609, "s": 26567, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26635, "s": 26609, "text": "Python String | replace()" }, { "code": null, "e": 26672, "s": 26635, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 26715, "s": 26672, "text": "Python program to convert a list to string" }, { "code": null, "e": 26759, "s": 26715, "text": "Reading and Writing to text files in Python" } ]
Writing data to a file using BufferedWriter class in Java
The BufferedWriter class of Java is used to write a stream of characters to the specified destination (character-output stream). It initially stores all the characters in a buffer and pushes the contents of the buffer to the destination, making the writing of characters, arrays and Strings efficient. You can specify the required size of the buffer at the time of instantiating this class. In the following Java program, we are trying to print a line on the console (Standard Output Stream). Here we are invoking the write() method by passing the required String. Live Demo import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStreamWriter; public class BufferedWriterExample { public static void main(String args[]) throws IOException { //Instantiating the OutputStreamWriter class OutputStreamWriter out = new OutputStreamWriter(System.out); //Instantiating the BufferedWriter BufferedWriter writer = new BufferedWriter(out); //Writing data to the console writer.write("Hello welcome to Tutorialspoint"); writer.flush(); } } Hello welcome to Tutorialspoint
[ { "code": null, "e": 1364, "s": 1062, "text": "The BufferedWriter class of Java is used to write a stream of characters to the specified destination (character-output stream). It initially stores all the characters in a buffer and pushes the contents of the buffer to the destination, making the writing of characters, arrays and Strings efficient." }, { "code": null, "e": 1453, "s": 1364, "text": "You can specify the required size of the buffer at the time of instantiating this class." }, { "code": null, "e": 1627, "s": 1453, "text": "In the following Java program, we are trying to print a line on the console (Standard Output Stream). Here we are invoking the write() method by passing the required String." }, { "code": null, "e": 1638, "s": 1627, "text": " Live Demo" }, { "code": null, "e": 2166, "s": 1638, "text": "import java.io.BufferedWriter;\nimport java.io.IOException;\nimport java.io.OutputStreamWriter;\npublic class BufferedWriterExample {\n public static void main(String args[]) throws IOException {\n //Instantiating the OutputStreamWriter class\n OutputStreamWriter out = new OutputStreamWriter(System.out);\n //Instantiating the BufferedWriter\n BufferedWriter writer = new BufferedWriter(out);\n //Writing data to the console\n writer.write(\"Hello welcome to Tutorialspoint\");\n writer.flush();\n }\n}" }, { "code": null, "e": 2198, "s": 2166, "text": "Hello welcome to Tutorialspoint" } ]
PL/SQL - Procedures
In this chapter, we will discuss Procedures in PL/SQL. A subprogram is a program unit/module that performs a particular task. These subprograms are combined to form larger programs. This is basically called the 'Modular design'. A subprogram can be invoked by another subprogram or program which is called the calling program. A subprogram can be created − At the schema level Inside a package Inside a PL/SQL block At the schema level, subprogram is a standalone subprogram. It is created with the CREATE PROCEDURE or the CREATE FUNCTION statement. It is stored in the database and can be deleted with the DROP PROCEDURE or DROP FUNCTION statement. A subprogram created inside a package is a packaged subprogram. It is stored in the database and can be deleted only when the package is deleted with the DROP PACKAGE statement. We will discuss packages in the chapter 'PL/SQL - Packages'. PL/SQL subprograms are named PL/SQL blocks that can be invoked with a set of parameters. PL/SQL provides two kinds of subprograms − Functions − These subprograms return a single value; mainly used to compute and return a value. Functions − These subprograms return a single value; mainly used to compute and return a value. Procedures − These subprograms do not return a value directly; mainly used to perform an action. Procedures − These subprograms do not return a value directly; mainly used to perform an action. This chapter is going to cover important aspects of a PL/SQL procedure. We will discuss PL/SQL function in the next chapter. Each PL/SQL subprogram has a name, and may also have a parameter list. Like anonymous PL/SQL blocks, the named blocks will also have the following three parts − Declarative Part It is an optional part. However, the declarative part for a subprogram does not start with the DECLARE keyword. It contains declarations of types, cursors, constants, variables, exceptions, and nested subprograms. These items are local to the subprogram and cease to exist when the subprogram completes execution. Executable Part This is a mandatory part and contains statements that perform the designated action. Exception-handling This is again an optional part. It contains the code that handles run-time errors. A procedure is created with the CREATE OR REPLACE PROCEDURE statement. The simplified syntax for the CREATE OR REPLACE PROCEDURE statement is as follows − CREATE [OR REPLACE] PROCEDURE procedure_name [(parameter_name [IN | OUT | IN OUT] type [, ...])] {IS | AS} BEGIN < procedure_body > END procedure_name; Where, procedure-name specifies the name of the procedure. procedure-name specifies the name of the procedure. [OR REPLACE] option allows the modification of an existing procedure. [OR REPLACE] option allows the modification of an existing procedure. The optional parameter list contains name, mode and types of the parameters. IN represents the value that will be passed from outside and OUT represents the parameter that will be used to return a value outside of the procedure. The optional parameter list contains name, mode and types of the parameters. IN represents the value that will be passed from outside and OUT represents the parameter that will be used to return a value outside of the procedure. procedure-body contains the executable part. procedure-body contains the executable part. The AS keyword is used instead of the IS keyword for creating a standalone procedure. The AS keyword is used instead of the IS keyword for creating a standalone procedure. The following example creates a simple procedure that displays the string 'Hello World!' on the screen when executed. CREATE OR REPLACE PROCEDURE greetings AS BEGIN dbms_output.put_line('Hello World!'); END; / When the above code is executed using the SQL prompt, it will produce the following result − Procedure created. A standalone procedure can be called in two ways − Using the EXECUTE keyword Using the EXECUTE keyword Calling the name of the procedure from a PL/SQL block Calling the name of the procedure from a PL/SQL block The above procedure named 'greetings' can be called with the EXECUTE keyword as − EXECUTE greetings; The above call will display − Hello World PL/SQL procedure successfully completed. The procedure can also be called from another PL/SQL block − BEGIN greetings; END; / The above call will display − Hello World PL/SQL procedure successfully completed. A standalone procedure is deleted with the DROP PROCEDURE statement. Syntax for deleting a procedure is − DROP PROCEDURE procedure-name; You can drop the greetings procedure by using the following statement − DROP PROCEDURE greetings; The following table lists out the parameter modes in PL/SQL subprograms − IN An IN parameter lets you pass a value to the subprogram. It is a read-only parameter. Inside the subprogram, an IN parameter acts like a constant. It cannot be assigned a value. You can pass a constant, literal, initialized variable, or expression as an IN parameter. You can also initialize it to a default value; however, in that case, it is omitted from the subprogram call. It is the default mode of parameter passing. Parameters are passed by reference. OUT An OUT parameter returns a value to the calling program. Inside the subprogram, an OUT parameter acts like a variable. You can change its value and reference the value after assigning it. The actual parameter must be variable and it is passed by value. IN OUT An IN OUT parameter passes an initial value to a subprogram and returns an updated value to the caller. It can be assigned a value and the value can be read. The actual parameter corresponding to an IN OUT formal parameter must be a variable, not a constant or an expression. Formal parameter must be assigned a value. Actual parameter is passed by value. This program finds the minimum of two values. Here, the procedure takes two numbers using the IN mode and returns their minimum using the OUT parameters. DECLARE a number; b number; c number; PROCEDURE findMin(x IN number, y IN number, z OUT number) IS BEGIN IF x < y THEN z:= x; ELSE z:= y; END IF; END; BEGIN a:= 23; b:= 45; findMin(a, b, c); dbms_output.put_line(' Minimum of (23, 45) : ' || c); END; / When the above code is executed at the SQL prompt, it produces the following result − Minimum of (23, 45) : 23 PL/SQL procedure successfully completed. This procedure computes the square of value of a passed value. This example shows how we can use the same parameter to accept a value and then return another result. DECLARE a number; PROCEDURE squareNum(x IN OUT number) IS BEGIN x := x * x; END; BEGIN a:= 23; squareNum(a); dbms_output.put_line(' Square of (23): ' || a); END; / When the above code is executed at the SQL prompt, it produces the following result − Square of (23): 529 PL/SQL procedure successfully completed. Actual parameters can be passed in three ways − Positional notation Named notation Mixed notation In positional notation, you can call the procedure as − findMin(a, b, c, d); In positional notation, the first actual parameter is substituted for the first formal parameter; the second actual parameter is substituted for the second formal parameter, and so on. So, a is substituted for x, b is substituted for y, c is substituted for z and d is substituted for m. In named notation, the actual parameter is associated with the formal parameter using the arrow symbol ( => ). The procedure call will be like the following − findMin(x => a, y => b, z => c, m => d); In mixed notation, you can mix both notations in procedure call; however, the positional notation should precede the named notation. The following call is legal − findMin(a, b, c, m => d); However, this is not legal: findMin(x => a, b, c, d); Print Add Notes Bookmark this page
[ { "code": null, "e": 2392, "s": 2065, "text": "In this chapter, we will discuss Procedures in PL/SQL. A subprogram is a program unit/module that performs a particular task. These subprograms are combined to form larger programs. This is basically called the 'Modular design'. A subprogram can be invoked by another subprogram or program which is called the calling program." }, { "code": null, "e": 2422, "s": 2392, "text": "A subprogram can be created −" }, { "code": null, "e": 2442, "s": 2422, "text": "At the schema level" }, { "code": null, "e": 2459, "s": 2442, "text": "Inside a package" }, { "code": null, "e": 2481, "s": 2459, "text": "Inside a PL/SQL block" }, { "code": null, "e": 2715, "s": 2481, "text": "At the schema level, subprogram is a standalone subprogram. It is created with the CREATE PROCEDURE or the CREATE FUNCTION statement. It is stored in the database and can be deleted with the DROP PROCEDURE or DROP FUNCTION statement." }, { "code": null, "e": 2954, "s": 2715, "text": "A subprogram created inside a package is a packaged subprogram. It is stored in the database and can be deleted only when the package is deleted with the DROP PACKAGE statement. We will discuss packages in the chapter 'PL/SQL - Packages'." }, { "code": null, "e": 3086, "s": 2954, "text": "PL/SQL subprograms are named PL/SQL blocks that can be invoked with a set of parameters. PL/SQL provides two kinds of subprograms −" }, { "code": null, "e": 3182, "s": 3086, "text": "Functions − These subprograms return a single value; mainly used to compute and return a value." }, { "code": null, "e": 3278, "s": 3182, "text": "Functions − These subprograms return a single value; mainly used to compute and return a value." }, { "code": null, "e": 3375, "s": 3278, "text": "Procedures − These subprograms do not return a value directly; mainly used to perform an action." }, { "code": null, "e": 3472, "s": 3375, "text": "Procedures − These subprograms do not return a value directly; mainly used to perform an action." }, { "code": null, "e": 3597, "s": 3472, "text": "This chapter is going to cover important aspects of a PL/SQL procedure. We will discuss PL/SQL function in the next chapter." }, { "code": null, "e": 3758, "s": 3597, "text": "Each PL/SQL subprogram has a name, and may also have a parameter list. Like anonymous PL/SQL blocks, the named blocks will also have the following three parts −" }, { "code": null, "e": 3775, "s": 3758, "text": "Declarative Part" }, { "code": null, "e": 4089, "s": 3775, "text": "It is an optional part. However, the declarative part for a subprogram does not start with the DECLARE keyword. It contains declarations of types, cursors, constants, variables, exceptions, and nested subprograms. These items are local to the subprogram and cease to exist when the subprogram completes execution." }, { "code": null, "e": 4105, "s": 4089, "text": "Executable Part" }, { "code": null, "e": 4190, "s": 4105, "text": "This is a mandatory part and contains statements that perform the designated action." }, { "code": null, "e": 4209, "s": 4190, "text": "Exception-handling" }, { "code": null, "e": 4292, "s": 4209, "text": "This is again an optional part. It contains the code that handles run-time errors." }, { "code": null, "e": 4447, "s": 4292, "text": "A procedure is created with the CREATE OR REPLACE PROCEDURE statement. The simplified syntax for the CREATE OR REPLACE PROCEDURE statement is as follows −" }, { "code": null, "e": 4607, "s": 4447, "text": "CREATE [OR REPLACE] PROCEDURE procedure_name \n[(parameter_name [IN | OUT | IN OUT] type [, ...])] \n{IS | AS} \nBEGIN \n < procedure_body > \nEND procedure_name; " }, { "code": null, "e": 4614, "s": 4607, "text": "Where," }, { "code": null, "e": 4666, "s": 4614, "text": "procedure-name specifies the name of the procedure." }, { "code": null, "e": 4718, "s": 4666, "text": "procedure-name specifies the name of the procedure." }, { "code": null, "e": 4788, "s": 4718, "text": "[OR REPLACE] option allows the modification of an existing procedure." }, { "code": null, "e": 4858, "s": 4788, "text": "[OR REPLACE] option allows the modification of an existing procedure." }, { "code": null, "e": 5087, "s": 4858, "text": "The optional parameter list contains name, mode and types of the parameters. IN represents the value that will be passed from outside and OUT represents the parameter that will be used to return a value outside of the procedure." }, { "code": null, "e": 5316, "s": 5087, "text": "The optional parameter list contains name, mode and types of the parameters. IN represents the value that will be passed from outside and OUT represents the parameter that will be used to return a value outside of the procedure." }, { "code": null, "e": 5361, "s": 5316, "text": "procedure-body contains the executable part." }, { "code": null, "e": 5406, "s": 5361, "text": "procedure-body contains the executable part." }, { "code": null, "e": 5492, "s": 5406, "text": "The AS keyword is used instead of the IS keyword for creating a standalone procedure." }, { "code": null, "e": 5578, "s": 5492, "text": "The AS keyword is used instead of the IS keyword for creating a standalone procedure." }, { "code": null, "e": 5696, "s": 5578, "text": "The following example creates a simple procedure that displays the string 'Hello World!' on the screen when executed." }, { "code": null, "e": 5796, "s": 5696, "text": "CREATE OR REPLACE PROCEDURE greetings \nAS \nBEGIN \n dbms_output.put_line('Hello World!'); \nEND; \n/" }, { "code": null, "e": 5889, "s": 5796, "text": "When the above code is executed using the SQL prompt, it will produce the following result −" }, { "code": null, "e": 5909, "s": 5889, "text": "Procedure created.\n" }, { "code": null, "e": 5960, "s": 5909, "text": "A standalone procedure can be called in two ways −" }, { "code": null, "e": 5986, "s": 5960, "text": "Using the EXECUTE keyword" }, { "code": null, "e": 6012, "s": 5986, "text": "Using the EXECUTE keyword" }, { "code": null, "e": 6066, "s": 6012, "text": "Calling the name of the procedure from a PL/SQL block" }, { "code": null, "e": 6120, "s": 6066, "text": "Calling the name of the procedure from a PL/SQL block" }, { "code": null, "e": 6202, "s": 6120, "text": "The above procedure named 'greetings' can be called with the EXECUTE keyword as −" }, { "code": null, "e": 6222, "s": 6202, "text": "EXECUTE greetings;\n" }, { "code": null, "e": 6252, "s": 6222, "text": "The above call will display −" }, { "code": null, "e": 6307, "s": 6252, "text": "Hello World\n\nPL/SQL procedure successfully completed.\n" }, { "code": null, "e": 6368, "s": 6307, "text": "The procedure can also be called from another PL/SQL block −" }, { "code": null, "e": 6398, "s": 6368, "text": "BEGIN \n greetings; \nEND; \n/" }, { "code": null, "e": 6428, "s": 6398, "text": "The above call will display −" }, { "code": null, "e": 6486, "s": 6428, "text": "Hello World \n\nPL/SQL procedure successfully completed. \n" }, { "code": null, "e": 6592, "s": 6486, "text": "A standalone procedure is deleted with the DROP PROCEDURE statement. Syntax for deleting a procedure is −" }, { "code": null, "e": 6625, "s": 6592, "text": "DROP PROCEDURE procedure-name; \n" }, { "code": null, "e": 6697, "s": 6625, "text": "You can drop the greetings procedure by using the following statement −" }, { "code": null, "e": 6725, "s": 6697, "text": "DROP PROCEDURE greetings; \n" }, { "code": null, "e": 6799, "s": 6725, "text": "The following table lists out the parameter modes in PL/SQL subprograms −" }, { "code": null, "e": 6802, "s": 6799, "text": "IN" }, { "code": null, "e": 7261, "s": 6802, "text": "An IN parameter lets you pass a value to the subprogram. It is a read-only parameter. Inside the subprogram, an IN parameter acts like a constant. It cannot be assigned a value. You can pass a constant, literal, initialized variable, or expression as an IN parameter. You can also initialize it to a default value; however, in that case, it is omitted from the subprogram call. It is the default mode of parameter passing. Parameters are passed by reference." }, { "code": null, "e": 7265, "s": 7261, "text": "OUT" }, { "code": null, "e": 7518, "s": 7265, "text": "An OUT parameter returns a value to the calling program. Inside the subprogram, an OUT parameter acts like a variable. You can change its value and reference the value after assigning it. The actual parameter must be variable and it is passed by value." }, { "code": null, "e": 7525, "s": 7518, "text": "IN OUT" }, { "code": null, "e": 7683, "s": 7525, "text": "An IN OUT parameter passes an initial value to a subprogram and returns an updated value to the caller. It can be assigned a value and the value can be read." }, { "code": null, "e": 7881, "s": 7683, "text": "The actual parameter corresponding to an IN OUT formal parameter must be a variable, not a constant or an expression. Formal parameter must be assigned a value. Actual parameter is passed by value." }, { "code": null, "e": 8035, "s": 7881, "text": "This program finds the minimum of two values. Here, the procedure takes two numbers using the IN mode and returns their minimum using the OUT parameters." }, { "code": null, "e": 8348, "s": 8035, "text": "DECLARE \n a number; \n b number; \n c number;\nPROCEDURE findMin(x IN number, y IN number, z OUT number) IS \nBEGIN \n IF x < y THEN \n z:= x; \n ELSE \n z:= y; \n END IF; \nEND; \nBEGIN \n a:= 23; \n b:= 45; \n findMin(a, b, c); \n dbms_output.put_line(' Minimum of (23, 45) : ' || c); \nEND; \n/" }, { "code": null, "e": 8434, "s": 8348, "text": "When the above code is executed at the SQL prompt, it produces the following result −" }, { "code": null, "e": 8505, "s": 8434, "text": "Minimum of (23, 45) : 23 \n\nPL/SQL procedure successfully completed. \n" }, { "code": null, "e": 8671, "s": 8505, "text": "This procedure computes the square of value of a passed value. This example shows how we can use the same parameter to accept a value and then return another result." }, { "code": null, "e": 8861, "s": 8671, "text": "DECLARE \n a number; \nPROCEDURE squareNum(x IN OUT number) IS \nBEGIN \n x := x * x; \nEND; \nBEGIN \n a:= 23; \n squareNum(a); \n dbms_output.put_line(' Square of (23): ' || a); \nEND; \n/" }, { "code": null, "e": 8947, "s": 8861, "text": "When the above code is executed at the SQL prompt, it produces the following result −" }, { "code": null, "e": 9011, "s": 8947, "text": "Square of (23): 529 \n\nPL/SQL procedure successfully completed.\n" }, { "code": null, "e": 9059, "s": 9011, "text": "Actual parameters can be passed in three ways −" }, { "code": null, "e": 9079, "s": 9059, "text": "Positional notation" }, { "code": null, "e": 9094, "s": 9079, "text": "Named notation" }, { "code": null, "e": 9109, "s": 9094, "text": "Mixed notation" }, { "code": null, "e": 9165, "s": 9109, "text": "In positional notation, you can call the procedure as −" }, { "code": null, "e": 9187, "s": 9165, "text": "findMin(a, b, c, d);\n" }, { "code": null, "e": 9475, "s": 9187, "text": "In positional notation, the first actual parameter is substituted for the first formal parameter; the second actual parameter is substituted for the second formal parameter, and so on. So, a is substituted for x, b is substituted for y, c is substituted for z and d is substituted for m." }, { "code": null, "e": 9634, "s": 9475, "text": "In named notation, the actual parameter is associated with the formal parameter using the arrow symbol ( => ). The procedure call will be like the following −" }, { "code": null, "e": 9676, "s": 9634, "text": "findMin(x => a, y => b, z => c, m => d);\n" }, { "code": null, "e": 9809, "s": 9676, "text": "In mixed notation, you can mix both notations in procedure call; however, the positional notation should precede the named notation." }, { "code": null, "e": 9839, "s": 9809, "text": "The following call is legal −" }, { "code": null, "e": 9866, "s": 9839, "text": "findMin(a, b, c, m => d);\n" }, { "code": null, "e": 9894, "s": 9866, "text": "However, this is not legal:" }, { "code": null, "e": 9922, "s": 9894, "text": "findMin(x => a, b, c, d); \n" }, { "code": null, "e": 9929, "s": 9922, "text": " Print" }, { "code": null, "e": 9940, "s": 9929, "text": " Add Notes" } ]
What is C unconditional jump statements?
C programming language allows jumping from one statement to another. It also supports break, continue, return and go to jump statements. It is a keyword which is used to terminate the loop (or) exit from the block. The control jumps to next statement after the loop (or) block. break is used with for, while, do-while and switch statement. When break is used in nested loops then, only the innermost loop is terminated. The syntax for break statement is as follows − Following is the C program for break statement − Live Demo #include<stdio.h> main( ){ int i; for (i=1; i<=5; i++){ printf ("%d", i); if (i==3) break; } } When the above program is executed, it produces the following output − 1 2 3 The syntax for the continue statement is as follows − Following is the C program for the continue statement − #include<stdio.h> main( ){ int i; for (i=1; i<=5; i++){ if (i==2) continue; printf("%d", i) } } When the above program is executed, it produces the following output − 1 2 3 4 5 It terminates the execution of function and returns the control of calling function The syntax for return statement is as follows − return[expression/value]; Following is the C program for the return statement − Live Demo #include<stdio.h> main(){ int a,b,c; printf("enter a and b value:"); scanf("%d%d",&a,&b); c=a*b; return(c); } When the above program is executed, it produces the following output − enter a and b value:2 4 Process returned 8 (0x8) It is used after the normal sequence of program execution by transferring the control to some other part of program. The syntax for the goto statement is as follows − Following is the C program for the goto statement − Live Demo #include<stdio.h> main( ) { printf("Hello"); goto l1; printf("How are"); l1: printf("you"); } When the above program is executed, it produces the following output − Hello you
[ { "code": null, "e": 1199, "s": 1062, "text": "C programming language allows jumping from one statement to another. It also supports break, continue, return and go to jump statements." }, { "code": null, "e": 1277, "s": 1199, "text": "It is a keyword which is used to terminate the loop (or) exit from the block." }, { "code": null, "e": 1340, "s": 1277, "text": "The control jumps to next statement after the loop (or) block." }, { "code": null, "e": 1402, "s": 1340, "text": "break is used with for, while, do-while and switch statement." }, { "code": null, "e": 1482, "s": 1402, "text": "When break is used in nested loops then, only the innermost loop is terminated." }, { "code": null, "e": 1529, "s": 1482, "text": "The syntax for break statement is as follows −" }, { "code": null, "e": 1578, "s": 1529, "text": "Following is the C program for break statement −" }, { "code": null, "e": 1589, "s": 1578, "text": " Live Demo" }, { "code": null, "e": 1711, "s": 1589, "text": "#include<stdio.h>\nmain( ){\n int i;\n for (i=1; i<=5; i++){\n printf (\"%d\", i);\n if (i==3)\n break;\n }\n}" }, { "code": null, "e": 1782, "s": 1711, "text": "When the above program is executed, it produces the following output −" }, { "code": null, "e": 1788, "s": 1782, "text": "1 2 3" }, { "code": null, "e": 1842, "s": 1788, "text": "The syntax for the continue statement is as follows −" }, { "code": null, "e": 1898, "s": 1842, "text": "Following is the C program for the continue statement −" }, { "code": null, "e": 2021, "s": 1898, "text": "#include<stdio.h>\nmain( ){\n int i;\n for (i=1; i<=5; i++){\n if (i==2)\n continue;\n printf(\"%d\", i)\n }\n}" }, { "code": null, "e": 2092, "s": 2021, "text": "When the above program is executed, it produces the following output −" }, { "code": null, "e": 2102, "s": 2092, "text": "1 2 3 4 5" }, { "code": null, "e": 2186, "s": 2102, "text": "It terminates the execution of function and returns the control of calling function" }, { "code": null, "e": 2234, "s": 2186, "text": "The syntax for return statement is as follows −" }, { "code": null, "e": 2260, "s": 2234, "text": "return[expression/value];" }, { "code": null, "e": 2314, "s": 2260, "text": "Following is the C program for the return statement −" }, { "code": null, "e": 2325, "s": 2314, "text": " Live Demo" }, { "code": null, "e": 2450, "s": 2325, "text": "#include<stdio.h>\nmain(){\n int a,b,c;\n printf(\"enter a and b value:\");\n scanf(\"%d%d\",&a,&b);\n c=a*b;\n return(c);\n}" }, { "code": null, "e": 2521, "s": 2450, "text": "When the above program is executed, it produces the following output −" }, { "code": null, "e": 2570, "s": 2521, "text": "enter a and b value:2 4\nProcess returned 8 (0x8)" }, { "code": null, "e": 2687, "s": 2570, "text": "It is used after the normal sequence of program execution by transferring the control to some other part of program." }, { "code": null, "e": 2737, "s": 2687, "text": "The syntax for the goto statement is as follows −" }, { "code": null, "e": 2789, "s": 2737, "text": "Following is the C program for the goto statement −" }, { "code": null, "e": 2800, "s": 2789, "text": " Live Demo" }, { "code": null, "e": 2906, "s": 2800, "text": "#include<stdio.h>\nmain( ) {\n printf(\"Hello\");\n goto l1;\n printf(\"How are\");\n l1: printf(\"you\");\n}" }, { "code": null, "e": 2977, "s": 2906, "text": "When the above program is executed, it produces the following output −" }, { "code": null, "e": 2987, "s": 2977, "text": "Hello you" } ]
Java.net.URLEncoder class in Java - GeeksforGeeks
16 Jun, 2017 This class is a utility class for HTML form encoding. Encoding makes the form of URL more reliable and secure. When the user request is triggered by a get method, the form parameters and their values are appended at the end of URL after a ‘?’ sign. The problem arises when special characters are used for their values. In general case, HTML handles the encoding part and automatically processes the special characters and convert them to special characters for smooth handling of all the operations. However it is not a good practice to rely solely on HTML features and thus java provides this class to explicitly encode the URLs.Following rules are used when encoding a string: Alphanumeric characters and certain special characters such as ‘*‘, ‘_‘, ‘–‘ and ‘.‘ remains unchanged.Spaces are converted into ‘+‘ signs.All other characters are encoded by one or more bytes using the encoding scheme specified. They are converted in a three character string of the form %xy, where xy represents the hexadecimal representation of the encoding character. W3C recommends using “UTF-8” for encoding purposes. Alphanumeric characters and certain special characters such as ‘*‘, ‘_‘, ‘–‘ and ‘.‘ remains unchanged. Spaces are converted into ‘+‘ signs. All other characters are encoded by one or more bytes using the encoding scheme specified. They are converted in a three character string of the form %xy, where xy represents the hexadecimal representation of the encoding character. W3C recommends using “UTF-8” for encoding purposes. For example, if we have the parameter value which contains special characters and spaces as u@geeks for geeks If the encoding used is UTF-8 which is most common used, the @ sign will be converted into %40 and spaces would be converted to + signs and our encoded string will look like- u%40geeks+for+geeks Methods : encode() : This is one and only method provided by this class. It as the name suggests returns an encoded string for the specified string. One method, which is now deprecated has only one parameter, the string to be encoded. It doesn’t let you specify the encoding to be used and uses the platform default encoding. Another version allows the specification of the encoding to be used, and thus is widely used.Syntax :public static String encode(String s) - @Deprecated Parameters : s : String to be encoded Syntax :public static String encode(String s, String enc) throws UnsupportedEncodingException Parameters : s : string to be encoded enc : encoding to be used Throws : UnsupportedEncodingException : If the specified encoding is not used encode() : This is one and only method provided by this class. It as the name suggests returns an encoded string for the specified string. One method, which is now deprecated has only one parameter, the string to be encoded. It doesn’t let you specify the encoding to be used and uses the platform default encoding. Another version allows the specification of the encoding to be used, and thus is widely used.Syntax :public static String encode(String s) - @Deprecated Parameters : s : String to be encoded Syntax :public static String encode(String s, String enc) throws UnsupportedEncodingException Parameters : s : string to be encoded enc : encoding to be used Throws : UnsupportedEncodingException : If the specified encoding is not used Syntax :public static String encode(String s) - @Deprecated Parameters : s : String to be encoded Syntax :public static String encode(String s, String enc) throws UnsupportedEncodingException Parameters : s : string to be encoded enc : encoding to be used Throws : UnsupportedEncodingException : If the specified encoding is not used Java Implementation : // Java program to show encode() method of // URLEncoder classimport java.io.UnsupportedEncodingException;import java.net.MalformedURLException;import java.net.URL;import java.net.URLEncoder; public class UrlEncoder { public static void main(String[] args) throws MalformedURLException, UnsupportedEncodingException { // base URL String baseurl = "https://www.geeksforgeeks.org/?q="; // String to be encoded String query = "u@geeks for geeks"; System.out.println("URL without encoding :"); URL url = new URL(baseurl + query); System.out.println(url); // encode() method System.out.println("URL after encoding :"); url = new URL(baseurl + URLEncoder.encode(query, "UTF-8")); System.out.println(url); } } Output : URL without encoding : https://www.geeksforgeeks.org/?q=u@geeks for geeks URL after encoding : https://www.geeksforgeeks.org/?q=u%40geeks+for+geeks References :Official Java DocumentationThis article is contributed by Rishabh Mahrsee. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Java-Networking Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Functional Interfaces in Java Stream In Java Constructors in Java Different ways of Reading a text file in Java Exceptions in Java Generics in Java Comparator Interface in Java with Examples Strings in Java Difference between Abstract Class and Interface in Java How to remove an element from ArrayList in Java?
[ { "code": null, "e": 23581, "s": 23553, "text": "\n16 Jun, 2017" }, { "code": null, "e": 24260, "s": 23581, "text": "This class is a utility class for HTML form encoding. Encoding makes the form of URL more reliable and secure. When the user request is triggered by a get method, the form parameters and their values are appended at the end of URL after a ‘?’ sign. The problem arises when special characters are used for their values. In general case, HTML handles the encoding part and automatically processes the special characters and convert them to special characters for smooth handling of all the operations. However it is not a good practice to rely solely on HTML features and thus java provides this class to explicitly encode the URLs.Following rules are used when encoding a string:" }, { "code": null, "e": 24684, "s": 24260, "text": "Alphanumeric characters and certain special characters such as ‘*‘, ‘_‘, ‘–‘ and ‘.‘ remains unchanged.Spaces are converted into ‘+‘ signs.All other characters are encoded by one or more bytes using the encoding scheme specified. They are converted in a three character string of the form %xy, where xy represents the hexadecimal representation of the encoding character. W3C recommends using “UTF-8” for encoding purposes." }, { "code": null, "e": 24788, "s": 24684, "text": "Alphanumeric characters and certain special characters such as ‘*‘, ‘_‘, ‘–‘ and ‘.‘ remains unchanged." }, { "code": null, "e": 24825, "s": 24788, "text": "Spaces are converted into ‘+‘ signs." }, { "code": null, "e": 25110, "s": 24825, "text": "All other characters are encoded by one or more bytes using the encoding scheme specified. They are converted in a three character string of the form %xy, where xy represents the hexadecimal representation of the encoding character. W3C recommends using “UTF-8” for encoding purposes." }, { "code": null, "e": 25202, "s": 25110, "text": "For example, if we have the parameter value which contains special characters and spaces as" }, { "code": null, "e": 25220, "s": 25202, "text": "u@geeks for geeks" }, { "code": null, "e": 25395, "s": 25220, "text": "If the encoding used is UTF-8 which is most common used, the @ sign will be converted into %40 and spaces would be converted to + signs and our encoded string will look like-" }, { "code": null, "e": 25415, "s": 25395, "text": "u%40geeks+for+geeks" }, { "code": null, "e": 25425, "s": 25415, "text": "Methods :" }, { "code": null, "e": 26203, "s": 25425, "text": "encode() : This is one and only method provided by this class. It as the name suggests returns an encoded string for the specified string. One method, which is now deprecated has only one parameter, the string to be encoded. It doesn’t let you specify the encoding to be used and uses the platform default encoding. Another version allows the specification of the encoding to be used, and thus is widely used.Syntax :public static String encode(String s) - @Deprecated\nParameters :\ns : String to be encoded\nSyntax :public static String encode(String s,\n String enc)\n throws UnsupportedEncodingException\nParameters : \ns : string to be encoded\nenc : encoding to be used\nThrows :\nUnsupportedEncodingException : If the specified encoding is not used\n" }, { "code": null, "e": 26981, "s": 26203, "text": "encode() : This is one and only method provided by this class. It as the name suggests returns an encoded string for the specified string. One method, which is now deprecated has only one parameter, the string to be encoded. It doesn’t let you specify the encoding to be used and uses the platform default encoding. Another version allows the specification of the encoding to be used, and thus is widely used.Syntax :public static String encode(String s) - @Deprecated\nParameters :\ns : String to be encoded\nSyntax :public static String encode(String s,\n String enc)\n throws UnsupportedEncodingException\nParameters : \ns : string to be encoded\nenc : encoding to be used\nThrows :\nUnsupportedEncodingException : If the specified encoding is not used\n" }, { "code": null, "e": 27080, "s": 26981, "text": "Syntax :public static String encode(String s) - @Deprecated\nParameters :\ns : String to be encoded\n" }, { "code": null, "e": 27351, "s": 27080, "text": "Syntax :public static String encode(String s,\n String enc)\n throws UnsupportedEncodingException\nParameters : \ns : string to be encoded\nenc : encoding to be used\nThrows :\nUnsupportedEncodingException : If the specified encoding is not used\n" }, { "code": null, "e": 27373, "s": 27351, "text": "Java Implementation :" }, { "code": "// Java program to show encode() method of // URLEncoder classimport java.io.UnsupportedEncodingException;import java.net.MalformedURLException;import java.net.URL;import java.net.URLEncoder; public class UrlEncoder { public static void main(String[] args) throws MalformedURLException, UnsupportedEncodingException { // base URL String baseurl = \"https://www.geeksforgeeks.org/?q=\"; // String to be encoded String query = \"u@geeks for geeks\"; System.out.println(\"URL without encoding :\"); URL url = new URL(baseurl + query); System.out.println(url); // encode() method System.out.println(\"URL after encoding :\"); url = new URL(baseurl + URLEncoder.encode(query, \"UTF-8\")); System.out.println(url); } }", "e": 28206, "s": 27373, "text": null }, { "code": null, "e": 28215, "s": 28206, "text": "Output :" }, { "code": null, "e": 28363, "s": 28215, "text": "URL without encoding :\nhttps://www.geeksforgeeks.org/?q=u@geeks for geeks\nURL after encoding :\nhttps://www.geeksforgeeks.org/?q=u%40geeks+for+geeks" }, { "code": null, "e": 28705, "s": 28363, "text": "References :Official Java DocumentationThis article is contributed by Rishabh Mahrsee. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 28830, "s": 28705, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 28846, "s": 28830, "text": "Java-Networking" }, { "code": null, "e": 28851, "s": 28846, "text": "Java" }, { "code": null, "e": 28856, "s": 28851, "text": "Java" }, { "code": null, "e": 28954, "s": 28856, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28963, "s": 28954, "text": "Comments" }, { "code": null, "e": 28976, "s": 28963, "text": "Old Comments" }, { "code": null, "e": 29006, "s": 28976, "text": "Functional Interfaces in Java" }, { "code": null, "e": 29021, "s": 29006, "text": "Stream In Java" }, { "code": null, "e": 29042, "s": 29021, "text": "Constructors in Java" }, { "code": null, "e": 29088, "s": 29042, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 29107, "s": 29088, "text": "Exceptions in Java" }, { "code": null, "e": 29124, "s": 29107, "text": "Generics in Java" }, { "code": null, "e": 29167, "s": 29124, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 29183, "s": 29167, "text": "Strings in Java" }, { "code": null, "e": 29239, "s": 29183, "text": "Difference between Abstract Class and Interface in Java" } ]
How to get the Daily News using Python | by Mukundan Sankar | Towards Data Science
Did you ever wonder how you can get the latest news programmatically? News API is one such module in Python which helps you in this. It has data from about 120 sources including Reuters, BBC News, ABC News, ESPN. newsapi.org Firstly, get the API key from NewsAPI to begin extracting news articles. You can see more on how to get one here. newsapi.org Import the relevant libraries. from newsapi import NewsApiClient This is for the NewsAPI import. Now initializing a variable for the NewsAPI newsapi = NewsApiClient(api_key=api_key)from pandas.io.json import json_normalizeimport pandas as pd We will use Beautiful Soup package in Python to help clean up the HTML tags from the data. from bs4 import BeautifulSoup Now, let’s see the practical use. Latest News To get the latest news: def top_headlines(): country=input("Which country are you interested in?") category=input("""Which category are you interested in? \nHere are the categories to choose from:\nbusiness\nentertainment \ngeneral\nhealth\nscience\ntechnology""") top_headlines =newsapi.get_top_headlines(category=category, language='en',country=country) top_headlines=json_normalize(top_headlines['articles']) newdf=top_headlines[["title","url"]] dic=newdf.set_index('title')['url'].to_dict() Let’s talk about what this piece of code does. I have written a function called top_headlines. I take in two inputs, country and category. When I supply an input to the country you would have to write it in a specific format. The country parameter in the News API follows this code system: en.wikipedia.org USA is “us”, the United Kingdom is “gb”, India is “in”. For symbols of other countries refer to the link above. In the code itself, I have mentioned how we can supply an input to the category parameter. “general” for general news, “sports” for sports news, and so on. Using get_top_headlines you can get the latest news. Now, the output is in JSON so I wanted to convert it into a Dataframe. So, I used the json_normalize method which I imported earlier in this tutorial. I am then storing that into a new Dataframe with only a few select columns from the list of columns returned in the JSON output. Then I decided that I want to make sense of this news information. I took a used case to see how the opinion of the media changes over time for a particular timeframe. News API has a paid version which offers up to 2 years worth of information. In the free version, you can retrieve up to 30 days worth of news which is the timeframe that I chose as well. Search for a particular topic To do this analysis, we need to use this method: get_everything(query,language,sort_by='relevancy',from_param,to) What this means is it gets everything related to a particular search query. Let’s say you want to try to get every piece of information regarding the hottest topic in the world today, COVID-19 or Coronavirus, you would specify so in the “query” parameter in the above function. The “from_param” parameter and “to” parameter in the above function are the date parameters. It is asking you to specify the timeframe for which you want to get results for the search query. Since I mentioned, I want to get all results for a period of 30 days which is the maximum allowed timeframe for the free version, I will specify the from_param as the day 30 days before today’s date. However, I need to write this in a loop so that I can ensure I am getting every day. So, I built a date function first which helps me with this. import datetimefrom datetime import datetime, timedeltadef date(base): date_list=[] yr=datetime.today().year if (yr%400)==0 or ((yr%100!=0) and (yr%4==0)): numdays=366 date_list.append([base - timedelta(days=x) for x in range(366)]) else: numdays=365 date_list.append([base - timedelta(days=x) for x in range(365)]) newlist=[] for i in date_list: for j in sorted(i): newlist.append(j) return newlist def last_30(base): date_list=[base - timedelta(days=x) for x in range(30)] return sorted(date_list) def from_dt(x): from_dt=[] for i in range(len(x)): from_dt.append(last_30(datetime.today())[i-1].date()) return from_dt def to_dt(x): to_dt=[] for i in range(len(x)): to_dt.append(last_30(datetime.today())[i].date()) return to_dtfrom_list=from_dt(last_30(datetime.today()))to_list=to_dt(last_30(datetime.today())) The first date function (date) that I have built is a more general date function where I want to use it for a large timeframe if needed. I am getting a list of all days using the first date function. I need only 30 days so I made sure to do that using last_30. This will give me a list of the last 30 days from the current day and time. Moving on to the from_dt function, it is specifically for the from_param for the get_everything function mentioned above. This is the start of the timeframe for which you need all the news articles and to_dt is the end date. I now have two separate lists for start and end date respectively. Now we will work on the query parameter which is the search term for the get_everything function. def func(query): newd={} newdf=pd.DataFrame() for (from_dt,to_dt) in zip(from_list,to_list): all_articles = newsapi.get_everything(q=query,language='en', sort_by='relevancy',from_param=from_dt,to=to_dt) d=json_normalize(all_articles['articles']) newdf=d[["url","publishedAt","source.name","author"]] dic=newdf.set_index(["source.name","publishedAt","author"]) ["url"].to_dict() for (k,v) in dic.items(): page = requests.get(v) html = page.content soup = BeautifulSoup(html, "lxml") text = soup.get_text() d2=soup.find_all("p") newd[k]=re.sub(r'<.+?>',r'',str(d2)) return newd Looping through the zipped version of the from and to lists for the dates, we get a list of all articles for the 30-day timeframe. The reason I chose to loop this is so that I can do analysis for every single day. I then store it in a data frame. I then get the relevant columns and store them back in a dictionary. I want to parse the content in the news URL so that I get the content only from the articles. I used the BeautifulSoup package in Python here to parse the content and get relevant <p> tags where the information resides. Since we are primarily focused on text data here, we need information between these paragraph tags. You can find more information on BeautifulSoup here: www.crummy.com Once we have cleaner data, we can now proceed towards the Wordclouds to analyze a pattern. News Analysis using WordCloud Now, we move on to the Wordcloud. The part where we can make sense of the data from the news. What are some of the commonly occurring patterns? def wordcld(dictionary): newd={} for (k,v) in dictionary.items(): if v!='[]': wordcloud = WordCloud().generate(str(dictionary[k])) fig, axes= plt.subplots(figsize=(20,12),clear=True) plt.imshow(wordcloud, interpolation='bilinear') plt.show() else: print(str(k[0])+"_"+str(k[1][5:10])+"_"+str(k[1][11:13]) +"_"+str(k[1][14:16]) +"_"+str(k[1][17:19])+"_"+str(k[2])) print("Wordcloud Not applicable")dic=func("Indian Economy")wordcld(dic) I am searching for some commonly occurring words for the Indian Economy and I get the below image. The image I got is for one day. The code I have above will get you results for 30 days. Try this out and feel free to let me know if you have any questions. As a next step, you can send this as a text message/email notification to yourself using Twilio API/SendGrid Email API which I will cover in another tutorial or you could see some of the existing ones like this: medium.com sendgrid.com To summarize: Feel free to comment here or send me an email if you have any questions. You can also see this code on GitHub: https://github.com/mukund14/News/tree/news_api_Python
[ { "code": null, "e": 384, "s": 171, "text": "Did you ever wonder how you can get the latest news programmatically? News API is one such module in Python which helps you in this. It has data from about 120 sources including Reuters, BBC News, ABC News, ESPN." }, { "code": null, "e": 396, "s": 384, "text": "newsapi.org" }, { "code": null, "e": 510, "s": 396, "text": "Firstly, get the API key from NewsAPI to begin extracting news articles. You can see more on how to get one here." }, { "code": null, "e": 522, "s": 510, "text": "newsapi.org" }, { "code": null, "e": 553, "s": 522, "text": "Import the relevant libraries." }, { "code": null, "e": 587, "s": 553, "text": "from newsapi import NewsApiClient" }, { "code": null, "e": 663, "s": 587, "text": "This is for the NewsAPI import. Now initializing a variable for the NewsAPI" }, { "code": null, "e": 764, "s": 663, "text": "newsapi = NewsApiClient(api_key=api_key)from pandas.io.json import json_normalizeimport pandas as pd" }, { "code": null, "e": 855, "s": 764, "text": "We will use Beautiful Soup package in Python to help clean up the HTML tags from the data." }, { "code": null, "e": 885, "s": 855, "text": "from bs4 import BeautifulSoup" }, { "code": null, "e": 919, "s": 885, "text": "Now, let’s see the practical use." }, { "code": null, "e": 931, "s": 919, "text": "Latest News" }, { "code": null, "e": 955, "s": 931, "text": "To get the latest news:" }, { "code": null, "e": 1473, "s": 955, "text": "def top_headlines(): country=input(\"Which country are you interested in?\") category=input(\"\"\"Which category are you interested in? \\nHere are the categories to choose from:\\nbusiness\\nentertainment \\ngeneral\\nhealth\\nscience\\ntechnology\"\"\") top_headlines =newsapi.get_top_headlines(category=category, language='en',country=country) top_headlines=json_normalize(top_headlines['articles']) newdf=top_headlines[[\"title\",\"url\"]] dic=newdf.set_index('title')['url'].to_dict()" }, { "code": null, "e": 1763, "s": 1473, "text": "Let’s talk about what this piece of code does. I have written a function called top_headlines. I take in two inputs, country and category. When I supply an input to the country you would have to write it in a specific format. The country parameter in the News API follows this code system:" }, { "code": null, "e": 1780, "s": 1763, "text": "en.wikipedia.org" }, { "code": null, "e": 1892, "s": 1780, "text": "USA is “us”, the United Kingdom is “gb”, India is “in”. For symbols of other countries refer to the link above." }, { "code": null, "e": 2048, "s": 1892, "text": "In the code itself, I have mentioned how we can supply an input to the category parameter. “general” for general news, “sports” for sports news, and so on." }, { "code": null, "e": 2381, "s": 2048, "text": "Using get_top_headlines you can get the latest news. Now, the output is in JSON so I wanted to convert it into a Dataframe. So, I used the json_normalize method which I imported earlier in this tutorial. I am then storing that into a new Dataframe with only a few select columns from the list of columns returned in the JSON output." }, { "code": null, "e": 2737, "s": 2381, "text": "Then I decided that I want to make sense of this news information. I took a used case to see how the opinion of the media changes over time for a particular timeframe. News API has a paid version which offers up to 2 years worth of information. In the free version, you can retrieve up to 30 days worth of news which is the timeframe that I chose as well." }, { "code": null, "e": 2767, "s": 2737, "text": "Search for a particular topic" }, { "code": null, "e": 2816, "s": 2767, "text": "To do this analysis, we need to use this method:" }, { "code": null, "e": 2881, "s": 2816, "text": "get_everything(query,language,sort_by='relevancy',from_param,to)" }, { "code": null, "e": 3159, "s": 2881, "text": "What this means is it gets everything related to a particular search query. Let’s say you want to try to get every piece of information regarding the hottest topic in the world today, COVID-19 or Coronavirus, you would specify so in the “query” parameter in the above function." }, { "code": null, "e": 3635, "s": 3159, "text": "The “from_param” parameter and “to” parameter in the above function are the date parameters. It is asking you to specify the timeframe for which you want to get results for the search query. Since I mentioned, I want to get all results for a period of 30 days which is the maximum allowed timeframe for the free version, I will specify the from_param as the day 30 days before today’s date. However, I need to write this in a loop so that I can ensure I am getting every day." }, { "code": null, "e": 3695, "s": 3635, "text": "So, I built a date function first which helps me with this." }, { "code": null, "e": 4801, "s": 3695, "text": "import datetimefrom datetime import datetime, timedeltadef date(base): date_list=[] yr=datetime.today().year if (yr%400)==0 or ((yr%100!=0) and (yr%4==0)): numdays=366 date_list.append([base - timedelta(days=x) for x in range(366)]) else: numdays=365 date_list.append([base - timedelta(days=x) for x in range(365)]) newlist=[] for i in date_list: for j in sorted(i): newlist.append(j) return newlist def last_30(base): date_list=[base - timedelta(days=x) for x in range(30)] return sorted(date_list) def from_dt(x): from_dt=[] for i in range(len(x)): from_dt.append(last_30(datetime.today())[i-1].date()) return from_dt def to_dt(x): to_dt=[] for i in range(len(x)): to_dt.append(last_30(datetime.today())[i].date()) return to_dtfrom_list=from_dt(last_30(datetime.today()))to_list=to_dt(last_30(datetime.today()))" }, { "code": null, "e": 5363, "s": 4801, "text": "The first date function (date) that I have built is a more general date function where I want to use it for a large timeframe if needed. I am getting a list of all days using the first date function. I need only 30 days so I made sure to do that using last_30. This will give me a list of the last 30 days from the current day and time. Moving on to the from_dt function, it is specifically for the from_param for the get_everything function mentioned above. This is the start of the timeframe for which you need all the news articles and to_dt is the end date." }, { "code": null, "e": 5430, "s": 5363, "text": "I now have two separate lists for start and end date respectively." }, { "code": null, "e": 5528, "s": 5430, "text": "Now we will work on the query parameter which is the search term for the get_everything function." }, { "code": null, "e": 6366, "s": 5528, "text": "def func(query): newd={} newdf=pd.DataFrame() for (from_dt,to_dt) in zip(from_list,to_list): all_articles = newsapi.get_everything(q=query,language='en', sort_by='relevancy',from_param=from_dt,to=to_dt) d=json_normalize(all_articles['articles']) newdf=d[[\"url\",\"publishedAt\",\"source.name\",\"author\"]] dic=newdf.set_index([\"source.name\",\"publishedAt\",\"author\"]) [\"url\"].to_dict() for (k,v) in dic.items(): page = requests.get(v) html = page.content soup = BeautifulSoup(html, \"lxml\") text = soup.get_text() d2=soup.find_all(\"p\") newd[k]=re.sub(r'<.+?>',r'',str(d2)) return newd" }, { "code": null, "e": 7055, "s": 6366, "text": "Looping through the zipped version of the from and to lists for the dates, we get a list of all articles for the 30-day timeframe. The reason I chose to loop this is so that I can do analysis for every single day. I then store it in a data frame. I then get the relevant columns and store them back in a dictionary. I want to parse the content in the news URL so that I get the content only from the articles. I used the BeautifulSoup package in Python here to parse the content and get relevant <p> tags where the information resides. Since we are primarily focused on text data here, we need information between these paragraph tags. You can find more information on BeautifulSoup here:" }, { "code": null, "e": 7070, "s": 7055, "text": "www.crummy.com" }, { "code": null, "e": 7161, "s": 7070, "text": "Once we have cleaner data, we can now proceed towards the Wordclouds to analyze a pattern." }, { "code": null, "e": 7191, "s": 7161, "text": "News Analysis using WordCloud" }, { "code": null, "e": 7335, "s": 7191, "text": "Now, we move on to the Wordcloud. The part where we can make sense of the data from the news. What are some of the commonly occurring patterns?" }, { "code": null, "e": 7969, "s": 7335, "text": "def wordcld(dictionary): newd={} for (k,v) in dictionary.items(): if v!='[]': wordcloud = WordCloud().generate(str(dictionary[k])) fig, axes= plt.subplots(figsize=(20,12),clear=True) plt.imshow(wordcloud, interpolation='bilinear') plt.show() else: print(str(k[0])+\"_\"+str(k[1][5:10])+\"_\"+str(k[1][11:13]) +\"_\"+str(k[1][14:16]) +\"_\"+str(k[1][17:19])+\"_\"+str(k[2])) print(\"Wordcloud Not applicable\")dic=func(\"Indian Economy\")wordcld(dic)" }, { "code": null, "e": 8156, "s": 7969, "text": "I am searching for some commonly occurring words for the Indian Economy and I get the below image. The image I got is for one day. The code I have above will get you results for 30 days." }, { "code": null, "e": 8225, "s": 8156, "text": "Try this out and feel free to let me know if you have any questions." }, { "code": null, "e": 8437, "s": 8225, "text": "As a next step, you can send this as a text message/email notification to yourself using Twilio API/SendGrid Email API which I will cover in another tutorial or you could see some of the existing ones like this:" }, { "code": null, "e": 8448, "s": 8437, "text": "medium.com" }, { "code": null, "e": 8461, "s": 8448, "text": "sendgrid.com" }, { "code": null, "e": 8475, "s": 8461, "text": "To summarize:" } ]
Speed up your Pandas Processing with Swifter | by Cornellius Yudha Wijaya | Towards Data Science
As a Pythonist Data Scientist, your daily job would involve a lot of data processing and feature engineering using the Pandas package. From analyzing data to create a new feature to gain insight, forcing you to execute many different codes repeatedly. The problem is the bigger your data, the longer time to finish running each line of code. In this article, I want to show you a simple package to speed up your Pandas processing called Swifter. Let’s just get started. Swifter is a package that tries to efficiently apply any function to a Pandas Data Frame or Series object in the quickest available method. It is integrated with the Pandas object so that we would use this package only with a Pandas object such as Data Frame or Series. Let’s try to see Swifter in action. For preparation, we need to install the Swifter package. #Installing Swifter via Pippip install swifter#or via condaconda install -c conda-forge swifter In case you have not possessed the latest Pandas package, it is suggested to update the package into the newest version. This is because Pandas extension api used in the Swifter module is a recent addition to pandas. #Update the Pandas package via pippip install -U pandas#or via condaconda update pandas When all the required packages ready, we could proceed to try Swifter. In this article, I would use the Reddit comment dataset from Kaggle. From here, we import all the packages to our notebook and read the dataset from CSV as usual. #Import the packageimport pandas as pdimport swifter#read the datasetdf = pd.read_csv('r_dataisbeautiful_posts.csv') This is our dataset. Now, let’s say I want to multiply the score by two and subtract the score by one (This is just a random equation I used here). Then I would put it in another column. In this case, I could use the apply function from the Pandas object attribute. %time df['score_2_subs'] = df['score'].apply(lambda x: x/2 -1) The time to execute the function to each data takes around 42.9 ms for an apply attribute by Pandas. This time, we would use Swifter and see how much time it take to execute the function. #When we importing the Swifter package, it would integrated with Pandas package and we could use functional attribute from Pandas such as apply%time df['score_2_swift'] = df['score'].swifter.apply(lambda x: x/2 - 1) As we can see above, Swifter processes the data way faster compared to the normal Pandas apply function. From the documentation, it is stated that Swifter could apply function a hundred times faster than Pandas function. This, however, only applied if we are using a vectorized form of function. Let’s say I create a function that evaluates the num_comments and score variable. When the comment count is zero, I will double the score. While it’s not, the score would stay the same. Then I would create a new column based on that. def scoring_comment(x): if x['num_comments'] == 0: return x['score'] *2 else: return x['score']#Trying applying the function using Pandas apply%time df['score_comment'] = df[['score','num_comments']].apply(scoring_comment, axis =1) It takes around 3.96 seconds to execute the function. Let’s see the performance if we are using Swifter. %time df['score_comment_swift'] = df[['score', 'num_comments']].swifter.apply(scoring_comment, axis =1) As we can see above, it takes much longer using Swifter compared to the regular Pandas apply function. This is because Swifter with non-vectorized function would implement dask parallel processing, not relying on the Swifter processing itself. So, how is the performance if we change the function to the vectorized function? Let’s try it. Import numpy as np#Using np.where to implement vectorized functiondef scoring_comment_vectorized(x): return np.where(x['num_comments'] ==0, x['score']*2, x['score'])#Trying using the normal Pandas apply%time df['score_comment_vectorized'] = df[['score', 'num_comments']].apply(scoring_comment_vectorized, axis =1) It takes around 6.25 seconds using the normal apply function to execute our vectorized function. Let’s see the performance using Swifter. %time df['score_comment_vectorized_swift'] = df[['score', 'num_comments']].swifter.apply(scoring_comment_vectorized, axis =1) The execution time now takes only 11 ms with the vectorized function, which saves so much time compared to the normal apply function. This is why it is advisable to use the vectorized function when we are processing data with Swifter. If you want to keep track of the execution time that just happen, I will give you the overall summary in the table below. I just show you how Swifter could speed up your Pandas Data Processing. Swifter is works best when we use a vectorized function instead of a non-vectorized function. If you want to know more about the Swifter and the available API, you could check the documentation. If you are not subscribed as a Medium Member, please consider subscribing through my referral.
[ { "code": null, "e": 513, "s": 171, "text": "As a Pythonist Data Scientist, your daily job would involve a lot of data processing and feature engineering using the Pandas package. From analyzing data to create a new feature to gain insight, forcing you to execute many different codes repeatedly. The problem is the bigger your data, the longer time to finish running each line of code." }, { "code": null, "e": 641, "s": 513, "text": "In this article, I want to show you a simple package to speed up your Pandas processing called Swifter. Let’s just get started." }, { "code": null, "e": 911, "s": 641, "text": "Swifter is a package that tries to efficiently apply any function to a Pandas Data Frame or Series object in the quickest available method. It is integrated with the Pandas object so that we would use this package only with a Pandas object such as Data Frame or Series." }, { "code": null, "e": 1004, "s": 911, "text": "Let’s try to see Swifter in action. For preparation, we need to install the Swifter package." }, { "code": null, "e": 1100, "s": 1004, "text": "#Installing Swifter via Pippip install swifter#or via condaconda install -c conda-forge swifter" }, { "code": null, "e": 1317, "s": 1100, "text": "In case you have not possessed the latest Pandas package, it is suggested to update the package into the newest version. This is because Pandas extension api used in the Swifter module is a recent addition to pandas." }, { "code": null, "e": 1405, "s": 1317, "text": "#Update the Pandas package via pippip install -U pandas#or via condaconda update pandas" }, { "code": null, "e": 1639, "s": 1405, "text": "When all the required packages ready, we could proceed to try Swifter. In this article, I would use the Reddit comment dataset from Kaggle. From here, we import all the packages to our notebook and read the dataset from CSV as usual." }, { "code": null, "e": 1756, "s": 1639, "text": "#Import the packageimport pandas as pdimport swifter#read the datasetdf = pd.read_csv('r_dataisbeautiful_posts.csv')" }, { "code": null, "e": 2022, "s": 1756, "text": "This is our dataset. Now, let’s say I want to multiply the score by two and subtract the score by one (This is just a random equation I used here). Then I would put it in another column. In this case, I could use the apply function from the Pandas object attribute." }, { "code": null, "e": 2085, "s": 2022, "text": "%time df['score_2_subs'] = df['score'].apply(lambda x: x/2 -1)" }, { "code": null, "e": 2273, "s": 2085, "text": "The time to execute the function to each data takes around 42.9 ms for an apply attribute by Pandas. This time, we would use Swifter and see how much time it take to execute the function." }, { "code": null, "e": 2489, "s": 2273, "text": "#When we importing the Swifter package, it would integrated with Pandas package and we could use functional attribute from Pandas such as apply%time df['score_2_swift'] = df['score'].swifter.apply(lambda x: x/2 - 1)" }, { "code": null, "e": 2594, "s": 2489, "text": "As we can see above, Swifter processes the data way faster compared to the normal Pandas apply function." }, { "code": null, "e": 2785, "s": 2594, "text": "From the documentation, it is stated that Swifter could apply function a hundred times faster than Pandas function. This, however, only applied if we are using a vectorized form of function." }, { "code": null, "e": 3019, "s": 2785, "text": "Let’s say I create a function that evaluates the num_comments and score variable. When the comment count is zero, I will double the score. While it’s not, the score would stay the same. Then I would create a new column based on that." }, { "code": null, "e": 3271, "s": 3019, "text": "def scoring_comment(x): if x['num_comments'] == 0: return x['score'] *2 else: return x['score']#Trying applying the function using Pandas apply%time df['score_comment'] = df[['score','num_comments']].apply(scoring_comment, axis =1)" }, { "code": null, "e": 3376, "s": 3271, "text": "It takes around 3.96 seconds to execute the function. Let’s see the performance if we are using Swifter." }, { "code": null, "e": 3480, "s": 3376, "text": "%time df['score_comment_swift'] = df[['score', 'num_comments']].swifter.apply(scoring_comment, axis =1)" }, { "code": null, "e": 3819, "s": 3480, "text": "As we can see above, it takes much longer using Swifter compared to the regular Pandas apply function. This is because Swifter with non-vectorized function would implement dask parallel processing, not relying on the Swifter processing itself. So, how is the performance if we change the function to the vectorized function? Let’s try it." }, { "code": null, "e": 4136, "s": 3819, "text": "Import numpy as np#Using np.where to implement vectorized functiondef scoring_comment_vectorized(x): return np.where(x['num_comments'] ==0, x['score']*2, x['score'])#Trying using the normal Pandas apply%time df['score_comment_vectorized'] = df[['score', 'num_comments']].apply(scoring_comment_vectorized, axis =1)" }, { "code": null, "e": 4274, "s": 4136, "text": "It takes around 6.25 seconds using the normal apply function to execute our vectorized function. Let’s see the performance using Swifter." }, { "code": null, "e": 4400, "s": 4274, "text": "%time df['score_comment_vectorized_swift'] = df[['score', 'num_comments']].swifter.apply(scoring_comment_vectorized, axis =1)" }, { "code": null, "e": 4635, "s": 4400, "text": "The execution time now takes only 11 ms with the vectorized function, which saves so much time compared to the normal apply function. This is why it is advisable to use the vectorized function when we are processing data with Swifter." }, { "code": null, "e": 4757, "s": 4635, "text": "If you want to keep track of the execution time that just happen, I will give you the overall summary in the table below." }, { "code": null, "e": 5024, "s": 4757, "text": "I just show you how Swifter could speed up your Pandas Data Processing. Swifter is works best when we use a vectorized function instead of a non-vectorized function. If you want to know more about the Swifter and the available API, you could check the documentation." } ]
Java Examples - Multiple exception (divided by zero)
How to use handle multiple exceptions (devided by zero) ? This example shows how to handle multiple exceptions while deviding by zero ? public class Main { public static void main (String args[]) { int array[] = {20,20,40}; int num1 = 15, num2 = 0; int result = 0; try { result = num1/num2; System.out.println("The result is" +result); for(int i = 2; i >= 0; i--) { System.out.println("The value of array is" +array[i]); } } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Error. Array is out of Bounds"+e); } catch (ArithmeticException e) { System.out.println ("Can't be divided by Zero"+e); } } } The above code sample will produce the following result. Can't be divided by Zerojava.lang.ArithmeticException: / by zero The following is an another example to use handle multiple exceptions in Java. public class JavaApplication4 { public static void main(String args[]) { try { int a[] = new int[5]; a[5] = 30/0; } catch(ArithmeticException e){System.out.println("task1 is completed");} catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");} catch(Exception e){System.out.println("common task completed");} System.out.println("rest of the code..."); } } The above code sample will produce the following result. task1 is completed rest of the code... Print Add Notes Bookmark this page
[ { "code": null, "e": 2126, "s": 2068, "text": "How to use handle multiple exceptions (devided by zero) ?" }, { "code": null, "e": 2204, "s": 2126, "text": "This example shows how to handle multiple exceptions while deviding by zero ?" }, { "code": null, "e": 2806, "s": 2204, "text": "public class Main {\n public static void main (String args[]) {\n int array[] = {20,20,40};\n int num1 = 15, num2 = 0;\n int result = 0;\n try {\n result = num1/num2;\n System.out.println(\"The result is\" +result);\n \n for(int i = 2; i >= 0; i--) {\n System.out.println(\"The value of array is\" +array[i]);\n }\n } catch (ArrayIndexOutOfBoundsException e) {\n System.out.println(\"Error. Array is out of Bounds\"+e);\n } catch (ArithmeticException e) {\n System.out.println (\"Can't be divided by Zero\"+e);\n }\n }\n}" }, { "code": null, "e": 2863, "s": 2806, "text": "The above code sample will produce the following result." }, { "code": null, "e": 2929, "s": 2863, "text": "Can't be divided by Zerojava.lang.ArithmeticException: / by zero\n" }, { "code": null, "e": 3008, "s": 2929, "text": "The following is an another example to use handle multiple exceptions in Java." }, { "code": null, "e": 3465, "s": 3008, "text": "public class JavaApplication4 { \n public static void main(String args[]) { \n try { \n int a[] = new int[5];\n a[5] = 30/0; \n } \n catch(ArithmeticException e){System.out.println(\"task1 is completed\");} \n catch(ArrayIndexOutOfBoundsException e){System.out.println(\"task 2 completed\");} \n catch(Exception e){System.out.println(\"common task completed\");}\n System.out.println(\"rest of the code...\"); \n } \n} " }, { "code": null, "e": 3522, "s": 3465, "text": "The above code sample will produce the following result." }, { "code": null, "e": 3562, "s": 3522, "text": "task1 is completed\nrest of the code...\n" }, { "code": null, "e": 3569, "s": 3562, "text": " Print" }, { "code": null, "e": 3580, "s": 3569, "text": " Add Notes" } ]
How do I insert a NULL value in MySQL?
To insert a NULL value, you can use UPDATE command. Following is the syntax − UPDATE yourTableName SET yourColumnName=NULL; Let us first create a table − mysql> create table insertNullValue -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> ClientName varchar(100), -> ClientCountryName varchar(20) -> ); Query OK, 0 rows affected (0.54 sec) Following is the query to insert some records in the table using insert command − mysql> insert into insertNullValue(ClientName,ClientCountryName) values('Larry','US'); Query OK, 1 row affected (0.19 sec) mysql> insert into insertNullValue(ClientName,ClientCountryName) values('David','AUS'); Query OK, 1 row affected (0.09 sec) mysql> insert into insertNullValue(ClientName,ClientCountryName) values('Bob','UK'); Query OK, 1 row affected (0.17 sec) Following is the query to display all records from the table using select statement − mysql> select * from insertNullValue; This will produce the following output − +----+------------+-------------------+ | Id | ClientName | ClientCountryName | +----+------------+-------------------+ | 1 | Larry | US | | 2 | David | AUS | | 3 | Bob | UK | +----+------------+-------------------+ 3 rows in set (0.00 sec) Following is the query to insert NULL value for a column − mysql> update insertNullValue set ClientCountryName=NULL; Query OK, 3 rows affected (0.19 sec) Rows matched: 3 Changed: 3 Warnings: 0 Let us check the NULL value is inserted for the column ‘ClientCountryName’ or not. Following is the query − mysql> select * from insertNullValue; This will produce the following output displaying the NULL values − +----+------------+-------------------+ | Id | ClientName | ClientCountryName | +----+------------+-------------------+ | 1 | Larry | NULL | | 2 | David | NULL | | 3 | Bob | NULL | +----+------------+-------------------+ 3 rows in set (0.00 sec)
[ { "code": null, "e": 1140, "s": 1062, "text": "To insert a NULL value, you can use UPDATE command. Following is the syntax −" }, { "code": null, "e": 1186, "s": 1140, "text": "UPDATE yourTableName SET yourColumnName=NULL;" }, { "code": null, "e": 1216, "s": 1186, "text": "Let us first create a table −" }, { "code": null, "e": 1423, "s": 1216, "text": "mysql> create table insertNullValue\n -> (\n -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> ClientName varchar(100),\n -> ClientCountryName varchar(20)\n -> );\nQuery OK, 0 rows affected (0.54 sec)" }, { "code": null, "e": 1505, "s": 1423, "text": "Following is the query to insert some records in the table using insert command −" }, { "code": null, "e": 1875, "s": 1505, "text": "mysql> insert into insertNullValue(ClientName,ClientCountryName) values('Larry','US');\nQuery OK, 1 row affected (0.19 sec)\n\nmysql> insert into insertNullValue(ClientName,ClientCountryName) values('David','AUS');\nQuery OK, 1 row affected (0.09 sec)\n\nmysql> insert into insertNullValue(ClientName,ClientCountryName) values('Bob','UK');\nQuery OK, 1 row affected (0.17 sec)" }, { "code": null, "e": 1961, "s": 1875, "text": "Following is the query to display all records from the table using select statement −" }, { "code": null, "e": 1999, "s": 1961, "text": "mysql> select * from insertNullValue;" }, { "code": null, "e": 2040, "s": 1999, "text": "This will produce the following output −" }, { "code": null, "e": 2345, "s": 2040, "text": "+----+------------+-------------------+\n| Id | ClientName | ClientCountryName |\n+----+------------+-------------------+\n| 1 | Larry | US |\n| 2 | David | AUS |\n| 3 | Bob | UK |\n+----+------------+-------------------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 2404, "s": 2345, "text": "Following is the query to insert NULL value for a column −" }, { "code": null, "e": 2538, "s": 2404, "text": "mysql> update insertNullValue set ClientCountryName=NULL;\nQuery OK, 3 rows affected (0.19 sec)\nRows matched: 3 Changed: 3 Warnings: 0" }, { "code": null, "e": 2646, "s": 2538, "text": "Let us check the NULL value is inserted for the column ‘ClientCountryName’ or not. Following is the query −" }, { "code": null, "e": 2684, "s": 2646, "text": "mysql> select * from insertNullValue;" }, { "code": null, "e": 2752, "s": 2684, "text": "This will produce the following output displaying the NULL values −" }, { "code": null, "e": 3057, "s": 2752, "text": "+----+------------+-------------------+\n| Id | ClientName | ClientCountryName |\n+----+------------+-------------------+\n| 1 | Larry | NULL |\n| 2 | David | NULL |\n| 3 | Bob | NULL |\n+----+------------+-------------------+\n3 rows in set (0.00 sec)" } ]
Plotting charts with Seaborn. Create attractive, intriguing charts... | by Jenny Dcruz | Towards Data Science
Seaborn is a powerful Python library which was created for enhancing data visualizations. It provides a large number of high-level interfaces to Matplotlib. Seaborn works well with dataframes while Matplotlib doesn’t. It lets you plot striking charts in a much simpler way. For better understanding of this article, you will need to know the basics of pandas as well as matplotlib. If not, you can refer to the following articles on the same: Pandas for data analysisVisualizations with Matplotlib Pandas for data analysis Visualizations with Matplotlib Make sure you have the necessary libraries installed in your system: Using conda: conda install pandasconda install matplotlibconda install seaborn Using pip: pip install pandaspip install matplotlibpip install seaborn Let’s first import the required Python libraries and our dataset. You can find the CSV file to this tutorial here. import pandas as pdfrom matplotlib import pyplot as pltimport seaborn as snsdf = pd.read_csv('Pokemon.csv', index_col = 0, encoding='unicode-escape')df.head() In the above code, we set index_col to 0 which indicates that we are treating the first column as the index. Using seaborn and the attributes from our Pokemon dataset we shall create some very interesting visualizations. The first thing that we’ll look at are scatter plots. Scatter plots use dots to represent values for different numeric variables. The position of each dot on the horizontal and vertical axis indicates values for an individual data point. They are used to observe relationships between variables. Making Scatterplots in seaborn takes just one line of code using the ‘lmplot’ function. To do so, we pass in the dataframe to the data argument and then pass in the column names for the x and y axes. By default, scatterplot also displays a regression line which simply is a line that best fits the data. sns.lmplot(x=’Attack’, y=’Defense’, data=df)plt.show() Here you can see our scatter plot which shows the attack scores compared to the defense scores. The regression line basically shows us the correlation between the two axes. In this case it is sloping upwards. Which means when attack scores get higher, so do defense scores. To remove the regression line, we can set the ‘fitreg’ argument to false. Furthermore, we can set the hue argument to color the individual plots by the Pokemon’s evolution stage. This hue argument is very useful because it allows you to express a third dimension of information with color. sns.lmplot(x=’Attack’, y=’Defense’, data=df, fit_reg=False, hue=’Stage’)plt.show() The scatter plot looks the same as the one before except that now it doesn’t have the regression line in the middle and it also has different colors for each point. The colors just show the stage of each individual pokemon. Stage is just another attribute in the data which we saw before. Looking at this plot, we can make the conclusion that the pokemon in stage 1 or the blue dots usually have lower scores than the pokemons in the higher stages. Boxplots are one of the important plots that are often used for displaying the distribution of data. It only takes a line of code in seaborn to display a boxplot using its boxplot function. In this example, we’ll use the whole dataframe except for the total, stage and legendary attributes. df_copy = df.drop([‘Total’, ‘Stage’, ‘Legendary’], axis=1)sns.boxplot(data=df_copy) Here we can see that each attribute has its individual boxplot. A box plot is based on a 5 number summary which are each displayed as different lines. The middle line is the median value and is the point where the data is centered around. The bottom and top most lines towards the ends of the box plot are the medians of quartile 1 and 4 which basically show the minimum and maximum of the distribution. The other two lines in the middle are medians of quartile 2 and 3 which show how much the values vary from the median. The single points outside this range indicate any outliers in the data. Violin plots are similar to boxplots. Violin plots are very useful alternatives to boxplots. They show the distribution through the thickness of the violin instead of only the summary statistics. Violin plots are known to be very handy while analyzing and visualizing the distribution of different attributes in a dataset. In this example, we’ll use the same dataframe copy from the last example. sns.violinplot(data=df_copy)plt.show() We can observe the distribution of values for each attribute of the pokemon. The areas where the violin is thicker means that there is a higher density of values. The middle of the violin plot is typically thicker meaning that there’s a high density of values there. Next we’ll visualize the distribution of the attack scores compared the pokemons primary type. To do this, lets use the same violin plot method. plt.figure(figsize=(10,6))\sns.violinplot(x='Type 1', y='Attack', data=df)plt.show() This plot shows the distribution of attack scores for each pokemon’s primary type. As you can see, the ‘Dragon’ type pokemon has the highest attack scores but they also have a higher variance which means that they also have attack scores that are very low. The ‘Ghost’ primary type has a very low variance which means most of their data values are concentrated in the center. Heatmaps help you visualize matrix type data. For example, we can visualize all the correlations between different attributes of the pokemons. Let us calculate the correlation for our dataframes by calling the ‘corr’ function and plot our heatmap using the ‘heatmap’ function. corr = df_copy.corr()sns.heatmap(corr) The above heatmap that displays the correlation of our dataframe. The lighter the color of the box, the higher the correlation is between those two attributes. For example, the correlation between HP and the overall speed of a pokemon is very low. Hence, the dark color of the box. The correlation between the HP and the speed of defense is quite high therefore we can see a red block in the heatmap. We can see that when one attribute gets higher, so does the other attributes such as the speed of the defense. Histograms allow you to plot the distribution of numeric values. If we were to use matplotlib to create histograms, it would require a bit more work as compared to creating the same with seaborn. With seaborn, it only takes one line to create a distribution. For example, we can create a histogram to plot the distribution values with the attack attribute. sns.distplot(df.Attack, color=’blue’) We can see that most pokemon are within the 50–100 range. There are much less pokemons with attack values greater than 100 or less than 50 as we can see here. Similar to bar graphs, calplots let you visualize the distribution of every category’s variables. We can use a calplot to see how many pokemon there are in each primary type. sns.countplot(x=’Type 1', data=df)plt.xticks(rotation=-45) We can see that the ‘Water’ type has the most pokemon where as the ‘Fairy’ and the ‘Ice’ categories has the least. Density plot display the distribution between two variables. For instance, we can use the density plot to compare two attributes of a pokemon: attack values, defense values. We’ll use the ‘jointplot’ function to do this. sns.jointplot(df.Attack, df.Defense, kind=’kde’, color=’lightblue’) ‘kde’ indicates that we want a density plot. As you can see, the plot area varies in darkness depending on how many values are in the area. The dark areas signal a very strong relationship. We can see from this plot, when the attack values are between 50 and 75, defense values are around 50. That’s about it for this article. I hope you enjoyed visualizing data using seaborn. You can find the code as well as the dataset to this article here. Thank you for giving it a read! [1] Seaborn documentation: https://seaborn.pydata.org/
[ { "code": null, "e": 446, "s": 172, "text": "Seaborn is a powerful Python library which was created for enhancing data visualizations. It provides a large number of high-level interfaces to Matplotlib. Seaborn works well with dataframes while Matplotlib doesn’t. It lets you plot striking charts in a much simpler way." }, { "code": null, "e": 615, "s": 446, "text": "For better understanding of this article, you will need to know the basics of pandas as well as matplotlib. If not, you can refer to the following articles on the same:" }, { "code": null, "e": 670, "s": 615, "text": "Pandas for data analysisVisualizations with Matplotlib" }, { "code": null, "e": 695, "s": 670, "text": "Pandas for data analysis" }, { "code": null, "e": 726, "s": 695, "text": "Visualizations with Matplotlib" }, { "code": null, "e": 795, "s": 726, "text": "Make sure you have the necessary libraries installed in your system:" }, { "code": null, "e": 808, "s": 795, "text": "Using conda:" }, { "code": null, "e": 874, "s": 808, "text": "conda install pandasconda install matplotlibconda install seaborn" }, { "code": null, "e": 885, "s": 874, "text": "Using pip:" }, { "code": null, "e": 945, "s": 885, "text": "pip install pandaspip install matplotlibpip install seaborn" }, { "code": null, "e": 1011, "s": 945, "text": "Let’s first import the required Python libraries and our dataset." }, { "code": null, "e": 1060, "s": 1011, "text": "You can find the CSV file to this tutorial here." }, { "code": null, "e": 1219, "s": 1060, "text": "import pandas as pdfrom matplotlib import pyplot as pltimport seaborn as snsdf = pd.read_csv('Pokemon.csv', index_col = 0, encoding='unicode-escape')df.head()" }, { "code": null, "e": 1328, "s": 1219, "text": "In the above code, we set index_col to 0 which indicates that we are treating the first column as the index." }, { "code": null, "e": 1494, "s": 1328, "text": "Using seaborn and the attributes from our Pokemon dataset we shall create some very interesting visualizations. The first thing that we’ll look at are scatter plots." }, { "code": null, "e": 1936, "s": 1494, "text": "Scatter plots use dots to represent values for different numeric variables. The position of each dot on the horizontal and vertical axis indicates values for an individual data point. They are used to observe relationships between variables. Making Scatterplots in seaborn takes just one line of code using the ‘lmplot’ function. To do so, we pass in the dataframe to the data argument and then pass in the column names for the x and y axes." }, { "code": null, "e": 2040, "s": 1936, "text": "By default, scatterplot also displays a regression line which simply is a line that best fits the data." }, { "code": null, "e": 2095, "s": 2040, "text": "sns.lmplot(x=’Attack’, y=’Defense’, data=df)plt.show()" }, { "code": null, "e": 2191, "s": 2095, "text": "Here you can see our scatter plot which shows the attack scores compared to the defense scores." }, { "code": null, "e": 2443, "s": 2191, "text": "The regression line basically shows us the correlation between the two axes. In this case it is sloping upwards. Which means when attack scores get higher, so do defense scores. To remove the regression line, we can set the ‘fitreg’ argument to false." }, { "code": null, "e": 2659, "s": 2443, "text": "Furthermore, we can set the hue argument to color the individual plots by the Pokemon’s evolution stage. This hue argument is very useful because it allows you to express a third dimension of information with color." }, { "code": null, "e": 2742, "s": 2659, "text": "sns.lmplot(x=’Attack’, y=’Defense’, data=df, fit_reg=False, hue=’Stage’)plt.show()" }, { "code": null, "e": 3031, "s": 2742, "text": "The scatter plot looks the same as the one before except that now it doesn’t have the regression line in the middle and it also has different colors for each point. The colors just show the stage of each individual pokemon. Stage is just another attribute in the data which we saw before." }, { "code": null, "e": 3191, "s": 3031, "text": "Looking at this plot, we can make the conclusion that the pokemon in stage 1 or the blue dots usually have lower scores than the pokemons in the higher stages." }, { "code": null, "e": 3482, "s": 3191, "text": "Boxplots are one of the important plots that are often used for displaying the distribution of data. It only takes a line of code in seaborn to display a boxplot using its boxplot function. In this example, we’ll use the whole dataframe except for the total, stage and legendary attributes." }, { "code": null, "e": 3566, "s": 3482, "text": "df_copy = df.drop([‘Total’, ‘Stage’, ‘Legendary’], axis=1)sns.boxplot(data=df_copy)" }, { "code": null, "e": 3630, "s": 3566, "text": "Here we can see that each attribute has its individual boxplot." }, { "code": null, "e": 4161, "s": 3630, "text": "A box plot is based on a 5 number summary which are each displayed as different lines. The middle line is the median value and is the point where the data is centered around. The bottom and top most lines towards the ends of the box plot are the medians of quartile 1 and 4 which basically show the minimum and maximum of the distribution. The other two lines in the middle are medians of quartile 2 and 3 which show how much the values vary from the median. The single points outside this range indicate any outliers in the data." }, { "code": null, "e": 4484, "s": 4161, "text": "Violin plots are similar to boxplots. Violin plots are very useful alternatives to boxplots. They show the distribution through the thickness of the violin instead of only the summary statistics. Violin plots are known to be very handy while analyzing and visualizing the distribution of different attributes in a dataset." }, { "code": null, "e": 4558, "s": 4484, "text": "In this example, we’ll use the same dataframe copy from the last example." }, { "code": null, "e": 4597, "s": 4558, "text": "sns.violinplot(data=df_copy)plt.show()" }, { "code": null, "e": 5009, "s": 4597, "text": "We can observe the distribution of values for each attribute of the pokemon. The areas where the violin is thicker means that there is a higher density of values. The middle of the violin plot is typically thicker meaning that there’s a high density of values there. Next we’ll visualize the distribution of the attack scores compared the pokemons primary type. To do this, lets use the same violin plot method." }, { "code": null, "e": 5094, "s": 5009, "text": "plt.figure(figsize=(10,6))\\sns.violinplot(x='Type 1', y='Attack', data=df)plt.show()" }, { "code": null, "e": 5470, "s": 5094, "text": "This plot shows the distribution of attack scores for each pokemon’s primary type. As you can see, the ‘Dragon’ type pokemon has the highest attack scores but they also have a higher variance which means that they also have attack scores that are very low. The ‘Ghost’ primary type has a very low variance which means most of their data values are concentrated in the center." }, { "code": null, "e": 5613, "s": 5470, "text": "Heatmaps help you visualize matrix type data. For example, we can visualize all the correlations between different attributes of the pokemons." }, { "code": null, "e": 5747, "s": 5613, "text": "Let us calculate the correlation for our dataframes by calling the ‘corr’ function and plot our heatmap using the ‘heatmap’ function." }, { "code": null, "e": 5786, "s": 5747, "text": "corr = df_copy.corr()sns.heatmap(corr)" }, { "code": null, "e": 5852, "s": 5786, "text": "The above heatmap that displays the correlation of our dataframe." }, { "code": null, "e": 6298, "s": 5852, "text": "The lighter the color of the box, the higher the correlation is between those two attributes. For example, the correlation between HP and the overall speed of a pokemon is very low. Hence, the dark color of the box. The correlation between the HP and the speed of defense is quite high therefore we can see a red block in the heatmap. We can see that when one attribute gets higher, so does the other attributes such as the speed of the defense." }, { "code": null, "e": 6557, "s": 6298, "text": "Histograms allow you to plot the distribution of numeric values. If we were to use matplotlib to create histograms, it would require a bit more work as compared to creating the same with seaborn. With seaborn, it only takes one line to create a distribution." }, { "code": null, "e": 6655, "s": 6557, "text": "For example, we can create a histogram to plot the distribution values with the attack attribute." }, { "code": null, "e": 6693, "s": 6655, "text": "sns.distplot(df.Attack, color=’blue’)" }, { "code": null, "e": 6852, "s": 6693, "text": "We can see that most pokemon are within the 50–100 range. There are much less pokemons with attack values greater than 100 or less than 50 as we can see here." }, { "code": null, "e": 7027, "s": 6852, "text": "Similar to bar graphs, calplots let you visualize the distribution of every category’s variables. We can use a calplot to see how many pokemon there are in each primary type." }, { "code": null, "e": 7086, "s": 7027, "text": "sns.countplot(x=’Type 1', data=df)plt.xticks(rotation=-45)" }, { "code": null, "e": 7201, "s": 7086, "text": "We can see that the ‘Water’ type has the most pokemon where as the ‘Fairy’ and the ‘Ice’ categories has the least." }, { "code": null, "e": 7422, "s": 7201, "text": "Density plot display the distribution between two variables. For instance, we can use the density plot to compare two attributes of a pokemon: attack values, defense values. We’ll use the ‘jointplot’ function to do this." }, { "code": null, "e": 7490, "s": 7422, "text": "sns.jointplot(df.Attack, df.Defense, kind=’kde’, color=’lightblue’)" }, { "code": null, "e": 7535, "s": 7490, "text": "‘kde’ indicates that we want a density plot." }, { "code": null, "e": 7783, "s": 7535, "text": "As you can see, the plot area varies in darkness depending on how many values are in the area. The dark areas signal a very strong relationship. We can see from this plot, when the attack values are between 50 and 75, defense values are around 50." }, { "code": null, "e": 7868, "s": 7783, "text": "That’s about it for this article. I hope you enjoyed visualizing data using seaborn." }, { "code": null, "e": 7935, "s": 7868, "text": "You can find the code as well as the dataset to this article here." }, { "code": null, "e": 7967, "s": 7935, "text": "Thank you for giving it a read!" } ]
Java Examples - Display hour and minute
How to display hour and minute (current time)? This example demonstrates how to display the hour and minute of that moment by using Calender.getInstance() of Calender class. import java.util.Calendar; import java.util.Formatter; public class MainClass{ public static void main(String args[]) { Formatter fmt = new Formatter(); Calendar cal = Calendar.getInstance(); fmt = new Formatter(); fmt.format("%tl:%tM", cal, cal); System.out.println(fmt); } } The above code sample will produce the following result. The result will change depending upon the current system time. 09:12 The following is an another sample example of Hour and minute import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class HelloWorld { public static void main(String[] args) { Calendar now = Calendar.getInstance(); System.out.println(now.get(Calendar.HOUR_OF_DAY) + ":" + now.get(Calendar.MINUTE)); } } The above code sample will produce the following result. The result will change depending upon the current system time. 5:31 Print Add Notes Bookmark this page
[ { "code": null, "e": 2115, "s": 2068, "text": "How to display hour and minute (current time)?" }, { "code": null, "e": 2242, "s": 2115, "text": "This example demonstrates how to display the hour and minute of that moment by using Calender.getInstance() of Calender class." }, { "code": null, "e": 2556, "s": 2242, "text": "import java.util.Calendar;\nimport java.util.Formatter;\n\npublic class MainClass{\n public static void main(String args[]) {\n Formatter fmt = new Formatter();\n Calendar cal = Calendar.getInstance();\n fmt = new Formatter();\n fmt.format(\"%tl:%tM\", cal, cal);\n System.out.println(fmt);\n }\n}" }, { "code": null, "e": 2676, "s": 2556, "text": "The above code sample will produce the following result. The result will change depending upon the current system time." }, { "code": null, "e": 2683, "s": 2676, "text": "09:12\n" }, { "code": null, "e": 2745, "s": 2683, "text": "The following is an another sample example of Hour and minute" }, { "code": null, "e": 3045, "s": 2745, "text": "import java.text.SimpleDateFormat;\nimport java.util.Calendar;\nimport java.util.Date;\n\npublic class HelloWorld { \n public static void main(String[] args) { \n Calendar now = Calendar.getInstance();\n System.out.println(now.get(Calendar.HOUR_OF_DAY) + \":\" + now.get(Calendar.MINUTE));\n }\n}" }, { "code": null, "e": 3165, "s": 3045, "text": "The above code sample will produce the following result. The result will change depending upon the current system time." }, { "code": null, "e": 3171, "s": 3165, "text": "5:31\n" }, { "code": null, "e": 3178, "s": 3171, "text": " Print" }, { "code": null, "e": 3189, "s": 3178, "text": " Add Notes" } ]
Equal Sum and XOR of three Numbers - GeeksforGeeks
17 Aug, 2021 Given an integer N. The task is to count the numbers of pairs of integers A and B such that A + B + N = A ^ B ^ N and A and B are less than N.Examples: Input: N = 2 Output: 3 Explanation:- For N = 2 2 XOR 0 XOR 0 = 2+0+0 2 XOR 0 XOR 1 = 2+0+1 2 XOR 0 XOR 2 != 2+0+2 2 XOR 1 XOR 0 = 2+1+0 2 XOR 1 XOR 1 != 2+1+1 2 XOR 1 XOR 2 != 2+1+2 2 XOR 2 XOR 0 != 2+2+0 2 XOR 2 XOR 1 != 2+2+1 2 XOR 2 XOR 2 != 2+2+2So (0, 0), (0, 1) and (1, 0) are the required pairs. So the output is 3.Input: N = 4 Output: 9 Approach : To make the sum of three numbers equal to the xor of three number with one of the number given we can do following:- Represent the fixed number in binary form.Traverse the binary expansion of the fixed number. If you find a 1 there is only one condition i.e. you take the other two number’s binary bits as 0 and 0.If you find a 0 there will be three conditions i.e. either you can have binary bits as (0, 0), (1, 0) or (0, 1).The following triplets of bits will never go for a carry so they are valid.So the answer will be 3^(number of zeros in binary representation). Represent the fixed number in binary form. Traverse the binary expansion of the fixed number. If you find a 1 there is only one condition i.e. you take the other two number’s binary bits as 0 and 0.If you find a 0 there will be three conditions i.e. either you can have binary bits as (0, 0), (1, 0) or (0, 1). If you find a 1 there is only one condition i.e. you take the other two number’s binary bits as 0 and 0. If you find a 0 there will be three conditions i.e. either you can have binary bits as (0, 0), (1, 0) or (0, 1). The following triplets of bits will never go for a carry so they are valid. So the answer will be 3^(number of zeros in binary representation). Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Defining ull to unsigned long long inttypedef unsigned long long int ull; // Function to calculate power of 3ull calculate(int bit_cnt){ ull res = 1; while (bit_cnt--) { res = res * 3; } return res;} // Function to return the count of the// unset bit ( zeros )int unset_bit_count(ull n){ int count = 0; while (n) { // Check the bit is 0 or not if ((n & 1) == 0) count++; // Right shifting ( dividing by 2 ) n = n >> 1; } return count;} // Driver Codeint main(){ ull n; n = 2; int count = unset_bit_count(n); ull ans = calculate(count); cout << ans << endl; return 0;} // Java implementation of the approachimport java.util.*; class GFG{ // Function to calculate power of 3static long calculate(int bit_cnt){ long res = 1; while (bit_cnt-- > 0) { res = res * 3; } return res;} // Function to return the count of the// unset bit ( zeros )static int unset_bit_count(long n){ int count = 0; while (n > 0) { // Check the bit is 0 or not if ((n & 1) == 0) count++; // Right shifting ( dividing by 2 ) n = n >> 1; } return count;} // Driver Codepublic static void main(String[] args){ long n; n = 2; int count = unset_bit_count(n); long ans = calculate(count); System.out.println(ans);}} // This code is contributed by PrinciRaj1992 # Python3 implementation of the approach # Function to calculate power of 3def calculate(bit_cnt): res = 1; while (bit_cnt > 0): bit_cnt -= 1; res = res * 3; return res; # Function to return the count of the# unset bit ( zeros )def unset_bit_count(n): count = 0; while (n > 0): # Check the bit is 0 or not if ((n & 1) == 0): count += 1; # Right shifting ( dividing by 2 ) n = n >> 1; return count; # Driver Codeif __name__ == '__main__': n = 2; count = unset_bit_count(n); ans = calculate(count); print(ans); # This code contributed by Rajput-Ji // C# implementation of the approachusing System; class GFG{ // Function to calculate power of 3static long calculate(int bit_cnt){ long res = 1; while (bit_cnt-- > 0) { res = res * 3; } return res;} // Function to return the count of the// unset bit (zeros)static int unset_bit_count(long n){ int count = 0; while (n > 0) { // Check the bit is 0 or not if ((n & 1) == 0) count++; // Right shifting ( dividing by 2 ) n = n >> 1; } return count;} // Driver Codepublic static void Main(String[] args){ long n; n = 2; int count = unset_bit_count(n); long ans = calculate(count); Console.WriteLine(ans);}} // This code is contributed by 29AjayKumar <script> // Javascript implementation of// the above approach // Function to calculate power of 3function calculate(bit_cnt){ let res = 1; while (bit_cnt--) { res = res * 3; } return res;} // Function to return the count of the// unset bit ( zeros )function unset_bit_count(n){ let count = 0; while (n) { // Check the bit is 0 or not if ((n & 1) == 0) count++; // Right shifting ( dividing by 2 ) n = n >> 1; } return count;} // Driver Code let n; n = 2; let count = unset_bit_count(n); let ans = calculate(count); document.write(ans); </script> 3 Time Complexity: O(Number of unset_bits). Auxiliary Space: O(1). princiraj1992 29AjayKumar Rajput-Ji subhammahato348 pankajsharmagfg Bitwise-XOR Numbers Bit Magic Competitive Programming Data Structures Data Structures Bit Magic Numbers Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Cyclic Redundancy Check and Modulo-2 Division Little and Big Endian Mystery Program to find whether a given number is power of 2 Binary representation of a given number Add two numbers without using arithmetic operators Practice for cracking any coding interview Competitive Programming - A Complete Guide Arrow operator -> in C/C++ with Examples Modulo 10^9+7 (1000000007) Top 10 Algorithms and Data Structures for Competitive Programming
[ { "code": null, "e": 25036, "s": 25008, "text": "\n17 Aug, 2021" }, { "code": null, "e": 25190, "s": 25036, "text": "Given an integer N. The task is to count the numbers of pairs of integers A and B such that A + B + N = A ^ B ^ N and A and B are less than N.Examples: " }, { "code": null, "e": 25537, "s": 25190, "text": "Input: N = 2 Output: 3 Explanation:- For N = 2 2 XOR 0 XOR 0 = 2+0+0 2 XOR 0 XOR 1 = 2+0+1 2 XOR 0 XOR 2 != 2+0+2 2 XOR 1 XOR 0 = 2+1+0 2 XOR 1 XOR 1 != 2+1+1 2 XOR 1 XOR 2 != 2+1+2 2 XOR 2 XOR 0 != 2+2+0 2 XOR 2 XOR 1 != 2+2+1 2 XOR 2 XOR 2 != 2+2+2So (0, 0), (0, 1) and (1, 0) are the required pairs. So the output is 3.Input: N = 4 Output: 9 " }, { "code": null, "e": 25669, "s": 25539, "text": "Approach : To make the sum of three numbers equal to the xor of three number with one of the number given we can do following:- " }, { "code": null, "e": 26121, "s": 25669, "text": "Represent the fixed number in binary form.Traverse the binary expansion of the fixed number. If you find a 1 there is only one condition i.e. you take the other two number’s binary bits as 0 and 0.If you find a 0 there will be three conditions i.e. either you can have binary bits as (0, 0), (1, 0) or (0, 1).The following triplets of bits will never go for a carry so they are valid.So the answer will be 3^(number of zeros in binary representation)." }, { "code": null, "e": 26164, "s": 26121, "text": "Represent the fixed number in binary form." }, { "code": null, "e": 26432, "s": 26164, "text": "Traverse the binary expansion of the fixed number. If you find a 1 there is only one condition i.e. you take the other two number’s binary bits as 0 and 0.If you find a 0 there will be three conditions i.e. either you can have binary bits as (0, 0), (1, 0) or (0, 1)." }, { "code": null, "e": 26537, "s": 26432, "text": "If you find a 1 there is only one condition i.e. you take the other two number’s binary bits as 0 and 0." }, { "code": null, "e": 26650, "s": 26537, "text": "If you find a 0 there will be three conditions i.e. either you can have binary bits as (0, 0), (1, 0) or (0, 1)." }, { "code": null, "e": 26726, "s": 26650, "text": "The following triplets of bits will never go for a carry so they are valid." }, { "code": null, "e": 26794, "s": 26726, "text": "So the answer will be 3^(number of zeros in binary representation)." }, { "code": null, "e": 26847, "s": 26794, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26851, "s": 26847, "text": "C++" }, { "code": null, "e": 26856, "s": 26851, "text": "Java" }, { "code": null, "e": 26864, "s": 26856, "text": "Python3" }, { "code": null, "e": 26867, "s": 26864, "text": "C#" }, { "code": null, "e": 26878, "s": 26867, "text": "Javascript" }, { "code": "// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Defining ull to unsigned long long inttypedef unsigned long long int ull; // Function to calculate power of 3ull calculate(int bit_cnt){ ull res = 1; while (bit_cnt--) { res = res * 3; } return res;} // Function to return the count of the// unset bit ( zeros )int unset_bit_count(ull n){ int count = 0; while (n) { // Check the bit is 0 or not if ((n & 1) == 0) count++; // Right shifting ( dividing by 2 ) n = n >> 1; } return count;} // Driver Codeint main(){ ull n; n = 2; int count = unset_bit_count(n); ull ans = calculate(count); cout << ans << endl; return 0;}", "e": 27631, "s": 26878, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class GFG{ // Function to calculate power of 3static long calculate(int bit_cnt){ long res = 1; while (bit_cnt-- > 0) { res = res * 3; } return res;} // Function to return the count of the// unset bit ( zeros )static int unset_bit_count(long n){ int count = 0; while (n > 0) { // Check the bit is 0 or not if ((n & 1) == 0) count++; // Right shifting ( dividing by 2 ) n = n >> 1; } return count;} // Driver Codepublic static void main(String[] args){ long n; n = 2; int count = unset_bit_count(n); long ans = calculate(count); System.out.println(ans);}} // This code is contributed by PrinciRaj1992", "e": 28398, "s": 27631, "text": null }, { "code": "# Python3 implementation of the approach # Function to calculate power of 3def calculate(bit_cnt): res = 1; while (bit_cnt > 0): bit_cnt -= 1; res = res * 3; return res; # Function to return the count of the# unset bit ( zeros )def unset_bit_count(n): count = 0; while (n > 0): # Check the bit is 0 or not if ((n & 1) == 0): count += 1; # Right shifting ( dividing by 2 ) n = n >> 1; return count; # Driver Codeif __name__ == '__main__': n = 2; count = unset_bit_count(n); ans = calculate(count); print(ans); # This code contributed by Rajput-Ji", "e": 29060, "s": 28398, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to calculate power of 3static long calculate(int bit_cnt){ long res = 1; while (bit_cnt-- > 0) { res = res * 3; } return res;} // Function to return the count of the// unset bit (zeros)static int unset_bit_count(long n){ int count = 0; while (n > 0) { // Check the bit is 0 or not if ((n & 1) == 0) count++; // Right shifting ( dividing by 2 ) n = n >> 1; } return count;} // Driver Codepublic static void Main(String[] args){ long n; n = 2; int count = unset_bit_count(n); long ans = calculate(count); Console.WriteLine(ans);}} // This code is contributed by 29AjayKumar", "e": 29814, "s": 29060, "text": null }, { "code": "<script> // Javascript implementation of// the above approach // Function to calculate power of 3function calculate(bit_cnt){ let res = 1; while (bit_cnt--) { res = res * 3; } return res;} // Function to return the count of the// unset bit ( zeros )function unset_bit_count(n){ let count = 0; while (n) { // Check the bit is 0 or not if ((n & 1) == 0) count++; // Right shifting ( dividing by 2 ) n = n >> 1; } return count;} // Driver Code let n; n = 2; let count = unset_bit_count(n); let ans = calculate(count); document.write(ans); </script>", "e": 30450, "s": 29814, "text": null }, { "code": null, "e": 30452, "s": 30450, "text": "3" }, { "code": null, "e": 30521, "s": 30454, "text": "Time Complexity: O(Number of unset_bits). Auxiliary Space: O(1). " }, { "code": null, "e": 30535, "s": 30521, "text": "princiraj1992" }, { "code": null, "e": 30547, "s": 30535, "text": "29AjayKumar" }, { "code": null, "e": 30557, "s": 30547, "text": "Rajput-Ji" }, { "code": null, "e": 30573, "s": 30557, "text": "subhammahato348" }, { "code": null, "e": 30589, "s": 30573, "text": "pankajsharmagfg" }, { "code": null, "e": 30601, "s": 30589, "text": "Bitwise-XOR" }, { "code": null, "e": 30609, "s": 30601, "text": "Numbers" }, { "code": null, "e": 30619, "s": 30609, "text": "Bit Magic" }, { "code": null, "e": 30643, "s": 30619, "text": "Competitive Programming" }, { "code": null, "e": 30659, "s": 30643, "text": "Data Structures" }, { "code": null, "e": 30675, "s": 30659, "text": "Data Structures" }, { "code": null, "e": 30685, "s": 30675, "text": "Bit Magic" }, { "code": null, "e": 30693, "s": 30685, "text": "Numbers" }, { "code": null, "e": 30791, "s": 30693, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30837, "s": 30791, "text": "Cyclic Redundancy Check and Modulo-2 Division" }, { "code": null, "e": 30867, "s": 30837, "text": "Little and Big Endian Mystery" }, { "code": null, "e": 30920, "s": 30867, "text": "Program to find whether a given number is power of 2" }, { "code": null, "e": 30960, "s": 30920, "text": "Binary representation of a given number" }, { "code": null, "e": 31011, "s": 30960, "text": "Add two numbers without using arithmetic operators" }, { "code": null, "e": 31054, "s": 31011, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 31097, "s": 31054, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 31138, "s": 31097, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 31165, "s": 31138, "text": "Modulo 10^9+7 (1000000007)" } ]
Check if the given push and pop sequences of Stack is valid or not - GeeksforGeeks
14 May, 2021 Given push[] and pop[] sequences with distinct values. The task is to check if this could have been the result of a sequence of push and pop operations on an initially empty stack. Return “True” if it otherwise returns “False”.Examples: Input: pushed = { 1, 2, 3, 4, 5 }, popped = { 4, 5, 3, 2, 1 } Output: True Following sequence can be performed: push(1), push(2), push(3), push(4), pop() -> 4, push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1 Input: pushed = { 1, 2, 3, 4, 5 }, popped = { 4, 3, 5, 1, 2 } Output: False 1 can't be popped before 2. Approach: If the element X has been pushed to the stack then check if the top element in the pop[] sequence is X or not. If it is X then pop it right now else top of the push[] sequence will be changed and make the sequences invalid. So, similarly, do the same for all the elements and check if the stack is empty or not in the last. If empty then print True else print False.Below is the implementation of above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of above approach#include <iostream>#include <stack> using namespace std; // Function to check validity of stack sequencebool validateStackSequence(int pushed[], int popped[], int len){ // maintain count of popped elements int j = 0; // an empty stack stack <int> st; for(int i = 0; i < len; i++){ st.push(pushed[i]); // check if appended value is next to be popped out while (!st.empty() && j < len && st.top() == popped[j]){ st.pop(); j++; } } return j == len;} // Driver codeint main(){ int pushed[] = {1, 2, 3, 4, 5}; int popped[] = {4, 5, 3, 2, 1}; int len = sizeof(pushed)/sizeof(pushed[0]); cout << (validateStackSequence(pushed, popped, len) ? "True" : "False"); return 0;} // This code is contributed by Rituraj Jain // Java program for above implementationimport java.util.*; class GfG{ // Function to check validity of stack sequence static boolean validateStackSequence(int pushed[], int popped[], int len) { // maintain count of popped elements int j = 0; // an empty stack Stack<Integer> st = new Stack<>(); for (int i = 0; i < len; i++) { st.push(pushed[i]); // check if appended value // is next to be popped out while (!st.empty() && j < len && st.peek() == popped[j]) { st.pop(); j++; } } return j == len; } // Driver code public static void main(String[] args) { int pushed[] = {1, 2, 3, 4, 5}; int popped[] = {4, 5, 3, 2, 1}; int len = pushed.length; System.out.println((validateStackSequence(pushed, popped, len) ? "True" : "False")); }} /* This code contributed by PrinciRaj1992 */ # Function to check validity of stack sequencedef validateStackSequence(pushed, popped): # maintain count of popped elements j = 0 # an empty stack stack = [] for x in pushed: stack.append(x) # check if appended value is next to be popped out while stack and j < len(popped) and stack[-1] == popped[j]: stack.pop() j = j + 1 return j == len(popped) # Driver codepushed = [1, 2, 3, 4, 5]popped = [4, 5, 3, 2, 1]print(validateStackSequence(pushed, popped)) // C# program for above implementationusing System;using System.Collections.Generic; class GfG{ // Function to check validity of stack sequence static bool validateStackSequence(int []pushed, int []popped, int len) { // maintain count of popped elements int j = 0; // an empty stack Stack<int> st = new Stack<int>(); for (int i = 0; i < len; i++) { st.Push(pushed[i]); // check if appended value // is next to be popped out while (st.Count != 0 && j < len && st.Peek() == popped[j]) { st.Pop(); j++; } } return j == len; } // Driver code public static void Main(String[] args) { int []pushed = {1, 2, 3, 4, 5}; int []popped = {4, 5, 3, 2, 1}; int len = pushed.Length; Console.WriteLine((validateStackSequence(pushed, popped, len) ? "True" : "False")); }} // This code contributed by Rajput-Ji <?php// PHP implementation of above approach // Function to check validity of stack sequencefunction validateStackSequence($pushed, $popped, $len){ // maintain count of popped elements $j = 0; // an empty stack $st = array(); for($i = 0; $i < $len; $i++) { array_push($st, $pushed[$i]); // check if appended value is next // to be popped out while (!empty($st) && $j < $len && $st[count($st) - 1] == $popped[$j]) { array_pop($st); $j++; } } return $j == $len;} // Driver code$pushed = array(1, 2, 3, 4, 5);$popped = array(4, 5, 3, 2, 1);$len = count($pushed); echo (validateStackSequence($pushed, $popped, $len) ? "True" : "False"); // This code is contributed by mits?> <script> // Javascript implementation of above approach function validateStackSequence( pushed, popped, len){ // maintain count of popped elements var j = 0; // an empty stack var st=[]; for(var i = 0; i < len; i++){ st.push(pushed[i]); // check if appended value is next // to be popped out while (!st.length==0 && j < len && st[st.length-1] == popped[j]) { st.pop(); j++; } } return j == len;} var pushed = [1, 2, 3, 4, 5]; var popped = [4, 5, 3, 2, 1]; var len = pushed.length; document.write( (validateStackSequence(pushed, popped, len) ? "True" : "False")); // This code is contributed by SoumikMondal </script> True Time Complexity: O(N), where N is size of stack. rituraj_jain princiraj1992 Rajput-Ji Mithun Kumar SoumikMondal Arrays Python Programs Stack Arrays Stack Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Stack Data Structure (Introduction and Program) Introduction to Arrays Multidimensional Arrays in Java 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": 25695, "s": 25667, "text": "\n14 May, 2021" }, { "code": null, "e": 25934, "s": 25695, "text": "Given push[] and pop[] sequences with distinct values. The task is to check if this could have been the result of a sequence of push and pop operations on an initially empty stack. Return “True” if it otherwise returns “False”.Examples: " }, { "code": null, "e": 26255, "s": 25934, "text": "Input: pushed = { 1, 2, 3, 4, 5 }, popped = { 4, 5, 3, 2, 1 }\nOutput: True\nFollowing sequence can be performed:\npush(1), push(2), push(3), push(4), pop() -> 4,\npush(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1\n\nInput: pushed = { 1, 2, 3, 4, 5 }, popped = { 4, 3, 5, 1, 2 }\nOutput: False\n1 can't be popped before 2." }, { "code": null, "e": 26681, "s": 26257, "text": "Approach: If the element X has been pushed to the stack then check if the top element in the pop[] sequence is X or not. If it is X then pop it right now else top of the push[] sequence will be changed and make the sequences invalid. So, similarly, do the same for all the elements and check if the stack is empty or not in the last. If empty then print True else print False.Below is the implementation of above approach: " }, { "code": null, "e": 26685, "s": 26681, "text": "C++" }, { "code": null, "e": 26690, "s": 26685, "text": "Java" }, { "code": null, "e": 26698, "s": 26690, "text": "Python3" }, { "code": null, "e": 26701, "s": 26698, "text": "C#" }, { "code": null, "e": 26705, "s": 26701, "text": "PHP" }, { "code": null, "e": 26716, "s": 26705, "text": "Javascript" }, { "code": "// C++ implementation of above approach#include <iostream>#include <stack> using namespace std; // Function to check validity of stack sequencebool validateStackSequence(int pushed[], int popped[], int len){ // maintain count of popped elements int j = 0; // an empty stack stack <int> st; for(int i = 0; i < len; i++){ st.push(pushed[i]); // check if appended value is next to be popped out while (!st.empty() && j < len && st.top() == popped[j]){ st.pop(); j++; } } return j == len;} // Driver codeint main(){ int pushed[] = {1, 2, 3, 4, 5}; int popped[] = {4, 5, 3, 2, 1}; int len = sizeof(pushed)/sizeof(pushed[0]); cout << (validateStackSequence(pushed, popped, len) ? \"True\" : \"False\"); return 0;} // This code is contributed by Rituraj Jain", "e": 27577, "s": 26716, "text": null }, { "code": "// Java program for above implementationimport java.util.*; class GfG{ // Function to check validity of stack sequence static boolean validateStackSequence(int pushed[], int popped[], int len) { // maintain count of popped elements int j = 0; // an empty stack Stack<Integer> st = new Stack<>(); for (int i = 0; i < len; i++) { st.push(pushed[i]); // check if appended value // is next to be popped out while (!st.empty() && j < len && st.peek() == popped[j]) { st.pop(); j++; } } return j == len; } // Driver code public static void main(String[] args) { int pushed[] = {1, 2, 3, 4, 5}; int popped[] = {4, 5, 3, 2, 1}; int len = pushed.length; System.out.println((validateStackSequence(pushed, popped, len) ? \"True\" : \"False\")); }} /* This code contributed by PrinciRaj1992 */", "e": 28624, "s": 27577, "text": null }, { "code": "# Function to check validity of stack sequencedef validateStackSequence(pushed, popped): # maintain count of popped elements j = 0 # an empty stack stack = [] for x in pushed: stack.append(x) # check if appended value is next to be popped out while stack and j < len(popped) and stack[-1] == popped[j]: stack.pop() j = j + 1 return j == len(popped) # Driver codepushed = [1, 2, 3, 4, 5]popped = [4, 5, 3, 2, 1]print(validateStackSequence(pushed, popped))", "e": 29145, "s": 28624, "text": null }, { "code": "// C# program for above implementationusing System;using System.Collections.Generic; class GfG{ // Function to check validity of stack sequence static bool validateStackSequence(int []pushed, int []popped, int len) { // maintain count of popped elements int j = 0; // an empty stack Stack<int> st = new Stack<int>(); for (int i = 0; i < len; i++) { st.Push(pushed[i]); // check if appended value // is next to be popped out while (st.Count != 0 && j < len && st.Peek() == popped[j]) { st.Pop(); j++; } } return j == len; } // Driver code public static void Main(String[] args) { int []pushed = {1, 2, 3, 4, 5}; int []popped = {4, 5, 3, 2, 1}; int len = pushed.Length; Console.WriteLine((validateStackSequence(pushed, popped, len) ? \"True\" : \"False\")); }} // This code contributed by Rajput-Ji", "e": 30230, "s": 29145, "text": null }, { "code": "<?php// PHP implementation of above approach // Function to check validity of stack sequencefunction validateStackSequence($pushed, $popped, $len){ // maintain count of popped elements $j = 0; // an empty stack $st = array(); for($i = 0; $i < $len; $i++) { array_push($st, $pushed[$i]); // check if appended value is next // to be popped out while (!empty($st) && $j < $len && $st[count($st) - 1] == $popped[$j]) { array_pop($st); $j++; } } return $j == $len;} // Driver code$pushed = array(1, 2, 3, 4, 5);$popped = array(4, 5, 3, 2, 1);$len = count($pushed); echo (validateStackSequence($pushed, $popped, $len) ? \"True\" : \"False\"); // This code is contributed by mits?>", "e": 31050, "s": 30230, "text": null }, { "code": "<script> // Javascript implementation of above approach function validateStackSequence( pushed, popped, len){ // maintain count of popped elements var j = 0; // an empty stack var st=[]; for(var i = 0; i < len; i++){ st.push(pushed[i]); // check if appended value is next // to be popped out while (!st.length==0 && j < len && st[st.length-1] == popped[j]) { st.pop(); j++; } } return j == len;} var pushed = [1, 2, 3, 4, 5]; var popped = [4, 5, 3, 2, 1]; var len = pushed.length; document.write( (validateStackSequence(pushed, popped, len) ? \"True\" : \"False\")); // This code is contributed by SoumikMondal </script>", "e": 31794, "s": 31050, "text": null }, { "code": null, "e": 31799, "s": 31794, "text": "True" }, { "code": null, "e": 31851, "s": 31801, "text": "Time Complexity: O(N), where N is size of stack. " }, { "code": null, "e": 31864, "s": 31851, "text": "rituraj_jain" }, { "code": null, "e": 31878, "s": 31864, "text": "princiraj1992" }, { "code": null, "e": 31888, "s": 31878, "text": "Rajput-Ji" }, { "code": null, "e": 31901, "s": 31888, "text": "Mithun Kumar" }, { "code": null, "e": 31914, "s": 31901, "text": "SoumikMondal" }, { "code": null, "e": 31921, "s": 31914, "text": "Arrays" }, { "code": null, "e": 31937, "s": 31921, "text": "Python Programs" }, { "code": null, "e": 31943, "s": 31937, "text": "Stack" }, { "code": null, "e": 31950, "s": 31943, "text": "Arrays" }, { "code": null, "e": 31956, "s": 31950, "text": "Stack" }, { "code": null, "e": 32054, "s": 31956, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32122, "s": 32054, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 32166, "s": 32122, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 32214, "s": 32166, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 32237, "s": 32214, "text": "Introduction to Arrays" }, { "code": null, "e": 32269, "s": 32237, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 32312, "s": 32269, "text": "Python program to convert a list to string" }, { "code": null, "e": 32334, "s": 32312, "text": "Defaultdict in Python" }, { "code": null, "e": 32373, "s": 32334, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 32419, "s": 32373, "text": "Python | Split string into list of characters" } ]
How to count the number of documents in a MongoDB collection?
Following is the syntax to count the number of documents in a MongoDB collection let anyVariableName= db.getCollection(‘yourCollectionName’); yourVariableName.count(); Let us first create a collection with documents > db.countNumberOfDocumentsDemo.insertOne({"CustomerName":"Bob"}); { "acknowledged" : true, "insertedId" : ObjectId("5c9a5e2015e86fd1496b38a1") } >db.countNumberOfDocumentsDemo.insertOne({"CustomerName":"Ramit","CustomerAge":23}); { "acknowledged" : true, "insertedId" : ObjectId("5c9a5e3515e86fd1496b38a2") } >db.countNumberOfDocumentsDemo.insertOne({"CustomerName":"Adam","CustomerAge":27,"CustomerCountryName":"US"}); { "acknowledged" : true, "insertedId" : ObjectId("5c9a5e4c15e86fd1496b38a3") } Following is the query to display all documents from a collection with the help of find() method > db.countNumberOfDocumentsDemo.find().pretty(); This will produce the following output { "_id" : ObjectId("5c9a5e2015e86fd1496b38a1"), "CustomerName" : "Bob" } { "_id" : ObjectId("5c9a5e3515e86fd1496b38a2"), "CustomerName" : "Ramit", "CustomerAge" : 23 } { "_id" : ObjectId("5c9a5e4c15e86fd1496b38a3"), "CustomerName" : "Adam", "CustomerAge" : 27, "CustomerCountryName" : "US" } Following is the query to count the number of documents in a MongoDB collection, > let myCollectionName = db.getCollection('countNumberOfDocumentsDemo'); > myCollectionName.count(); This will produce the following output 3
[ { "code": null, "e": 1143, "s": 1062, "text": "Following is the syntax to count the number of documents in a MongoDB collection" }, { "code": null, "e": 1230, "s": 1143, "text": "let anyVariableName= db.getCollection(‘yourCollectionName’);\nyourVariableName.count();" }, { "code": null, "e": 1278, "s": 1230, "text": "Let us first create a collection with documents" }, { "code": null, "e": 1796, "s": 1278, "text": "> db.countNumberOfDocumentsDemo.insertOne({\"CustomerName\":\"Bob\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c9a5e2015e86fd1496b38a1\")\n}\n>db.countNumberOfDocumentsDemo.insertOne({\"CustomerName\":\"Ramit\",\"CustomerAge\":23});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c9a5e3515e86fd1496b38a2\")\n}\n>db.countNumberOfDocumentsDemo.insertOne({\"CustomerName\":\"Adam\",\"CustomerAge\":27,\"CustomerCountryName\":\"US\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c9a5e4c15e86fd1496b38a3\")\n}" }, { "code": null, "e": 1893, "s": 1796, "text": "Following is the query to display all documents from a collection with the help of find() method" }, { "code": null, "e": 1942, "s": 1893, "text": "> db.countNumberOfDocumentsDemo.find().pretty();" }, { "code": null, "e": 1981, "s": 1942, "text": "This will produce the following output" }, { "code": null, "e": 2294, "s": 1981, "text": "{ \"_id\" : ObjectId(\"5c9a5e2015e86fd1496b38a1\"), \"CustomerName\" : \"Bob\" }\n{\n \"_id\" : ObjectId(\"5c9a5e3515e86fd1496b38a2\"),\n \"CustomerName\" : \"Ramit\",\n \"CustomerAge\" : 23\n}\n{\n \"_id\" : ObjectId(\"5c9a5e4c15e86fd1496b38a3\"),\n \"CustomerName\" : \"Adam\",\n \"CustomerAge\" : 27,\n \"CustomerCountryName\" : \"US\"\n}" }, { "code": null, "e": 2375, "s": 2294, "text": "Following is the query to count the number of documents in a MongoDB collection," }, { "code": null, "e": 2476, "s": 2375, "text": "> let myCollectionName = db.getCollection('countNumberOfDocumentsDemo');\n> myCollectionName.count();" }, { "code": null, "e": 2515, "s": 2476, "text": "This will produce the following output" }, { "code": null, "e": 2517, "s": 2515, "text": "3" } ]
Joining Datasets with Python’s Pandas | by Thiago Carvalho | Towards Data Science
It’s definitely not uncommon to work with more than one dataset when performing your analysis. Therefore, there’s an abundant amount of methods to bring this data together. SQL call those operations ‘Joins’ or ‘Unions’; in other languages and tools, you may find functions like Merge or LookUp to do the job. In this article, I’ll go through some of the functions we can use to join datasets with Pandas. I’ll run my code in a Jupyter notebook, and the only thing we need for the examples is Pandas. import pandas as pd We’ll start by defining some dummy data for the examples, I’ll use lists for simplification, but you’re definitely encouraged to load a dataset. # create 5 lists with the same sizenames = ['bob', 'bella', 'blue', 'suzy', 'gunter', 'joe', 'holly', 'coco', 'elliot']species = ['dog', 'cat', 'velociraptor', 'dog', 'penguin', 'squid', 'cat', 'cat', 'horse']age = [1, 6, 70, 8, 3, 1, 2, 13, 3]weight = [10, 5, 15, 7, 4, 1, 3, 2, 380]color = ['brown', 'black', 'blue', 'black', 'black', 'gray', 'white', 'orange', 'white'] After defining the lists, we can create our data frames. # create 3 data frames with the values from the listsdf1 = pd.DataFrame( {'name': names[:3], 'species': species[:3], 'age': age[:3]})df2 = pd.DataFrame( {'name': names[3:6], 'species': species[3:6], 'age': age[3:6]})df3 = pd.DataFrame( {'name': names[6:], 'species': species[6:], 'age': age[6:]})print(df1, '\n')print(df2, '\n')print(df3) Ok, we have three datasets with the same columns and size. Let’s say we want to group those in a single data frame. For that, we can use .concat, which is a function that accepts a list of data frames and concatenates them into one. # .concat to join the dataframes, like a 'union all'df_list = [df1, df2, df3]df = pd.concat(df_list)df Cool, Pandas matched the columns and returned an almost perfect data frame without much effort. But what if the column names don’t match? or what if we’re missing a column? # test with mismatching and missing columnsdf1 = pd.DataFrame( {'name': names[:3], 'specie': species[:3], 'age': age[:3]})df2 = pd.DataFrame( {'name': names[3:6], 'species': species[3:6], 'age': age[3:6]})df3 = pd.DataFrame( {'name': names[6:], 'age - years': age[6:]})print(df1, '\n')print(df2, '\n')print(df3) For the ‘species’ column, I changed its name in the first df and removed it from the last; I’ve also renamed ‘age’ to ‘age — years’. # concat with mismatching and missing columnsdf_list = [df1, df2, df3]df = pd.concat(df_list)df Ok, so Pandas .concat requires the names of the columns to be exact matches. If a column is unique to a dataset, just like a full join, it’ll fill the gaps with null values. There’s one more thing we need to pay attention to, the indexes. Since we didn’t define unique indexes when creating our data frame, Pandas set us with some default values starting from zero, but it doesn't reset them when we use .concat. A unique index is always a good idea. In this case, we can use .reset_index to create a new column with proper values or use .set_index to define one of the columns as the index. But let’s try an even simpler solution that fits our case. df1 = pd.DataFrame( {'name': names[:3], 'species': species[:3], 'age': age[:3]})df2 = pd.DataFrame( {'name': names[3:6], 'species': species[3:6], 'age': age[3:6]})df3 = pd.DataFrame( {'name': names[6:], 'species': species[6:], 'age': age[6:]})# since we didn't define the indexes when creating the dataframes we can ignore them when concatenatingdf_list = [df1, df2, df3]df = pd.concat(df_list, ignore_index=True)df With a single parameter, we ignored the indexes and got new ones in the concatenated result. Another handy parameter is ‘keys’, which allows us to identify the data source with a new index level. df1 = pd.DataFrame( {'name': names[:3], 'species': species[:3], 'age': age[:3]}, index = [1,2,3])df2 = pd.DataFrame( {'name': names[3:6], 'species': species[3:6], 'age': age[3:6]}, index = [10,11,12])df3 = pd.DataFrame( {'name': names[6:], 'species': species[6:], 'age': age[6:]}, index = [100,200,300])# we can pass 'keys' which creates another index level to identify the concatenated data framesdf_list = [df1, df2, df3, df1]df = pd.concat(df_list, keys=['df1', 'df2', 'df3', 'df4'])df By default, .concat uses the columns as keys and append the values as rows. But what if we want to concatenate columns to our data frame? First, let’s define some new columns to concatenate. df4 = pd.DataFrame( {'weight': weight, 'color': color })df4 Similarly, we could add the lists directly to our data frame by assigning them to a column, like so: df['color'] = color But a data frame could have lots of fields, and passing them one by one wouldn’t be the best option. The concatenate function accepts a parameter for ‘axis’, which allows us to do just that — concatenate columns. df = pd.concat([df, df4], axis=1)df We can also change the behaviour of the join. Let’s try making the ‘name’ column our index and creating another dataset with an extra column to experiment with. df_list = [df1, df2]df = pd.concat(df_list)df.set_index('name', inplace=True)df5 = pd.DataFrame( {'species': species, 'age': age, 'score': [9,10,10,8,6,9,3,4,10]}, index = names)print(df, '\n')print(df5) Note that our first data frame has fewer values than the second. When we perform an inner join, it should only bring the rows where the indexes match. # by default concat behaves like an outer join, or a union all# we can change that with the 'join' parameterdf_list = [df, df5]df = pd.concat(df_list, axis=1, join='inner')df Now let’s have a look at another function called .append. This function has similar behaviour to .concat. The previous take multiple data frames and concatenates them into a new one. The append method will use an existing data frame to add the data. Both will return a data frame, but the way you call them is different. You’ll use Pandas.concat() and DataFrame.append(). Let’s check some examples. df1.append(df2) df = df1.append(df2)df = df.append(df3)print(df, '\n')df = df1.append([df2, df3])print(df) # append a rowdf.append(pd.Series(['oliver', 'monkey', 13], index=['name', 'species', 'age']), ignore_index=True) Awesome, with .concat and .append, we can perform most of the joins we might need. Now let’s check a more robust solution named .merge. Starting with something simple, let’s see how .merge performs a join. I’ll define another data frame similar to the one we’re already using, but with one more column and one less record. print(df, '\n')df6 = pd.DataFrame( {'name': names[1:], 'age': age[1:], 'score': [10,10,8,6,9,3,4,10]})print(df6) Merge allows us to select which column will be the key; in this case, let’s use ‘name’. merged_df = pd.merge(df, df6, on='name')merged_df Unlike what we saw earlier, a merge is by default an inner join — That means unless told otherwise, it’ll only return the matching rows from both datasets. We can also notice that the columns present in both datasets are separated, even though they contain the same values. Lastly, when we perform an inner join like the above, both data frames must have the key column with the same name. You can select multiple columns as key, like a composite key, and you can also select which kind of join you’ll use. merged_df = pd.merge(df, df6, how='left', on=['name', 'age'])merged_df merged_df = pd.merge(df6, df, how='right', on=['name', 'age'])merged_df Great! Besides all that, the merge function also helps us to validate and understand the data were merging. # 'one_to_one' or ‘1:1’merged_df = pd.merge(df6, df.append(df1), how='right', on=['name', 'age'], validate='one_to_one')merged_df For example, the validate parameter will raise an error if the data frames don’t respect the criteria you chose. Other useful options are: ‘one_to_many’ or ‘1:m’ — Checks if the left keys are unique; ‘many_to_one’ or ‘m:1’— Checks if the right keys are unique; The ‘indicator’ parameter adds a column to the data frame explaining the keys' relationship. merged_df = pd.merge(df6, df.append(df1), how='outer', on=['name', 'age'], indicator=True)merged_df *If you pass a string to the indicator parameter, it’ll be used as the created column's name. We don’t need to specify which column contains the key since, by default, Pandas will assume the index is the key. Let’s try setting the name as our index and merging those data frames again. df.set_index('name', inplace=True)df6.set_index('name', inplace=True)print(df)print(df6) pd.merge(df6, df) If we don’t want Pandas to reset the index, we have to use the right_index and left_index parameters. pd.merge(df6, df, how='outer', left_index=True, right_index=True) If we want to merge with an index on one side and with a key on the other, we can specify the right_on and left_on parameters. They accept the column's name holding the key, just like we saw before, but will be applied only to that specific side, using the index column on the other side. pd.merge(df, df6, how='right', right_on='name', left_index=True) Great! We got a look at .concat and .append, two convenient functions for joining two data frames. Then we explored .merge, an even better option with lots of flexibility. Pandas have even more methods to help you work with multiple datasets; it’s not unusual to spend time building the logic to solve your problem and then finding out an already implemented solution for that in a library. So I encourage you to get a look at some of those other functions such as .compare, .combine_first, and .merge_asof. Thanks for reading my article. I hope you enjoyed it! References:Python for Data Analysis — Wes McKinney;Pandas — Concat;Pandas — Merge;Pandas — Append;Pandas — Merge, join, concatenate and compare;
[ { "code": null, "e": 220, "s": 47, "text": "It’s definitely not uncommon to work with more than one dataset when performing your analysis. Therefore, there’s an abundant amount of methods to bring this data together." }, { "code": null, "e": 356, "s": 220, "text": "SQL call those operations ‘Joins’ or ‘Unions’; in other languages and tools, you may find functions like Merge or LookUp to do the job." }, { "code": null, "e": 452, "s": 356, "text": "In this article, I’ll go through some of the functions we can use to join datasets with Pandas." }, { "code": null, "e": 547, "s": 452, "text": "I’ll run my code in a Jupyter notebook, and the only thing we need for the examples is Pandas." }, { "code": null, "e": 567, "s": 547, "text": "import pandas as pd" }, { "code": null, "e": 712, "s": 567, "text": "We’ll start by defining some dummy data for the examples, I’ll use lists for simplification, but you’re definitely encouraged to load a dataset." }, { "code": null, "e": 1085, "s": 712, "text": "# create 5 lists with the same sizenames = ['bob', 'bella', 'blue', 'suzy', 'gunter', 'joe', 'holly', 'coco', 'elliot']species = ['dog', 'cat', 'velociraptor', 'dog', 'penguin', 'squid', 'cat', 'cat', 'horse']age = [1, 6, 70, 8, 3, 1, 2, 13, 3]weight = [10, 5, 15, 7, 4, 1, 3, 2, 380]color = ['brown', 'black', 'blue', 'black', 'black', 'gray', 'white', 'orange', 'white']" }, { "code": null, "e": 1142, "s": 1085, "text": "After defining the lists, we can create our data frames." }, { "code": null, "e": 1601, "s": 1142, "text": "# create 3 data frames with the values from the listsdf1 = pd.DataFrame( {'name': names[:3], 'species': species[:3], 'age': age[:3]})df2 = pd.DataFrame( {'name': names[3:6], 'species': species[3:6], 'age': age[3:6]})df3 = pd.DataFrame( {'name': names[6:], 'species': species[6:], 'age': age[6:]})print(df1, '\\n')print(df2, '\\n')print(df3)" }, { "code": null, "e": 1717, "s": 1601, "text": "Ok, we have three datasets with the same columns and size. Let’s say we want to group those in a single data frame." }, { "code": null, "e": 1834, "s": 1717, "text": "For that, we can use .concat, which is a function that accepts a list of data frames and concatenates them into one." }, { "code": null, "e": 1937, "s": 1834, "text": "# .concat to join the dataframes, like a 'union all'df_list = [df1, df2, df3]df = pd.concat(df_list)df" }, { "code": null, "e": 2033, "s": 1937, "text": "Cool, Pandas matched the columns and returned an almost perfect data frame without much effort." }, { "code": null, "e": 2110, "s": 2033, "text": "But what if the column names don’t match? or what if we’re missing a column?" }, { "code": null, "e": 2522, "s": 2110, "text": "# test with mismatching and missing columnsdf1 = pd.DataFrame( {'name': names[:3], 'specie': species[:3], 'age': age[:3]})df2 = pd.DataFrame( {'name': names[3:6], 'species': species[3:6], 'age': age[3:6]})df3 = pd.DataFrame( {'name': names[6:], 'age - years': age[6:]})print(df1, '\\n')print(df2, '\\n')print(df3)" }, { "code": null, "e": 2655, "s": 2522, "text": "For the ‘species’ column, I changed its name in the first df and removed it from the last; I’ve also renamed ‘age’ to ‘age — years’." }, { "code": null, "e": 2751, "s": 2655, "text": "# concat with mismatching and missing columnsdf_list = [df1, df2, df3]df = pd.concat(df_list)df" }, { "code": null, "e": 2925, "s": 2751, "text": "Ok, so Pandas .concat requires the names of the columns to be exact matches. If a column is unique to a dataset, just like a full join, it’ll fill the gaps with null values." }, { "code": null, "e": 2990, "s": 2925, "text": "There’s one more thing we need to pay attention to, the indexes." }, { "code": null, "e": 3164, "s": 2990, "text": "Since we didn’t define unique indexes when creating our data frame, Pandas set us with some default values starting from zero, but it doesn't reset them when we use .concat." }, { "code": null, "e": 3343, "s": 3164, "text": "A unique index is always a good idea. In this case, we can use .reset_index to create a new column with proper values or use .set_index to define one of the columns as the index." }, { "code": null, "e": 3402, "s": 3343, "text": "But let’s try an even simpler solution that fits our case." }, { "code": null, "e": 3938, "s": 3402, "text": "df1 = pd.DataFrame( {'name': names[:3], 'species': species[:3], 'age': age[:3]})df2 = pd.DataFrame( {'name': names[3:6], 'species': species[3:6], 'age': age[3:6]})df3 = pd.DataFrame( {'name': names[6:], 'species': species[6:], 'age': age[6:]})# since we didn't define the indexes when creating the dataframes we can ignore them when concatenatingdf_list = [df1, df2, df3]df = pd.concat(df_list, ignore_index=True)df" }, { "code": null, "e": 4031, "s": 3938, "text": "With a single parameter, we ignored the indexes and got new ones in the concatenated result." }, { "code": null, "e": 4134, "s": 4031, "text": "Another handy parameter is ‘keys’, which allows us to identify the data source with a new index level." }, { "code": null, "e": 4803, "s": 4134, "text": "df1 = pd.DataFrame( {'name': names[:3], 'species': species[:3], 'age': age[:3]}, index = [1,2,3])df2 = pd.DataFrame( {'name': names[3:6], 'species': species[3:6], 'age': age[3:6]}, index = [10,11,12])df3 = pd.DataFrame( {'name': names[6:], 'species': species[6:], 'age': age[6:]}, index = [100,200,300])# we can pass 'keys' which creates another index level to identify the concatenated data framesdf_list = [df1, df2, df3, df1]df = pd.concat(df_list, keys=['df1', 'df2', 'df3', 'df4'])df" }, { "code": null, "e": 4941, "s": 4803, "text": "By default, .concat uses the columns as keys and append the values as rows. But what if we want to concatenate columns to our data frame?" }, { "code": null, "e": 4994, "s": 4941, "text": "First, let’s define some new columns to concatenate." }, { "code": null, "e": 5094, "s": 4994, "text": "df4 = pd.DataFrame( {'weight': weight, 'color': color })df4" }, { "code": null, "e": 5195, "s": 5094, "text": "Similarly, we could add the lists directly to our data frame by assigning them to a column, like so:" }, { "code": null, "e": 5215, "s": 5195, "text": "df['color'] = color" }, { "code": null, "e": 5316, "s": 5215, "text": "But a data frame could have lots of fields, and passing them one by one wouldn’t be the best option." }, { "code": null, "e": 5428, "s": 5316, "text": "The concatenate function accepts a parameter for ‘axis’, which allows us to do just that — concatenate columns." }, { "code": null, "e": 5464, "s": 5428, "text": "df = pd.concat([df, df4], axis=1)df" }, { "code": null, "e": 5510, "s": 5464, "text": "We can also change the behaviour of the join." }, { "code": null, "e": 5625, "s": 5510, "text": "Let’s try making the ‘name’ column our index and creating another dataset with an extra column to experiment with." }, { "code": null, "e": 5889, "s": 5625, "text": "df_list = [df1, df2]df = pd.concat(df_list)df.set_index('name', inplace=True)df5 = pd.DataFrame( {'species': species, 'age': age, 'score': [9,10,10,8,6,9,3,4,10]}, index = names)print(df, '\\n')print(df5)" }, { "code": null, "e": 6040, "s": 5889, "text": "Note that our first data frame has fewer values than the second. When we perform an inner join, it should only bring the rows where the indexes match." }, { "code": null, "e": 6215, "s": 6040, "text": "# by default concat behaves like an outer join, or a union all# we can change that with the 'join' parameterdf_list = [df, df5]df = pd.concat(df_list, axis=1, join='inner')df" }, { "code": null, "e": 6273, "s": 6215, "text": "Now let’s have a look at another function called .append." }, { "code": null, "e": 6465, "s": 6273, "text": "This function has similar behaviour to .concat. The previous take multiple data frames and concatenates them into a new one. The append method will use an existing data frame to add the data." }, { "code": null, "e": 6587, "s": 6465, "text": "Both will return a data frame, but the way you call them is different. You’ll use Pandas.concat() and DataFrame.append()." }, { "code": null, "e": 6614, "s": 6587, "text": "Let’s check some examples." }, { "code": null, "e": 6630, "s": 6614, "text": "df1.append(df2)" }, { "code": null, "e": 6721, "s": 6630, "text": "df = df1.append(df2)df = df.append(df3)print(df, '\\n')df = df1.append([df2, df3])print(df)" }, { "code": null, "e": 6836, "s": 6721, "text": "# append a rowdf.append(pd.Series(['oliver', 'monkey', 13], index=['name', 'species', 'age']), ignore_index=True) " }, { "code": null, "e": 6972, "s": 6836, "text": "Awesome, with .concat and .append, we can perform most of the joins we might need. Now let’s check a more robust solution named .merge." }, { "code": null, "e": 7042, "s": 6972, "text": "Starting with something simple, let’s see how .merge performs a join." }, { "code": null, "e": 7159, "s": 7042, "text": "I’ll define another data frame similar to the one we’re already using, but with one more column and one less record." }, { "code": null, "e": 7312, "s": 7159, "text": "print(df, '\\n')df6 = pd.DataFrame( {'name': names[1:], 'age': age[1:], 'score': [10,10,8,6,9,3,4,10]})print(df6)" }, { "code": null, "e": 7400, "s": 7312, "text": "Merge allows us to select which column will be the key; in this case, let’s use ‘name’." }, { "code": null, "e": 7450, "s": 7400, "text": "merged_df = pd.merge(df, df6, on='name')merged_df" }, { "code": null, "e": 7606, "s": 7450, "text": "Unlike what we saw earlier, a merge is by default an inner join — That means unless told otherwise, it’ll only return the matching rows from both datasets." }, { "code": null, "e": 7724, "s": 7606, "text": "We can also notice that the columns present in both datasets are separated, even though they contain the same values." }, { "code": null, "e": 7840, "s": 7724, "text": "Lastly, when we perform an inner join like the above, both data frames must have the key column with the same name." }, { "code": null, "e": 7957, "s": 7840, "text": "You can select multiple columns as key, like a composite key, and you can also select which kind of join you’ll use." }, { "code": null, "e": 8028, "s": 7957, "text": "merged_df = pd.merge(df, df6, how='left', on=['name', 'age'])merged_df" }, { "code": null, "e": 8100, "s": 8028, "text": "merged_df = pd.merge(df6, df, how='right', on=['name', 'age'])merged_df" }, { "code": null, "e": 8208, "s": 8100, "text": "Great! Besides all that, the merge function also helps us to validate and understand the data were merging." }, { "code": null, "e": 8338, "s": 8208, "text": "# 'one_to_one' or ‘1:1’merged_df = pd.merge(df6, df.append(df1), how='right', on=['name', 'age'], validate='one_to_one')merged_df" }, { "code": null, "e": 8451, "s": 8338, "text": "For example, the validate parameter will raise an error if the data frames don’t respect the criteria you chose." }, { "code": null, "e": 8477, "s": 8451, "text": "Other useful options are:" }, { "code": null, "e": 8538, "s": 8477, "text": "‘one_to_many’ or ‘1:m’ — Checks if the left keys are unique;" }, { "code": null, "e": 8599, "s": 8538, "text": "‘many_to_one’ or ‘m:1’— Checks if the right keys are unique;" }, { "code": null, "e": 8692, "s": 8599, "text": "The ‘indicator’ parameter adds a column to the data frame explaining the keys' relationship." }, { "code": null, "e": 8792, "s": 8692, "text": "merged_df = pd.merge(df6, df.append(df1), how='outer', on=['name', 'age'], indicator=True)merged_df" }, { "code": null, "e": 8886, "s": 8792, "text": "*If you pass a string to the indicator parameter, it’ll be used as the created column's name." }, { "code": null, "e": 9001, "s": 8886, "text": "We don’t need to specify which column contains the key since, by default, Pandas will assume the index is the key." }, { "code": null, "e": 9078, "s": 9001, "text": "Let’s try setting the name as our index and merging those data frames again." }, { "code": null, "e": 9167, "s": 9078, "text": "df.set_index('name', inplace=True)df6.set_index('name', inplace=True)print(df)print(df6)" }, { "code": null, "e": 9185, "s": 9167, "text": "pd.merge(df6, df)" }, { "code": null, "e": 9287, "s": 9185, "text": "If we don’t want Pandas to reset the index, we have to use the right_index and left_index parameters." }, { "code": null, "e": 9353, "s": 9287, "text": "pd.merge(df6, df, how='outer', left_index=True, right_index=True)" }, { "code": null, "e": 9480, "s": 9353, "text": "If we want to merge with an index on one side and with a key on the other, we can specify the right_on and left_on parameters." }, { "code": null, "e": 9642, "s": 9480, "text": "They accept the column's name holding the key, just like we saw before, but will be applied only to that specific side, using the index column on the other side." }, { "code": null, "e": 9707, "s": 9642, "text": "pd.merge(df, df6, how='right', right_on='name', left_index=True)" }, { "code": null, "e": 9879, "s": 9707, "text": "Great! We got a look at .concat and .append, two convenient functions for joining two data frames. Then we explored .merge, an even better option with lots of flexibility." }, { "code": null, "e": 10098, "s": 9879, "text": "Pandas have even more methods to help you work with multiple datasets; it’s not unusual to spend time building the logic to solve your problem and then finding out an already implemented solution for that in a library." }, { "code": null, "e": 10215, "s": 10098, "text": "So I encourage you to get a look at some of those other functions such as .compare, .combine_first, and .merge_asof." }, { "code": null, "e": 10269, "s": 10215, "text": "Thanks for reading my article. I hope you enjoyed it!" } ]
How to eliminate repeated lines in a python function?
Let us name the given text file as bar.txt We use file handling methods in python to remove duplicate lines in python text file or function. The text file or function has to be in the same directory as the python program file. Following code is one way of removing duplicates in a text file bar.txt and the output is stored in foo.txt. These files should be in the same directory as the python script file, else it won’t work. The file bar.txt is as follows A cow is an animal. A cow is an animal. A buffalo too is an animal. Lion is the king of jungle. The code below removes the duplicate lines in bar.txt and stores in foo.txt # This program opens file bar.txt and removes duplicate lines and writes the # contents to foo.txt file. lines_seen = set() # holds lines already seen outfile = open('foo.txt', "w") infile = open('bar.txt', "r") print "The file bar.txt is as follows" for line in infile: print line if line not in lines_seen: # not a duplicate outfile.write(line) lines_seen.add(line) outfile.close() print "The file foo.txt is as follows" for line in open('foo.txt', "r"): print line The file foo.txt is as follows A cow is an animal. A buffalo too is an animal. Lion is the king of jungle.
[ { "code": null, "e": 1105, "s": 1062, "text": "Let us name the given text file as bar.txt" }, { "code": null, "e": 1489, "s": 1105, "text": "We use file handling methods in python to remove duplicate lines in python text file or function. The text file or function has to be in the same directory as the python program file. Following code is one way of removing duplicates in a text file bar.txt and the output is stored in foo.txt. These files should be in the same directory as the python script file, else it won’t work." }, { "code": null, "e": 1520, "s": 1489, "text": "The file bar.txt is as follows" }, { "code": null, "e": 1616, "s": 1520, "text": "A cow is an animal.\nA cow is an animal.\nA buffalo too is an animal.\nLion is the king of jungle." }, { "code": null, "e": 1692, "s": 1616, "text": "The code below removes the duplicate lines in bar.txt and stores in foo.txt" }, { "code": null, "e": 2191, "s": 1692, "text": "# This program opens file bar.txt and removes duplicate lines and writes the\n# contents to foo.txt file.\nlines_seen = set() # holds lines already seen\noutfile = open('foo.txt', \"w\")\ninfile = open('bar.txt', \"r\")\nprint \"The file bar.txt is as follows\"\nfor line in infile:\n print line\n if line not in lines_seen: # not a duplicate\n outfile.write(line)\n lines_seen.add(line)\noutfile.close()\nprint \"The file foo.txt is as follows\"\nfor line in open('foo.txt', \"r\"):\n print line\n" }, { "code": null, "e": 2222, "s": 2191, "text": "The file foo.txt is as follows" }, { "code": null, "e": 2298, "s": 2222, "text": "A cow is an animal.\nA buffalo too is an animal.\nLion is the king of jungle." } ]
Customizing Fonts in Flutter - GeeksforGeeks
11 Feb, 2021 Customization is everywhere, from documents to apps, we can customize everything as we want to. The power of customization is humongous, that it has revolutionized the way we look at technology in this world. Just like how printing “Hello World”, is the basic step towards learning a new programming language, customizing the style of a text is the basic step towards customizing an app. So, let’s see how to customize text in Flutter. In Flutter, everything is a widget. So, “Text” is a widget too. The text widget has its own properties like font style, font size, font-weight, etc. The Flutter team has set a few default properties prior to making things easier for the user in creating apps. So, customizing text is all about editing these properties as we want, to get the desired output. Now, let’s create a basic Flutter app with various default Text widget properties available. Dart // main.dart fileimport 'package:flutter/material.dart';import 'package:flutter/cupertino.dart'; void main() => runApp(MyApp()); // Create a stateless widgetclass MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text('Geeks for Geeks'), backgroundColor: Colors.green, ), body: SafeArea( child: Center( child: Text( 'Welcome to GFG!', style: TextStyle( fontSize: 40.0, color: Colors.green, fontWeight: FontWeight.bold, ), ), ), ), ), ); }} Output: A Font file has all the required details regarding a font family, so once imported the font style can be used throughout the app. Google Fonts website has a wide variety of font families that can be downloaded and used in an app. The steps for downloading the file is as follows: Step 1: Open Google Fonts and search for a font family in the search bar (here “Pacifico”). Step 2: Select the “Pacifico” font file. Step 3: To download, click the “Download Family” button. In order to use the downloaded font family, we need to import the font file into the root of the Flutter app. The steps for importing the font file in Android Studio is as follows: Step 1: Click the “Project” button in the top left corner of Android Studio. Step 2: Right-click on the project name, here “gfg_custom_fonts” and select New + Directory. Step 3: Name the directory as “fonts“. Step 4: Open file manager and go to downloads. Extract and open the “Pacifico” zip file. Step 5: Move the “Pacifico Regular” file into this directory. After moving, the font directory contains a file named “Pacifico-Regular.ttf”. Now after importing the font file, it’s a necessity to tell Flutter where to fetch the font file from. So, it’s a need to declare the font in a specific file named “pubspec.yaml” file. Indentation plays a major role in this file, where double-space is used to indent the code. The steps to declare the font file is as follows: Step 1: Click the “Project” button and click on the project name, here “gfg_custom_fonts”. Step 2: In the list, there is a file called “pubspec.yaml” file. Click this file. Step 3: Paste the below code in the pubspec.yaml file. Be aware of the indentations. Step 4: Press the “Pub get” button in the top right corner of the file. Dart // pubspec.yaml filename: gfgcustomfontsdescription: A new Flutter application.publish_to: 'none'version: 1.0.0+1 environment: sdk: ">=2.7.0 <3.0.0" dependencies: flutter: sdk: flutter cupertino_icons: ^0.1.3 dev_dependencies: flutter_test: sdk: flutter flutter: uses-material-design: true fonts: - family: Pacifico fonts: - asset: fonts/Pacifico-Regular.ttf Now this font family can be used in styling the text widget in the app wherever needed. Not only one, but multiple families can be downloaded in the above-mentioned steps. Note: The name mentioned in the “family:” of the “pubspec.yaml” file should be unique for different font families. In order to use this font, the font family property of the text widget is used in the .dart file. The syntax for it is as follows: Syntax: Text('text', style: TextStyle( fontFamily: 'family_name', ), ), The final code after customizing the text style is as follows: Dart // main.dart file after custom fontimport 'package:flutter/material.dart';import 'package:flutter/cupertino.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text('Geeks for Geeks'), backgroundColor: Colors.green, ), body: SafeArea( child: Center( child: Text( 'Welcome to GFG!', style: TextStyle( fontFamily: 'Pacifico', fontSize: 40.0, color: Colors.green, fontWeight: FontWeight.bold, ), ), ), ), ), ); }} Output: maitreyi sondhi Flutter Dart Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Listview.builder in Flutter Flutter - DropDownButton Widget Flutter - Asset Image Splash Screen in Flutter Flutter - Custom Bottom Navigation Bar Dart - Standard Input Output Getter and Setter Methods in Dart Flutter - Checkbox Widget Flutter - Row and Column Widgets How to Append or Concatenate Strings in Dart?
[ { "code": null, "e": 25549, "s": 25521, "text": "\n11 Feb, 2021" }, { "code": null, "e": 25985, "s": 25549, "text": "Customization is everywhere, from documents to apps, we can customize everything as we want to. The power of customization is humongous, that it has revolutionized the way we look at technology in this world. Just like how printing “Hello World”, is the basic step towards learning a new programming language, customizing the style of a text is the basic step towards customizing an app. So, let’s see how to customize text in Flutter." }, { "code": null, "e": 26343, "s": 25985, "text": "In Flutter, everything is a widget. So, “Text” is a widget too. The text widget has its own properties like font style, font size, font-weight, etc. The Flutter team has set a few default properties prior to making things easier for the user in creating apps. So, customizing text is all about editing these properties as we want, to get the desired output." }, { "code": null, "e": 26436, "s": 26343, "text": "Now, let’s create a basic Flutter app with various default Text widget properties available." }, { "code": null, "e": 26441, "s": 26436, "text": "Dart" }, { "code": "// main.dart fileimport 'package:flutter/material.dart';import 'package:flutter/cupertino.dart'; void main() => runApp(MyApp()); // Create a stateless widgetclass MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text('Geeks for Geeks'), backgroundColor: Colors.green, ), body: SafeArea( child: Center( child: Text( 'Welcome to GFG!', style: TextStyle( fontSize: 40.0, color: Colors.green, fontWeight: FontWeight.bold, ), ), ), ), ), ); }}", "e": 27158, "s": 26441, "text": null }, { "code": null, "e": 27169, "s": 27161, "text": "Output:" }, { "code": null, "e": 27453, "s": 27173, "text": "A Font file has all the required details regarding a font family, so once imported the font style can be used throughout the app. Google Fonts website has a wide variety of font families that can be downloaded and used in an app. The steps for downloading the file is as follows:" }, { "code": null, "e": 27547, "s": 27455, "text": "Step 1: Open Google Fonts and search for a font family in the search bar (here “Pacifico”)." }, { "code": null, "e": 27588, "s": 27547, "text": "Step 2: Select the “Pacifico” font file." }, { "code": null, "e": 27645, "s": 27588, "text": "Step 3: To download, click the “Download Family” button." }, { "code": null, "e": 27828, "s": 27647, "text": "In order to use the downloaded font family, we need to import the font file into the root of the Flutter app. The steps for importing the font file in Android Studio is as follows:" }, { "code": null, "e": 27907, "s": 27830, "text": "Step 1: Click the “Project” button in the top left corner of Android Studio." }, { "code": null, "e": 28000, "s": 27907, "text": "Step 2: Right-click on the project name, here “gfg_custom_fonts” and select New + Directory." }, { "code": null, "e": 28039, "s": 28000, "text": "Step 3: Name the directory as “fonts“." }, { "code": null, "e": 28128, "s": 28039, "text": "Step 4: Open file manager and go to downloads. Extract and open the “Pacifico” zip file." }, { "code": null, "e": 28269, "s": 28128, "text": "Step 5: Move the “Pacifico Regular” file into this directory. After moving, the font directory contains a file named “Pacifico-Regular.ttf”." }, { "code": null, "e": 28598, "s": 28271, "text": "Now after importing the font file, it’s a necessity to tell Flutter where to fetch the font file from. So, it’s a need to declare the font in a specific file named “pubspec.yaml” file. Indentation plays a major role in this file, where double-space is used to indent the code. The steps to declare the font file is as follows:" }, { "code": null, "e": 28691, "s": 28600, "text": "Step 1: Click the “Project” button and click on the project name, here “gfg_custom_fonts”." }, { "code": null, "e": 28774, "s": 28691, "text": "Step 2: In the list, there is a file called “pubspec.yaml” file. Click this file." }, { "code": null, "e": 28859, "s": 28774, "text": "Step 3: Paste the below code in the pubspec.yaml file. Be aware of the indentations." }, { "code": null, "e": 28931, "s": 28859, "text": "Step 4: Press the “Pub get” button in the top right corner of the file." }, { "code": null, "e": 28938, "s": 28933, "text": "Dart" }, { "code": "// pubspec.yaml filename: gfgcustomfontsdescription: A new Flutter application.publish_to: 'none'version: 1.0.0+1 environment: sdk: \">=2.7.0 <3.0.0\" dependencies: flutter: sdk: flutter cupertino_icons: ^0.1.3 dev_dependencies: flutter_test: sdk: flutter flutter: uses-material-design: true fonts: - family: Pacifico fonts: - asset: fonts/Pacifico-Regular.ttf", "e": 29326, "s": 28938, "text": null }, { "code": null, "e": 29504, "s": 29331, "text": "Now this font family can be used in styling the text widget in the app wherever needed. Not only one, but multiple families can be downloaded in the above-mentioned steps. " }, { "code": null, "e": 29752, "s": 29506, "text": "Note: The name mentioned in the “family:” of the “pubspec.yaml” file should be unique for different font families. In order to use this font, the font family property of the text widget is used in the .dart file. The syntax for it is as follows:" }, { "code": null, "e": 29878, "s": 29754, "text": "Syntax:\nText('text',\n style: TextStyle(\n fontFamily: 'family_name',\n ),\n )," }, { "code": null, "e": 29943, "s": 29880, "text": "The final code after customizing the text style is as follows:" }, { "code": null, "e": 29950, "s": 29945, "text": "Dart" }, { "code": "// main.dart file after custom fontimport 'package:flutter/material.dart';import 'package:flutter/cupertino.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text('Geeks for Geeks'), backgroundColor: Colors.green, ), body: SafeArea( child: Center( child: Text( 'Welcome to GFG!', style: TextStyle( fontFamily: 'Pacifico', fontSize: 40.0, color: Colors.green, fontWeight: FontWeight.bold, ), ), ), ), ), ); }}", "e": 30696, "s": 29950, "text": null }, { "code": null, "e": 30707, "s": 30699, "text": "Output:" }, { "code": null, "e": 30733, "s": 30717, "text": "maitreyi sondhi" }, { "code": null, "e": 30741, "s": 30733, "text": "Flutter" }, { "code": null, "e": 30746, "s": 30741, "text": "Dart" }, { "code": null, "e": 30844, "s": 30746, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30853, "s": 30844, "text": "Comments" }, { "code": null, "e": 30866, "s": 30853, "text": "Old Comments" }, { "code": null, "e": 30894, "s": 30866, "text": "Listview.builder in Flutter" }, { "code": null, "e": 30926, "s": 30894, "text": "Flutter - DropDownButton Widget" }, { "code": null, "e": 30948, "s": 30926, "text": "Flutter - Asset Image" }, { "code": null, "e": 30973, "s": 30948, "text": "Splash Screen in Flutter" }, { "code": null, "e": 31012, "s": 30973, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 31041, "s": 31012, "text": "Dart - Standard Input Output" }, { "code": null, "e": 31075, "s": 31041, "text": "Getter and Setter Methods in Dart" }, { "code": null, "e": 31101, "s": 31075, "text": "Flutter - Checkbox Widget" }, { "code": null, "e": 31134, "s": 31101, "text": "Flutter - Row and Column Widgets" } ]
Stock predictions with Transformer and Time Embeddings | Towards Data Science
In my previous post, I have shared my first research results for predicting stock prices which will be subsequently used as input for a deep learning trading bot. While upscaling my datasets to thousands of equity tickers equating to almost 1 Terabyte of stock price histories and news articles, I have come to realize that my initial approach of working with neural networks that are comprised of LSTM(Long-Short Term Memory Models) and CNN (Convolutional Neural Network) components has its limitations. Thus, to overcome the limitations I had to implement a Transformer, specialized for stock time-series. In recent years Transformers have gained popularity due to their outstanding performance. Combining the self-attention mechanism, parallelization, and positional encoding under one hood provides usually an edge over classical LSTM and CNN models when working on tasks where semantic feature extraction and large datasets are required [1]. Since I was not able to find a simple Transformer implementation which is customized for time-series sequences that have multiple features e.g. the (Open, High, Low, Close, Volume) features of our stock data I had to implement it myself. In this post, I’ll be sharing my Transformer architecture for stock data as well as what Time Embeddings are and why it essential to use them in combination with time-series. For the explanatory purpose of this article, we will be using the IBM stock price history as a simplified version of the 1 Terabyte stock dataset. Nonetheless, you can easily apply to code in this article to a significantly larger dataset. The IBM dataset starts on the 1962–01–02, ends on the date 2020–05–24 and contains in total 14699 trading days. Additionally, for every training day, we have the Open, High, Low, and Close price as well as the trading Volume (OHLCV) of the IBM stock. The price and volume features are converted into daily stock returns and daily volume changes, a min-max normalized is applied and the time-series is split into a training, validation, and test set. Converting stock prices and volumes into daily change rates increases the stationarity of our dataset. Thus the learnings a model derives from our dataset have a higher validity for future predictions. Here an overview of how the transformed data looks like. Lastly, the training, validation, and test sets are separated into individual sequences with a length of 128 days each. For each sequence day, the 4 price features (Open, High, Low, Close) and the Volume feature are present, resulting in 5 features per day. During a single training step, our Transformer model will receive 32 sequences (batch_size = 32) that are 128 days long (seq_len=128) and have 5 features per day as input. As the first step of our Transformer implementation, we have to consider how to encode the notion of time which is hidden in our stock prices into our model. When processing time-series data, time is an essential feature. However, when processing time-series/sequential data with a Transformer, sequences are forwarded all at once through the Transformer architecture, making it difficult to extract temporal/sequential dependencies. Thus, Transformers that are used in combination with natural language data tend to utilize positional encoding to provide a notion of word order to the model. In detail, the positional encoding is a representation of a word’s value and its position in a sentence, allowing the Transformer to obtain knowledge about a sentence structure and word interdependencies. An example of positional encoding can be found when looking under the hood of the BERT [2] model, which has achieved state-of-the-art performance for many language tasks. Similarly, a Transformer requires a notion of time when processing our stock prices. Without Time Embeddings, our Transformer would not receive any information about the temporal order of our stock prices. Hence, a stock price from 2020 can have the same influence on tomorrows’ price prediction as a price from the year 1990. And of course, this would be ludicrous. In order to overcome a Transformer’s temporal indifferences, we will implement the approach described in the paper Time2Vec: Learning a Vector Representation of Time [2]. The authors of the paper propose “a model-agnostic vector representation for time, called Time2Vec”. You can think of a vector representation just like a normal embedding layer that can be added to a neural network architecture to improve a model’s performance. Boiling the paper down to its essentials, there are two main ideas to consider. Firstly, the authors identified that a meaningful representation of time has to include both periodic and non-periodic patterns. An example of a periodic pattern is the weather that varies over different seasons. In contrast, an example of a non-periodic pattern would be a disease, which occurs with a high probability, the older a patient. Secondly, a time representation should have an invariance to time rescaling, meaning that the time representation is not affected by different time increments e.g. (days, hours or seconds) and long time horizons. Combining the ideas of periodic and non-periodic patterns as well as the invariance to time rescaling we are presented by the following mathematical definition. No worries, it is easier than it looks and I’ll explain it in detail. 😉 The time vector/representation t2v is comprised of two components, where ωiτ + φi represents the non-periodic/linear and F(ωiτ + φi) the periodic feature of the time vector. Rewriting t2v(τ) = ωiτ + φi in a simpler way, the new version y = mix + bi should look familiar since it is the vanilla version of a linear function that you know from high school. ω in ωiτ + φi is a matrix that defines the slope of our time-series τ and φ in simple terms is a matrix that defines where our time-series τ intersects with the y-axis. Hence, ωiτ + φi is nothing more than a linear function. The second component F(ωiτ + φi) represents the periodic feature of the time vector. Just like before we have the linear term ωiτ + φi again, however, this time the linear function is wrapped in an additional function F(). The authors experimented with different functions to best describe a periodic relationship (sigmoid, tanh, ReLU, mod, triangle, etc.). In the end, a sine-function achieved the best and most stable performance (cosine achieved similar results). When combining the linear function ωiτ + φi with a sine function the 2D representation looks as follows. φ shifts the sine function along the x-axis and ω determines the wavelength of the sine function. Let’s have a look at an overview of how the accuracy of an LSTM network in combination with different non-linear functions of the time vector (Time2vec) changes. We can clearly see that the ReLU function performs the worst, in contrast, the sine function outperforms every other non-linear function. The reason, the ReLU function has such an unsatisfying results is that a ReLU function is not invariant to time rescaling. The higher the invariant of a function to time rescaling the better the performance. Before we start implementing the time embedding let’s take look at the performance difference of a normal LSTM network (blue) and an LSTM+Time2Vec network (red). As you can see the proposed time vector leads across multiple datasets never to worse performance and almost always improves a model’s performance. Equipped with these insights we move on to the implementation. Ok, we have discussed how the periodic and non-periodic components of our time vector work in theory, now we’ll implement them in code. In order for the time vector to be easily integrated in any kind of neural network architecture, we’ll define the vector as a Keras layer. Our custom Time2Vector Layer has two sub-functions def build(): and def call():. In def build(): we initiate 4 matrices, 2 for ω and 2 forφ since we need aω and φ matrix for both non-periodical (linear) and the periodical (sin) features. seq_len = 128def build(input_shape): weights_linear = add_weight(shape=(seq_len), trainable=True) bias_linear = add_weight(shape=(seq_len), trainable=True) weights_periodic = add_weight(shape=(seq_len), trainable=True) bias_periodic = add_weight(shape=(seq_len), trainable=True) After having initiated our 4 matrices we define the calculation steps that will be performed once the layer is called, hence the def call(): function. The input which will be received by the Time2Vector layer has the following shape (batch_size, seq_len, 5) → (32, 128, 5). The batch_size defines how many stock price sequences we want to feed into the model/layer at once. The seq_len parameter determines the length of a single stock price sequence. Lastly, the number 5 is derived from the fact that we have 5 features of the daily IBM stock recording (Open price, High price, Low price, Close price, Volume). The first calculation step excludes the Volume and takes an average across the Open, High, Low, and Close prices, resulting in the shape (batch_size, seq_len) . x = tf.math.reduce_mean(x[:,:,:4], axis=-1) Next, we calculate the non-periodic (linear) time feature and expand the dimension by 1 again. (batch_size, seq_len, 1) time_linear = weights_linear * x + bias_lineartime_linear = tf.expand_dims(time_linear, axis=-1) The same process is repeated for the periodic time feature, also resulting in the same matrix shape. (batch_size, seq_len, 1) time_periodic = tf.math.sin(tf.multiply(x, weights_periodic) + bias_periodic)time_periodic = tf.expand_dims(time_periodic, axis=-1) The last step that is needed to conclude the time vector calculation is concatenating the linear and periodic time feature. (batch_size, seq_len, 2) time_vector = tf.concat([time_linear, time_periodic], axis=-1) Combining all steps into one Layer function the code looks as follows. Now we know that it is important to provide a notion of time and how to implement a time vector, the next step will be the Transformer. A Transformer is a neural network architecture that uses a self-attention mechanism, allowing the model to focus on the relevant parts of the time-series to improve prediction qualities. The self-attention mechanism consists of a Single-Head Attention and Multi-Head Attention layer. The self-attention mechanism is able to connect all time-series steps with each other at once, leading to the creation of long-term dependency understandings. Finally, all these processes are parallelized within the Transformer architecture, allowing an acceleration of the learning process. After having implemented the Time Embeddings we will be using the time vector in combination with IBM’s price and volume features as input for our Transformer. The Time2Vector layer receives the IBM price and volume features as input and calculates the non-periodic and periodic time features. In the subsequent model step, the calculated time features are concatenated with the price and volume features forming a matrix, with the shape (32, 128, 7). The IBM time-series plus the time features which we just calculated, form the initial input to the first single-head attention layer. The single-head attention layer takes 3 inputs (Query, Key, Value) in total. For us, each Query, Key, and Value input is representative of the IBM price, volume, and time features. Each Query, Key, and Value input receives a separate linear transformation by going through individual dense layers. Providing the dense layers with 96 output cells was a personal architectural choice. After the initial linear transformation, we will calculate the attention score/weights. The attention weights determine how much focus is placed on individual time-series steps when predicting a future stock price. Attention weights are calculated by taking the dot-product of the linearly transformed Query and Key inputs, whereas the transformed Key input has been transposed to make the dot-product multiplication feasible. Then the dot-product is divided by the dimension size of the previous dense layers (96), to avoid exploding gradients. The divided dot-product then goes through the softmax function to yield a set of weights that sum up 1. As the last step, the calculated softmax matrix which determines the focus of each time step is multiplied with the transformed v matrix which concludes the single-head attention mechanism. Since illustrations are great for first initial learnings but lack the implementation aspect, I have prepared a clean SingleAttention Keras layer function for you guys 🙂. To further improve the self-attention mechanism the authors of the paper Attention Is All You Need [4] proposed the implementation of multi-head attention. The functionality of a multi-head attention layer is to concatenate the attention weights of n single-head attention layers and then apply a non-linear transformation with a Dense layer. The illustration below shows the concatenation of 3 single-head layers. Having the output of n single-head layers allows the encoding of multiple independent single-head layers transformation into the model. Hence, the model is able to focus on multiple time-series steps at once. Increasing the number of attention heads impacts a model’s ability to capture long-distance dependencies positively. [1] The same as above, a clean implementation of the multi-head attention layer. The single- and multi-head attention mechanisms (self-attention) are now aggregated into a transformer encoder layer. Each encoder layer incorporates a self-attention sublayer and a feedforward sublayer. The feedforward sublayer consists of two dense layers with ReLU activation in between. On a side note, the dense layers can be replaced with 1-dimensional convolutional layers if the Conv-layers have a kernel size and stride of 1. The math of a dense layer and a convolutional layer with the described configuration is the same. Each sublayer is followed by a dropout layer, after the dropout, a residual connection is formed by adding the initial Query input to both sublayer outputs. Concluding each sublayer a normalization layer placed after the residual connection addition to stabilize and accelerate the training process. Now we have a ready to use Transformer layer, which can be easily stacked to improve a model’s performance. Since we do not need any Transformer decoder layers our implemented Transformer architecture is very similar to the BERT [2] architecture. Although, the differences are the time embeddings and our transformer can handle a 3-dimensional time-series instead of a simple 2-dimensional sequence. If you want to dive into the code instead, here we go. In conclusion, we first initialize the time embedding layer as well as 3 Transformer encoder layers. After the initialization, we stack a regression head onto the last transformer layer and the training process begins. The training process has a total number of 35 epochs. After the training, we can see that our transform model is just predicting a flat line that is centered in between the daily stock price changes. When only using the IBM stock history even a transformer model is merely capable of predicting the linear trend of a stock’s development. Concluding that the historical price and volume data of a stock does only contain enough explanatory value for a linear trend prediction. However, when upscaling the dataset to thousands of stock tickers (1 Terabyte dataset) the results, look quite different 🙂. As shown above, even the most advanced model architectures are not able to extract non-linear stock predictions from historical stock prices and volumes. However, when applying a simple moving average smoothing effect on the data (window size=10), the model is able to provide significantly better predictions (green line). Instead of predicting the linear trend of the IBM stock, the model is able to predict the up and downs, too. However, when observing carefully you can still see that the model has a large prediction delta on days with extreme daily change rate, hence we can conclude that we still have issues with outliers. The disadvantage of applying a moving average effect is that the new dataset is not reflecting our original data anymore. Hence the predictions with the moving average effect cannot be used as input for our trading bot. The performance increases due to the smoothing of the moving average effect can be achieved however without applying a moving average though. My latest research has shown that when extending the dataset to a large magnitude of stocks the same performance can be obtained. All the code that has been presented in this article is part of a notebook that can be run end-to-end. The notebook can be found on GitHub. Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details. Thank you, Jan None of the content presented in this article constitutes a recommendation that any particular security, portfolio of securities, transaction, or investment strategy is suitable for any specific person. Futures, stocks, and options trading involves substantial risk of loss and is not suitable for every investor. The valuation of futures, stocks, and options may fluctuate, and, as a result, clients may lose more than their original investment. [1] Why Self-Attention? A Targeted Evaluation of Neural Machine Translation Architectures https://arxiv.org/abs/1808.08946 [2] BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding https://arxiv.org/abs/1810.04805 [3] Time2Vec: Learning a Vector Representation of Time https://arxiv.org/abs/1907.05321 [4] Attention Is All You Need https://arxiv.org/abs/1706.03762
[ { "code": null, "e": 779, "s": 171, "text": "In my previous post, I have shared my first research results for predicting stock prices which will be subsequently used as input for a deep learning trading bot. While upscaling my datasets to thousands of equity tickers equating to almost 1 Terabyte of stock price histories and news articles, I have come to realize that my initial approach of working with neural networks that are comprised of LSTM(Long-Short Term Memory Models) and CNN (Convolutional Neural Network) components has its limitations. Thus, to overcome the limitations I had to implement a Transformer, specialized for stock time-series." }, { "code": null, "e": 1118, "s": 779, "text": "In recent years Transformers have gained popularity due to their outstanding performance. Combining the self-attention mechanism, parallelization, and positional encoding under one hood provides usually an edge over classical LSTM and CNN models when working on tasks where semantic feature extraction and large datasets are required [1]." }, { "code": null, "e": 1531, "s": 1118, "text": "Since I was not able to find a simple Transformer implementation which is customized for time-series sequences that have multiple features e.g. the (Open, High, Low, Close, Volume) features of our stock data I had to implement it myself. In this post, I’ll be sharing my Transformer architecture for stock data as well as what Time Embeddings are and why it essential to use them in combination with time-series." }, { "code": null, "e": 2022, "s": 1531, "text": "For the explanatory purpose of this article, we will be using the IBM stock price history as a simplified version of the 1 Terabyte stock dataset. Nonetheless, you can easily apply to code in this article to a significantly larger dataset. The IBM dataset starts on the 1962–01–02, ends on the date 2020–05–24 and contains in total 14699 trading days. Additionally, for every training day, we have the Open, High, Low, and Close price as well as the trading Volume (OHLCV) of the IBM stock." }, { "code": null, "e": 2480, "s": 2022, "text": "The price and volume features are converted into daily stock returns and daily volume changes, a min-max normalized is applied and the time-series is split into a training, validation, and test set. Converting stock prices and volumes into daily change rates increases the stationarity of our dataset. Thus the learnings a model derives from our dataset have a higher validity for future predictions. Here an overview of how the transformed data looks like." }, { "code": null, "e": 2910, "s": 2480, "text": "Lastly, the training, validation, and test sets are separated into individual sequences with a length of 128 days each. For each sequence day, the 4 price features (Open, High, Low, Close) and the Volume feature are present, resulting in 5 features per day. During a single training step, our Transformer model will receive 32 sequences (batch_size = 32) that are 128 days long (seq_len=128) and have 5 features per day as input." }, { "code": null, "e": 3068, "s": 2910, "text": "As the first step of our Transformer implementation, we have to consider how to encode the notion of time which is hidden in our stock prices into our model." }, { "code": null, "e": 3879, "s": 3068, "text": "When processing time-series data, time is an essential feature. However, when processing time-series/sequential data with a Transformer, sequences are forwarded all at once through the Transformer architecture, making it difficult to extract temporal/sequential dependencies. Thus, Transformers that are used in combination with natural language data tend to utilize positional encoding to provide a notion of word order to the model. In detail, the positional encoding is a representation of a word’s value and its position in a sentence, allowing the Transformer to obtain knowledge about a sentence structure and word interdependencies. An example of positional encoding can be found when looking under the hood of the BERT [2] model, which has achieved state-of-the-art performance for many language tasks." }, { "code": null, "e": 4246, "s": 3879, "text": "Similarly, a Transformer requires a notion of time when processing our stock prices. Without Time Embeddings, our Transformer would not receive any information about the temporal order of our stock prices. Hence, a stock price from 2020 can have the same influence on tomorrows’ price prediction as a price from the year 1990. And of course, this would be ludicrous." }, { "code": null, "e": 4679, "s": 4246, "text": "In order to overcome a Transformer’s temporal indifferences, we will implement the approach described in the paper Time2Vec: Learning a Vector Representation of Time [2]. The authors of the paper propose “a model-agnostic vector representation for time, called Time2Vec”. You can think of a vector representation just like a normal embedding layer that can be added to a neural network architecture to improve a model’s performance." }, { "code": null, "e": 5101, "s": 4679, "text": "Boiling the paper down to its essentials, there are two main ideas to consider. Firstly, the authors identified that a meaningful representation of time has to include both periodic and non-periodic patterns. An example of a periodic pattern is the weather that varies over different seasons. In contrast, an example of a non-periodic pattern would be a disease, which occurs with a high probability, the older a patient." }, { "code": null, "e": 5314, "s": 5101, "text": "Secondly, a time representation should have an invariance to time rescaling, meaning that the time representation is not affected by different time increments e.g. (days, hours or seconds) and long time horizons." }, { "code": null, "e": 5547, "s": 5314, "text": "Combining the ideas of periodic and non-periodic patterns as well as the invariance to time rescaling we are presented by the following mathematical definition. No worries, it is easier than it looks and I’ll explain it in detail. 😉" }, { "code": null, "e": 5721, "s": 5547, "text": "The time vector/representation t2v is comprised of two components, where ωiτ + φi represents the non-periodic/linear and F(ωiτ + φi) the periodic feature of the time vector." }, { "code": null, "e": 6127, "s": 5721, "text": "Rewriting t2v(τ) = ωiτ + φi in a simpler way, the new version y = mix + bi should look familiar since it is the vanilla version of a linear function that you know from high school. ω in ωiτ + φi is a matrix that defines the slope of our time-series τ and φ in simple terms is a matrix that defines where our time-series τ intersects with the y-axis. Hence, ωiτ + φi is nothing more than a linear function." }, { "code": null, "e": 6797, "s": 6127, "text": "The second component F(ωiτ + φi) represents the periodic feature of the time vector. Just like before we have the linear term ωiτ + φi again, however, this time the linear function is wrapped in an additional function F(). The authors experimented with different functions to best describe a periodic relationship (sigmoid, tanh, ReLU, mod, triangle, etc.). In the end, a sine-function achieved the best and most stable performance (cosine achieved similar results). When combining the linear function ωiτ + φi with a sine function the 2D representation looks as follows. φ shifts the sine function along the x-axis and ω determines the wavelength of the sine function." }, { "code": null, "e": 7305, "s": 6797, "text": "Let’s have a look at an overview of how the accuracy of an LSTM network in combination with different non-linear functions of the time vector (Time2vec) changes. We can clearly see that the ReLU function performs the worst, in contrast, the sine function outperforms every other non-linear function. The reason, the ReLU function has such an unsatisfying results is that a ReLU function is not invariant to time rescaling. The higher the invariant of a function to time rescaling the better the performance." }, { "code": null, "e": 7678, "s": 7305, "text": "Before we start implementing the time embedding let’s take look at the performance difference of a normal LSTM network (blue) and an LSTM+Time2Vec network (red). As you can see the proposed time vector leads across multiple datasets never to worse performance and almost always improves a model’s performance. Equipped with these insights we move on to the implementation." }, { "code": null, "e": 8191, "s": 7678, "text": "Ok, we have discussed how the periodic and non-periodic components of our time vector work in theory, now we’ll implement them in code. In order for the time vector to be easily integrated in any kind of neural network architecture, we’ll define the vector as a Keras layer. Our custom Time2Vector Layer has two sub-functions def build(): and def call():. In def build(): we initiate 4 matrices, 2 for ω and 2 forφ since we need aω and φ matrix for both non-periodical (linear) and the periodical (sin) features." }, { "code": null, "e": 8478, "s": 8191, "text": "seq_len = 128def build(input_shape): weights_linear = add_weight(shape=(seq_len), trainable=True) bias_linear = add_weight(shape=(seq_len), trainable=True) weights_periodic = add_weight(shape=(seq_len), trainable=True) bias_periodic = add_weight(shape=(seq_len), trainable=True)" }, { "code": null, "e": 8629, "s": 8478, "text": "After having initiated our 4 matrices we define the calculation steps that will be performed once the layer is called, hence the def call(): function." }, { "code": null, "e": 9091, "s": 8629, "text": "The input which will be received by the Time2Vector layer has the following shape (batch_size, seq_len, 5) → (32, 128, 5). The batch_size defines how many stock price sequences we want to feed into the model/layer at once. The seq_len parameter determines the length of a single stock price sequence. Lastly, the number 5 is derived from the fact that we have 5 features of the daily IBM stock recording (Open price, High price, Low price, Close price, Volume)." }, { "code": null, "e": 9252, "s": 9091, "text": "The first calculation step excludes the Volume and takes an average across the Open, High, Low, and Close prices, resulting in the shape (batch_size, seq_len) ." }, { "code": null, "e": 9296, "s": 9252, "text": "x = tf.math.reduce_mean(x[:,:,:4], axis=-1)" }, { "code": null, "e": 9416, "s": 9296, "text": "Next, we calculate the non-periodic (linear) time feature and expand the dimension by 1 again. (batch_size, seq_len, 1)" }, { "code": null, "e": 9513, "s": 9416, "text": "time_linear = weights_linear * x + bias_lineartime_linear = tf.expand_dims(time_linear, axis=-1)" }, { "code": null, "e": 9639, "s": 9513, "text": "The same process is repeated for the periodic time feature, also resulting in the same matrix shape. (batch_size, seq_len, 1)" }, { "code": null, "e": 9771, "s": 9639, "text": "time_periodic = tf.math.sin(tf.multiply(x, weights_periodic) + bias_periodic)time_periodic = tf.expand_dims(time_periodic, axis=-1)" }, { "code": null, "e": 9920, "s": 9771, "text": "The last step that is needed to conclude the time vector calculation is concatenating the linear and periodic time feature. (batch_size, seq_len, 2)" }, { "code": null, "e": 9983, "s": 9920, "text": "time_vector = tf.concat([time_linear, time_periodic], axis=-1)" }, { "code": null, "e": 10054, "s": 9983, "text": "Combining all steps into one Layer function the code looks as follows." }, { "code": null, "e": 10766, "s": 10054, "text": "Now we know that it is important to provide a notion of time and how to implement a time vector, the next step will be the Transformer. A Transformer is a neural network architecture that uses a self-attention mechanism, allowing the model to focus on the relevant parts of the time-series to improve prediction qualities. The self-attention mechanism consists of a Single-Head Attention and Multi-Head Attention layer. The self-attention mechanism is able to connect all time-series steps with each other at once, leading to the creation of long-term dependency understandings. Finally, all these processes are parallelized within the Transformer architecture, allowing an acceleration of the learning process." }, { "code": null, "e": 11218, "s": 10766, "text": "After having implemented the Time Embeddings we will be using the time vector in combination with IBM’s price and volume features as input for our Transformer. The Time2Vector layer receives the IBM price and volume features as input and calculates the non-periodic and periodic time features. In the subsequent model step, the calculated time features are concatenated with the price and volume features forming a matrix, with the shape (32, 128, 7)." }, { "code": null, "e": 11735, "s": 11218, "text": "The IBM time-series plus the time features which we just calculated, form the initial input to the first single-head attention layer. The single-head attention layer takes 3 inputs (Query, Key, Value) in total. For us, each Query, Key, and Value input is representative of the IBM price, volume, and time features. Each Query, Key, and Value input receives a separate linear transformation by going through individual dense layers. Providing the dense layers with 96 output cells was a personal architectural choice." }, { "code": null, "e": 12575, "s": 11735, "text": "After the initial linear transformation, we will calculate the attention score/weights. The attention weights determine how much focus is placed on individual time-series steps when predicting a future stock price. Attention weights are calculated by taking the dot-product of the linearly transformed Query and Key inputs, whereas the transformed Key input has been transposed to make the dot-product multiplication feasible. Then the dot-product is divided by the dimension size of the previous dense layers (96), to avoid exploding gradients. The divided dot-product then goes through the softmax function to yield a set of weights that sum up 1. As the last step, the calculated softmax matrix which determines the focus of each time step is multiplied with the transformed v matrix which concludes the single-head attention mechanism." }, { "code": null, "e": 12746, "s": 12575, "text": "Since illustrations are great for first initial learnings but lack the implementation aspect, I have prepared a clean SingleAttention Keras layer function for you guys 🙂." }, { "code": null, "e": 13161, "s": 12746, "text": "To further improve the self-attention mechanism the authors of the paper Attention Is All You Need [4] proposed the implementation of multi-head attention. The functionality of a multi-head attention layer is to concatenate the attention weights of n single-head attention layers and then apply a non-linear transformation with a Dense layer. The illustration below shows the concatenation of 3 single-head layers." }, { "code": null, "e": 13491, "s": 13161, "text": "Having the output of n single-head layers allows the encoding of multiple independent single-head layers transformation into the model. Hence, the model is able to focus on multiple time-series steps at once. Increasing the number of attention heads impacts a model’s ability to capture long-distance dependencies positively. [1]" }, { "code": null, "e": 13568, "s": 13491, "text": "The same as above, a clean implementation of the multi-head attention layer." }, { "code": null, "e": 13859, "s": 13568, "text": "The single- and multi-head attention mechanisms (self-attention) are now aggregated into a transformer encoder layer. Each encoder layer incorporates a self-attention sublayer and a feedforward sublayer. The feedforward sublayer consists of two dense layers with ReLU activation in between." }, { "code": null, "e": 14101, "s": 13859, "text": "On a side note, the dense layers can be replaced with 1-dimensional convolutional layers if the Conv-layers have a kernel size and stride of 1. The math of a dense layer and a convolutional layer with the described configuration is the same." }, { "code": null, "e": 14401, "s": 14101, "text": "Each sublayer is followed by a dropout layer, after the dropout, a residual connection is formed by adding the initial Query input to both sublayer outputs. Concluding each sublayer a normalization layer placed after the residual connection addition to stabilize and accelerate the training process." }, { "code": null, "e": 14801, "s": 14401, "text": "Now we have a ready to use Transformer layer, which can be easily stacked to improve a model’s performance. Since we do not need any Transformer decoder layers our implemented Transformer architecture is very similar to the BERT [2] architecture. Although, the differences are the time embeddings and our transformer can handle a 3-dimensional time-series instead of a simple 2-dimensional sequence." }, { "code": null, "e": 14856, "s": 14801, "text": "If you want to dive into the code instead, here we go." }, { "code": null, "e": 15075, "s": 14856, "text": "In conclusion, we first initialize the time embedding layer as well as 3 Transformer encoder layers. After the initialization, we stack a regression head onto the last transformer layer and the training process begins." }, { "code": null, "e": 15675, "s": 15075, "text": "The training process has a total number of 35 epochs. After the training, we can see that our transform model is just predicting a flat line that is centered in between the daily stock price changes. When only using the IBM stock history even a transformer model is merely capable of predicting the linear trend of a stock’s development. Concluding that the historical price and volume data of a stock does only contain enough explanatory value for a linear trend prediction. However, when upscaling the dataset to thousands of stock tickers (1 Terabyte dataset) the results, look quite different 🙂." }, { "code": null, "e": 16307, "s": 15675, "text": "As shown above, even the most advanced model architectures are not able to extract non-linear stock predictions from historical stock prices and volumes. However, when applying a simple moving average smoothing effect on the data (window size=10), the model is able to provide significantly better predictions (green line). Instead of predicting the linear trend of the IBM stock, the model is able to predict the up and downs, too. However, when observing carefully you can still see that the model has a large prediction delta on days with extreme daily change rate, hence we can conclude that we still have issues with outliers." }, { "code": null, "e": 16527, "s": 16307, "text": "The disadvantage of applying a moving average effect is that the new dataset is not reflecting our original data anymore. Hence the predictions with the moving average effect cannot be used as input for our trading bot." }, { "code": null, "e": 16799, "s": 16527, "text": "The performance increases due to the smoothing of the moving average effect can be achieved however without applying a moving average though. My latest research has shown that when extending the dataset to a large magnitude of stocks the same performance can be obtained." }, { "code": null, "e": 16939, "s": 16799, "text": "All the code that has been presented in this article is part of a notebook that can be run end-to-end. The notebook can be found on GitHub." }, { "code": null, "e": 17239, "s": 16939, "text": "Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details." }, { "code": null, "e": 17250, "s": 17239, "text": "Thank you," }, { "code": null, "e": 17254, "s": 17250, "text": "Jan" }, { "code": null, "e": 17701, "s": 17254, "text": "None of the content presented in this article constitutes a recommendation that any particular security, portfolio of securities, transaction, or investment strategy is suitable for any specific person. Futures, stocks, and options trading involves substantial risk of loss and is not suitable for every investor. The valuation of futures, stocks, and options may fluctuate, and, as a result, clients may lose more than their original investment." }, { "code": null, "e": 17824, "s": 17701, "text": "[1] Why Self-Attention? A Targeted Evaluation of Neural Machine Translation Architectures https://arxiv.org/abs/1808.08946" }, { "code": null, "e": 17942, "s": 17824, "text": "[2] BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding https://arxiv.org/abs/1810.04805" }, { "code": null, "e": 18030, "s": 17942, "text": "[3] Time2Vec: Learning a Vector Representation of Time https://arxiv.org/abs/1907.05321" } ]
Delegation in Kotlin - GeeksforGeeks
27 Jul, 2020 Delegation controls the allocation of power/authority from an instance to another for any object. For classes and functions implementations, delegations can be used on static as well as mutable relations between them. Inheritance implementation in classes and functions can be altered with the help of delegation techniques and object-oriented programing languages support it innately without any boilerplate code. Delegation is used in Kotlin with the help of “by” keyword. There are two types of delegation present in Kotlin: • Explicit delegation: Supported by all object-oriented language and it is done by passing a delegate(the one to be implemented) object to delegating object (the one that will implement delegate object). • Implicit delegation: Requires language-level support for the delegation pattern. Let us discuss the concept of the delegation with the help of the examples: Example 1: As we know that in Kotlin, inheritance provides us with a permanent static relationship between objects which are not mutable while delegation is, this fact makes Delegation an extremely powerful alternative. In this example, using Newfeature class we can implement delegation base class with new features by delegating all its public members i.e mymessage and messageline and we are using this implementation with the help of “by” keyword. Kotlin // Kotlin program to illustrate the // concept of delegation interface delegation { fun mymessage() fun mymessageline()} class delegationimplementation(val y: String) : delegation{ override fun mymessage() { print(y) } override fun mymessageline() { println(y) }} class Newfeature(m: delegation) : delegation by m{ override fun mymessage() { print("GeeksforGeeks") }} // Main functionfun main() { val b = delegationimplementation("\nWelcome, GFG!") Newfeature(b).mymessage() Newfeature(b).mymessageline()} Output: GeeksforGeeks Welcome, GFG! Example 2: In this example, we have one delegation base class with val value and method “fun message()”. In the delegationimplementation class, we are assigning value to this “fun message” and later from another class we are using this implementation using “by” keyword to add a new statement with same val value; Kotlin // Kotlin program to illustrate the // concept of delegationinterface delegation{ val value: String fun mymessage()} class delegationimplementation(val y: String) : delegation{ override val value = "delegationimplementation y = $y" override fun mymessage() { println(value) }} class Newfeatures(a: delegation) : delegation by a { override val value = "GeeksforGeeks"} fun main() { val b = delegationimplementation("Hello!GFG") val derived = Newfeatures(b) derived.mymessage() println(derived.value)} Output: delegationimplementation y = Hello!GFG GeeksforGeeks 1. It is a flexible, powerful as well as mutable method. 2. Multiple interfaces can be implemented with the help of the existing ones. 3. It is used to add new features and values to current implementations. Picked Kotlin Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Retrofit with Kotlin Coroutine in Android How to Get Current Location in Android? ImageView in Android with Example How to Build a Weather App in Android? Kotlin extension function ScrollView in Android How to Send Data From Activity to Fragment in Android? Notifications in Android with Example Kotlin Coroutines on Android Suspend Function In Kotlin Coroutines
[ { "code": null, "e": 24518, "s": 24490, "text": "\n27 Jul, 2020" }, { "code": null, "e": 24994, "s": 24518, "text": "Delegation controls the allocation of power/authority from an instance to another for any object. For classes and functions implementations, delegations can be used on static as well as mutable relations between them. Inheritance implementation in classes and functions can be altered with the help of delegation techniques and object-oriented programing languages support it innately without any boilerplate code. Delegation is used in Kotlin with the help of “by” keyword. " }, { "code": null, "e": 25336, "s": 24994, "text": "There are two types of delegation present in Kotlin: • Explicit delegation: Supported by all object-oriented language and it is done by passing a delegate(the one to be implemented) object to delegating object (the one that will implement delegate object). • Implicit delegation: Requires language-level support for the delegation pattern. " }, { "code": null, "e": 25423, "s": 25336, "text": "Let us discuss the concept of the delegation with the help of the examples: Example 1:" }, { "code": null, "e": 25866, "s": 25423, "text": "As we know that in Kotlin, inheritance provides us with a permanent static relationship between objects which are not mutable while delegation is, this fact makes Delegation an extremely powerful alternative. In this example, using Newfeature class we can implement delegation base class with new features by delegating all its public members i.e mymessage and messageline and we are using this implementation with the help of “by” keyword. " }, { "code": null, "e": 25873, "s": 25866, "text": "Kotlin" }, { "code": "// Kotlin program to illustrate the // concept of delegation interface delegation { fun mymessage() fun mymessageline()} class delegationimplementation(val y: String) : delegation{ override fun mymessage() { print(y) } override fun mymessageline() { println(y) }} class Newfeature(m: delegation) : delegation by m{ override fun mymessage() { print(\"GeeksforGeeks\") }} // Main functionfun main() { val b = delegationimplementation(\"\\nWelcome, GFG!\") Newfeature(b).mymessage() Newfeature(b).mymessageline()}", "e": 26457, "s": 25873, "text": null }, { "code": null, "e": 26465, "s": 26457, "text": "Output:" }, { "code": null, "e": 26496, "s": 26465, "text": "GeeksforGeeks\nWelcome, GFG!\n\n\n" }, { "code": null, "e": 26508, "s": 26496, "text": "Example 2: " }, { "code": null, "e": 26813, "s": 26508, "text": "In this example, we have one delegation base class with val value and method “fun message()”. In the delegationimplementation class, we are assigning value to this “fun message” and later from another class we are using this implementation using “by” keyword to add a new statement with same val value; " }, { "code": null, "e": 26820, "s": 26813, "text": "Kotlin" }, { "code": "// Kotlin program to illustrate the // concept of delegationinterface delegation{ val value: String fun mymessage()} class delegationimplementation(val y: String) : delegation{ override val value = \"delegationimplementation y = $y\" override fun mymessage() { println(value) }} class Newfeatures(a: delegation) : delegation by a { override val value = \"GeeksforGeeks\"} fun main() { val b = delegationimplementation(\"Hello!GFG\") val derived = Newfeatures(b) derived.mymessage() println(derived.value)}", "e": 27370, "s": 26820, "text": null }, { "code": null, "e": 27378, "s": 27370, "text": "Output:" }, { "code": null, "e": 27433, "s": 27378, "text": "delegationimplementation y = Hello!GFG\nGeeksforGeeks\n\n" }, { "code": null, "e": 27642, "s": 27433, "text": "1. It is a flexible, powerful as well as mutable method. 2. Multiple interfaces can be implemented with the help of the existing ones. 3. It is used to add new features and values to current implementations. " }, { "code": null, "e": 27649, "s": 27642, "text": "Picked" }, { "code": null, "e": 27656, "s": 27649, "text": "Kotlin" }, { "code": null, "e": 27754, "s": 27656, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27796, "s": 27754, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 27836, "s": 27796, "text": "How to Get Current Location in Android?" }, { "code": null, "e": 27870, "s": 27836, "text": "ImageView in Android with Example" }, { "code": null, "e": 27909, "s": 27870, "text": "How to Build a Weather App in Android?" }, { "code": null, "e": 27935, "s": 27909, "text": "Kotlin extension function" }, { "code": null, "e": 27957, "s": 27935, "text": "ScrollView in Android" }, { "code": null, "e": 28012, "s": 27957, "text": "How to Send Data From Activity to Fragment in Android?" }, { "code": null, "e": 28050, "s": 28012, "text": "Notifications in Android with Example" }, { "code": null, "e": 28079, "s": 28050, "text": "Kotlin Coroutines on Android" } ]
Unix / Linux - Environment
In this chapter, we will discuss in detail about the Unix environment. An important Unix concept is the environment, which is defined by environment variables. Some are set by the system, others by you, yet others by the shell, or any program that loads another program. A variable is a character string to which we assign a value. The value assigned could be a number, text, filename, device, or any other type of data. For example, first we set a variable TEST and then we access its value using the echo command − $TEST="Unix Programming" $echo $TEST It produces the following result. Unix Programming Note that the environment variables are set without using the $ sign but while accessing them we use the $ sign as prefix. These variables retain their values until we come out of the shell. When you log in to the system, the shell undergoes a phase called initialization to set up the environment. This is usually a two-step process that involves the shell reading the following files − /etc/profile profile The process is as follows − The shell checks to see whether the file /etc/profile exists. The shell checks to see whether the file /etc/profile exists. If it exists, the shell reads it. Otherwise, this file is skipped. No error message is displayed. If it exists, the shell reads it. Otherwise, this file is skipped. No error message is displayed. The shell checks to see whether the file .profile exists in your home directory. Your home directory is the directory that you start out in after you log in. The shell checks to see whether the file .profile exists in your home directory. Your home directory is the directory that you start out in after you log in. If it exists, the shell reads it; otherwise, the shell skips it. No error message is displayed. If it exists, the shell reads it; otherwise, the shell skips it. No error message is displayed. As soon as both of these files have been read, the shell displays a prompt − $ This is the prompt where you can enter commands in order to have them executed. Note − The shell initialization process detailed here applies to all Bourne type shells, but some additional files are used by bash and ksh. The file /etc/profile is maintained by the system administrator of your Unix machine and contains shell initialization information required by all users on a system. The file .profile is under your control. You can add as much shell customization information as you want to this file. The minimum set of information that you need to configure includes − The type of terminal you are using. A list of directories in which to locate the commands. A list of variables affecting the look and feel of your terminal. You can check your .profile available in your home directory. Open it using the vi editor and check all the variables set for your environment. Usually, the type of terminal you are using is automatically configured by either the login or getty programs. Sometimes, the auto configuration process guesses your terminal incorrectly. If your terminal is set incorrectly, the output of the commands might look strange, or you might not be able to interact with the shell properly. To make sure that this is not the case, most users set their terminal to the lowest common denominator in the following way − $TERM=vt100 $ When you type any command on the command prompt, the shell has to locate the command before it can be executed. The PATH variable specifies the locations in which the shell should look for commands. Usually the Path variable is set as follows − $PATH=/bin:/usr/bin $ Here, each of the individual entries separated by the colon character (:) are directories. If you request the shell to execute a command and it cannot find it in any of the directories given in the PATH variable, a message similar to the following appears − $hello hello: not found $ There are variables like PS1 and PS2 which are discussed in the next section. The characters that the shell displays as your command prompt are stored in the variable PS1. You can change this variable to be anything you want. As soon as you change it, it'll be used by the shell from that point on. For example, if you issued the command − $PS1='=>' => => => Your prompt will become =>. To set the value of PS1 so that it shows the working directory, issue the command − =>PS1="[\u@\h \w]\$" [root@ip-72-167-112-17 /var/www/tutorialspoint/unix]$ [root@ip-72-167-112-17 /var/www/tutorialspoint/unix]$ The result of this command is that the prompt displays the user's username, the machine's name (hostname), and the working directory. There are quite a few escape sequences that can be used as value arguments for PS1; try to limit yourself to the most critical so that the prompt does not overwhelm you with information. \t Current time, expressed as HH:MM:SS \d Current date, expressed as Weekday Month Date \n Newline \s Current shell environment \W Working directory \w Full path of the working directory \u Current user’s username \h Hostname of the current machine \# Command number of the current command. Increases when a new command is entered \$ If the effective UID is 0 (that is, if you are logged in as root), end the prompt with the # character; otherwise, use the $ sign You can make the change yourself every time you log in, or you can have the change made automatically in PS1 by adding it to your .profile file. When you issue a command that is incomplete, the shell will display a secondary prompt and wait for you to complete the command and hit Enter again. The default secondary prompt is > (the greater than sign), but can be changed by re-defining the PS2 shell variable − Following is the example which uses the default secondary prompt − $ echo "this is a > test" this is a test $ The example given below re-defines PS2 with a customized prompt − $ PS2="secondary prompt->" $ echo "this is a secondary prompt->test" this is a test $ Following is the partial list of important environment variables. These variables are set and accessed as mentioned below − DISPLAY Contains the identifier for the display that X11 programs should use by default. HOME Indicates the home directory of the current user: the default argument for the cd built-in command. IFS Indicates the Internal Field Separator that is used by the parser for word splitting after expansion. LANG LANG expands to the default system locale; LC_ALL can be used to override this. For example, if its value is pt_BR, then the language is set to (Brazilian) Portuguese and the locale to Brazil. LD_LIBRARY_PATH A Unix system with a dynamic linker, contains a colonseparated list of directories that the dynamic linker should search for shared objects when building a process image after exec, before searching in any other directories. PATH Indicates the search path for commands. It is a colon-separated list of directories in which the shell looks for commands. PWD Indicates the current working directory as set by the cd command. RANDOM Generates a random integer between 0 and 32,767 each time it is referenced. SHLVL Increments by one each time an instance of bash is started. This variable is useful for determining whether the built-in exit command ends the current session. TERM Refers to the display type. TZ Refers to Time zone. It can take values like GMT, AST, etc. UID Expands to the numeric user ID of the current user, initialized at the shell startup. Following is the sample example showing few environment variables − $ echo $HOME /root ]$ echo $DISPLAY $ echo $TERM xterm $ echo $PATH /usr/local/bin:/bin:/usr/bin:/home/amrood/bin:/usr/local/bin $ 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 3018, "s": 2747, "text": "In this chapter, we will discuss in detail about the Unix environment. An important Unix concept is the environment, which is defined by environment variables. Some are set by the system, others by you, yet others by the shell, or any program that loads another program." }, { "code": null, "e": 3168, "s": 3018, "text": "A variable is a character string to which we assign a value. The value assigned could be a number, text, filename, device, or any other type of data." }, { "code": null, "e": 3264, "s": 3168, "text": "For example, first we set a variable TEST and then we access its value using the echo command −" }, { "code": null, "e": 3301, "s": 3264, "text": "$TEST=\"Unix Programming\"\n$echo $TEST" }, { "code": null, "e": 3335, "s": 3301, "text": "It produces the following result." }, { "code": null, "e": 3353, "s": 3335, "text": "Unix Programming\n" }, { "code": null, "e": 3544, "s": 3353, "text": "Note that the environment variables are set without using the $ sign but while accessing them we use the $ sign as prefix. These variables retain their values until we come out of the shell." }, { "code": null, "e": 3741, "s": 3544, "text": "When you log in to the system, the shell undergoes a phase called initialization to set up the environment. This is usually a two-step process that involves the shell reading the following files −" }, { "code": null, "e": 3754, "s": 3741, "text": "/etc/profile" }, { "code": null, "e": 3762, "s": 3754, "text": "profile" }, { "code": null, "e": 3790, "s": 3762, "text": "The process is as follows −" }, { "code": null, "e": 3852, "s": 3790, "text": "The shell checks to see whether the file /etc/profile exists." }, { "code": null, "e": 3914, "s": 3852, "text": "The shell checks to see whether the file /etc/profile exists." }, { "code": null, "e": 4012, "s": 3914, "text": "If it exists, the shell reads it. Otherwise, this file is skipped. No error message is displayed." }, { "code": null, "e": 4110, "s": 4012, "text": "If it exists, the shell reads it. Otherwise, this file is skipped. No error message is displayed." }, { "code": null, "e": 4268, "s": 4110, "text": "The shell checks to see whether the file .profile exists in your home directory. Your home directory is the directory that you start out in after you log in." }, { "code": null, "e": 4426, "s": 4268, "text": "The shell checks to see whether the file .profile exists in your home directory. Your home directory is the directory that you start out in after you log in." }, { "code": null, "e": 4522, "s": 4426, "text": "If it exists, the shell reads it; otherwise, the shell skips it. No error message is displayed." }, { "code": null, "e": 4618, "s": 4522, "text": "If it exists, the shell reads it; otherwise, the shell skips it. No error message is displayed." }, { "code": null, "e": 4695, "s": 4618, "text": "As soon as both of these files have been read, the shell displays a prompt −" }, { "code": null, "e": 4698, "s": 4695, "text": "$\n" }, { "code": null, "e": 4778, "s": 4698, "text": "This is the prompt where you can enter commands in order to have them executed." }, { "code": null, "e": 4919, "s": 4778, "text": "Note − The shell initialization process detailed here applies to all Bourne type shells, but some additional files are used by bash and ksh." }, { "code": null, "e": 5085, "s": 4919, "text": "The file /etc/profile is maintained by the system administrator of your Unix machine and contains shell initialization information required by all users on a system." }, { "code": null, "e": 5273, "s": 5085, "text": "The file .profile is under your control. You can add as much shell customization information as you want to this file. The minimum set of information that you need to configure includes −" }, { "code": null, "e": 5309, "s": 5273, "text": "The type of terminal you are using." }, { "code": null, "e": 5364, "s": 5309, "text": "A list of directories in which to locate the commands." }, { "code": null, "e": 5430, "s": 5364, "text": "A list of variables affecting the look and feel of your terminal." }, { "code": null, "e": 5574, "s": 5430, "text": "You can check your .profile available in your home directory. Open it using the vi editor and check all the variables set for your environment." }, { "code": null, "e": 5762, "s": 5574, "text": "Usually, the type of terminal you are using is automatically configured by either the login or getty programs. Sometimes, the auto configuration process guesses your terminal incorrectly." }, { "code": null, "e": 5908, "s": 5762, "text": "If your terminal is set incorrectly, the output of the commands might look strange, or you might not be able to interact with the shell properly." }, { "code": null, "e": 6034, "s": 5908, "text": "To make sure that this is not the case, most users set their terminal to the lowest common denominator in the following way −" }, { "code": null, "e": 6049, "s": 6034, "text": "$TERM=vt100\n$\n" }, { "code": null, "e": 6161, "s": 6049, "text": "When you type any command on the command prompt, the shell has to locate the command before it can be executed." }, { "code": null, "e": 6294, "s": 6161, "text": "The PATH variable specifies the locations in which the shell should look for commands. Usually the Path variable is set as follows −" }, { "code": null, "e": 6317, "s": 6294, "text": "$PATH=/bin:/usr/bin\n$\n" }, { "code": null, "e": 6575, "s": 6317, "text": "Here, each of the individual entries separated by the colon character (:) are directories. If you request the shell to execute a command and it cannot find it in any of the directories given in the PATH variable, a message similar to the following appears −" }, { "code": null, "e": 6602, "s": 6575, "text": "$hello\nhello: not found\n$\n" }, { "code": null, "e": 6680, "s": 6602, "text": "There are variables like PS1 and PS2 which are discussed in the next section." }, { "code": null, "e": 6901, "s": 6680, "text": "The characters that the shell displays as your command prompt are stored in the variable PS1. You can change this variable to be anything you want. As soon as you change it, it'll be used by the shell from that point on." }, { "code": null, "e": 6942, "s": 6901, "text": "For example, if you issued the command −" }, { "code": null, "e": 6961, "s": 6942, "text": "$PS1='=>'\n=>\n=>\n=>" }, { "code": null, "e": 7073, "s": 6961, "text": "Your prompt will become =>. To set the value of PS1 so that it shows the working directory, issue the command −" }, { "code": null, "e": 7203, "s": 7073, "text": "=>PS1=\"[\\u@\\h \\w]\\$\"\n[root@ip-72-167-112-17 /var/www/tutorialspoint/unix]$\n[root@ip-72-167-112-17 /var/www/tutorialspoint/unix]$\n" }, { "code": null, "e": 7337, "s": 7203, "text": "The result of this command is that the prompt displays the user's username, the machine's name (hostname), and the working directory." }, { "code": null, "e": 7524, "s": 7337, "text": "There are quite a few escape sequences that can be used as value arguments for PS1; try to limit yourself to the most critical so that the prompt does not overwhelm you with information." }, { "code": null, "e": 7527, "s": 7524, "text": "\\t" }, { "code": null, "e": 7563, "s": 7527, "text": "Current time, expressed as HH:MM:SS" }, { "code": null, "e": 7566, "s": 7563, "text": "\\d" }, { "code": null, "e": 7612, "s": 7566, "text": "Current date, expressed as Weekday Month Date" }, { "code": null, "e": 7615, "s": 7612, "text": "\\n" }, { "code": null, "e": 7623, "s": 7615, "text": "Newline" }, { "code": null, "e": 7626, "s": 7623, "text": "\\s" }, { "code": null, "e": 7652, "s": 7626, "text": "Current shell environment" }, { "code": null, "e": 7655, "s": 7652, "text": "\\W" }, { "code": null, "e": 7673, "s": 7655, "text": "Working directory" }, { "code": null, "e": 7676, "s": 7673, "text": "\\w" }, { "code": null, "e": 7711, "s": 7676, "text": "Full path of the working directory" }, { "code": null, "e": 7714, "s": 7711, "text": "\\u" }, { "code": null, "e": 7738, "s": 7714, "text": "Current user’s username" }, { "code": null, "e": 7741, "s": 7738, "text": "\\h" }, { "code": null, "e": 7773, "s": 7741, "text": "Hostname of the current machine" }, { "code": null, "e": 7776, "s": 7773, "text": "\\#" }, { "code": null, "e": 7855, "s": 7776, "text": "Command number of the current command. Increases when a new command is entered" }, { "code": null, "e": 7858, "s": 7855, "text": "\\$" }, { "code": null, "e": 7988, "s": 7858, "text": "If the effective UID is 0 (that is, if you are logged in as root), end the prompt with the # character; otherwise, use the $ sign" }, { "code": null, "e": 8133, "s": 7988, "text": "You can make the change yourself every time you log in, or you can have the change made automatically in PS1 by adding it to your .profile file." }, { "code": null, "e": 8282, "s": 8133, "text": "When you issue a command that is incomplete, the shell will display a secondary prompt and wait for you to complete the command and hit Enter again." }, { "code": null, "e": 8400, "s": 8282, "text": "The default secondary prompt is > (the greater than sign), but can be changed by re-defining the PS2 shell variable −" }, { "code": null, "e": 8467, "s": 8400, "text": "Following is the example which uses the default secondary prompt −" }, { "code": null, "e": 8510, "s": 8467, "text": "$ echo \"this is a\n> test\"\nthis is a\ntest\n$" }, { "code": null, "e": 8576, "s": 8510, "text": "The example given below re-defines PS2 with a customized prompt −" }, { "code": null, "e": 8662, "s": 8576, "text": "$ PS2=\"secondary prompt->\"\n$ echo \"this is a\nsecondary prompt->test\"\nthis is a\ntest\n$" }, { "code": null, "e": 8786, "s": 8662, "text": "Following is the partial list of important environment variables. These variables are set and accessed as mentioned below −" }, { "code": null, "e": 8794, "s": 8786, "text": "DISPLAY" }, { "code": null, "e": 8875, "s": 8794, "text": "Contains the identifier for the display that X11 programs should use by default." }, { "code": null, "e": 8880, "s": 8875, "text": "HOME" }, { "code": null, "e": 8980, "s": 8880, "text": "Indicates the home directory of the current user: the default argument for the cd built-in command." }, { "code": null, "e": 8984, "s": 8980, "text": "IFS" }, { "code": null, "e": 9086, "s": 8984, "text": "Indicates the Internal Field Separator that is used by the parser for word splitting after expansion." }, { "code": null, "e": 9091, "s": 9086, "text": "LANG" }, { "code": null, "e": 9284, "s": 9091, "text": "LANG expands to the default system locale; LC_ALL can be used to override this. For example, if its value is pt_BR, then the language is set to (Brazilian) Portuguese and the locale to Brazil." }, { "code": null, "e": 9300, "s": 9284, "text": "LD_LIBRARY_PATH" }, { "code": null, "e": 9525, "s": 9300, "text": "A Unix system with a dynamic linker, contains a colonseparated list of directories that the dynamic linker should search for shared objects when building a process image after exec, before searching in any other directories." }, { "code": null, "e": 9530, "s": 9525, "text": "PATH" }, { "code": null, "e": 9653, "s": 9530, "text": "Indicates the search path for commands. It is a colon-separated list of directories in which the shell looks for commands." }, { "code": null, "e": 9657, "s": 9653, "text": "PWD" }, { "code": null, "e": 9723, "s": 9657, "text": "Indicates the current working directory as set by the cd command." }, { "code": null, "e": 9730, "s": 9723, "text": "RANDOM" }, { "code": null, "e": 9806, "s": 9730, "text": "Generates a random integer between 0 and 32,767 each time it is referenced." }, { "code": null, "e": 9812, "s": 9806, "text": "SHLVL" }, { "code": null, "e": 9972, "s": 9812, "text": "Increments by one each time an instance of bash is started. This variable is useful for determining whether the built-in exit command ends the current session." }, { "code": null, "e": 9977, "s": 9972, "text": "TERM" }, { "code": null, "e": 10005, "s": 9977, "text": "Refers to the display type." }, { "code": null, "e": 10008, "s": 10005, "text": "TZ" }, { "code": null, "e": 10068, "s": 10008, "text": "Refers to Time zone. It can take values like GMT, AST, etc." }, { "code": null, "e": 10072, "s": 10068, "text": "UID" }, { "code": null, "e": 10158, "s": 10072, "text": "Expands to the numeric user ID of the current user, initialized at the shell startup." }, { "code": null, "e": 10226, "s": 10158, "text": "Following is the sample example showing few environment variables −" }, { "code": null, "e": 10358, "s": 10226, "text": "$ echo $HOME\n/root\n]$ echo $DISPLAY\n\n$ echo $TERM\nxterm\n$ echo $PATH\n/usr/local/bin:/bin:/usr/bin:/home/amrood/bin:/usr/local/bin\n$" }, { "code": null, "e": 10393, "s": 10358, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 10421, "s": 10393, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 10455, "s": 10421, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 10472, "s": 10455, "text": " Frahaan Hussain" }, { "code": null, "e": 10505, "s": 10472, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 10516, "s": 10505, "text": " Pradeep D" }, { "code": null, "e": 10551, "s": 10516, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 10567, "s": 10551, "text": " Musab Zayadneh" }, { "code": null, "e": 10600, "s": 10567, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 10612, "s": 10600, "text": " GUHARAJANM" }, { "code": null, "e": 10644, "s": 10612, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 10652, "s": 10644, "text": " Uplatz" }, { "code": null, "e": 10659, "s": 10652, "text": " Print" }, { "code": null, "e": 10670, "s": 10659, "text": " Add Notes" } ]
How to make Marquee text in Android?
This example demonstrate about how to make Marquee text in Android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version = "1.0" encoding = "utf-8"?> <RelativeLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:gravity = "center" android:layout_height = "match_parent"> <TextView android:id = "@+id/text" android:textSize = "20dp" android:textAlignment = "center" android:layout_width = "match_parent" android:ellipsize = "marquee" android:fadingEdge = "horizontal" android:marqueeRepeatLimit = "marquee_forever" android:scrollHorizontally = "true" android:textColor = "#ff4500" android:text = "Simple application that shows how to use marquee, with a long text" android:layout_height = "wrap_content" android:singleLine = "true" /> </RelativeLayout> In the above code, we have taken text view and ellipsize property as marquee as shown below - android:ellipsize = "marquee" android:fadingEdge = "horizontal" android:marqueeRepeatLimit = "marquee_forever" android:scrollHorizontally = "true" android:singleLine = "true" Step 3 − Add the following code to src/MainActivity.java package com.example.andy.myapplication; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView txt = findViewById(R.id.text); txt.setSelected(true); } } Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − In the above result, text view will scroll from right to left with scroll animation. Click here to download the project code
[ { "code": null, "e": 1130, "s": 1062, "text": "This example demonstrate about how to make Marquee text in Android." }, { "code": null, "e": 1259, "s": 1130, "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": 1324, "s": 1259, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2169, "s": 1324, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<RelativeLayout\n xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:gravity = \"center\"\n android:layout_height = \"match_parent\">\n <TextView\n android:id = \"@+id/text\"\n android:textSize = \"20dp\"\n android:textAlignment = \"center\"\n android:layout_width = \"match_parent\"\n android:ellipsize = \"marquee\"\n android:fadingEdge = \"horizontal\"\n android:marqueeRepeatLimit = \"marquee_forever\"\n android:scrollHorizontally = \"true\"\n android:textColor = \"#ff4500\"\n android:text = \"Simple application that shows how to use marquee, with a long text\"\n android:layout_height = \"wrap_content\"\n android:singleLine = \"true\" />\n</RelativeLayout>" }, { "code": null, "e": 2263, "s": 2169, "text": "In the above code, we have taken text view and ellipsize property as marquee as shown below -" }, { "code": null, "e": 2438, "s": 2263, "text": "android:ellipsize = \"marquee\"\nandroid:fadingEdge = \"horizontal\"\nandroid:marqueeRepeatLimit = \"marquee_forever\"\nandroid:scrollHorizontally = \"true\"\nandroid:singleLine = \"true\"" }, { "code": null, "e": 2495, "s": 2438, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 2936, "s": 2495, "text": "package com.example.andy.myapplication;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.widget.TextView;\n\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n TextView txt = findViewById(R.id.text);\n txt.setSelected(true);\n }\n}" }, { "code": null, "e": 3284, "s": 2936, "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": 3369, "s": 3284, "text": "In the above result, text view will scroll from right to left with scroll animation." }, { "code": null, "e": 3409, "s": 3369, "text": "Click here to download the project code" } ]
How can I convert an array to an object by splitting strings? JavaScript
Let’s say, we have an array of strings in which each value each element has a dash (-), left to which we have our key and right to which we have our value. Our job is to split these strings and form an object out of this array. Here is the sample array − const arr = ["name-Rakesh", "age-23", "city-New Delhi", "jobType-remote", "language-English"]; So, let’s write the code, it will loop over the array splitting each string and feeding it into the new object The full code will be − const arr = ["name-Rakesh", "age-23", "city-New Delhi", "jobType-remote", "language-English"]; const obj = {}; arr.forEach(string => { const [key, value] = string.split("-"); obj[key] = value; }); console.log(obj); The console output for this code will be − { name: 'Rakesh', age: '23', city: 'New Delhi', jobType: 'remote', language: 'English' }
[ { "code": null, "e": 1290, "s": 1062, "text": "Let’s say, we have an array of strings in which each value each element has a dash (-), left to\nwhich we have our key and right to which we have our value. Our job is to split these strings and\nform an object out of this array." }, { "code": null, "e": 1317, "s": 1290, "text": "Here is the sample array −" }, { "code": null, "e": 1412, "s": 1317, "text": "const arr = [\"name-Rakesh\", \"age-23\", \"city-New Delhi\", \"jobType-remote\",\n\"language-English\"];" }, { "code": null, "e": 1523, "s": 1412, "text": "So, let’s write the code, it will loop over the array splitting each string and feeding it into the new\nobject" }, { "code": null, "e": 1547, "s": 1523, "text": "The full code will be −" }, { "code": null, "e": 1768, "s": 1547, "text": "const arr = [\"name-Rakesh\", \"age-23\", \"city-New Delhi\", \"jobType-remote\",\n\"language-English\"];\nconst obj = {};\narr.forEach(string => {\n const [key, value] = string.split(\"-\");\n obj[key] = value;\n});\nconsole.log(obj);" }, { "code": null, "e": 1811, "s": 1768, "text": "The console output for this code will be −" }, { "code": null, "e": 1915, "s": 1811, "text": "{\n name: 'Rakesh',\n age: '23',\n city: 'New Delhi',\n jobType: 'remote',\n language: 'English'\n}" } ]
Find pair with maximum GCD in an array - GeeksforGeeks
20 May, 2021 We are given an array of positive integers. Find the pair in array with maximum GCD.Examples: Input : arr[] : { 1 2 3 4 5 } Output : 2 Explanation : Pair {2, 4} has GCD 2 which is highest. Other pairs have a GCD of 1. Input : arr[] : { 2 3 4 8 8 11 12 } Output : 8 Explanation : Pair {8, 8} has GCD 8 which is highest. Method 1 (Brute-force): The simplest method to solve this problem is to use two loops to generate all possible pairs of elements of the array and calculate and compare the GCD at the same time. We can use the Extended Euclidean algorithm for efficiently computing GCD of two numbers. Time Complexity: O(N^2 * log(max(a, b))) Here, log(max(a, b)) is the time complexity to calculate GCD of a and b.Method 2 : (Efficient) In this method, we maintain a count array to store the count of divisors of every element. We will traverse the given array and for every element, we will calculate its divisors and increment at the index of count array. The process of computing divisors will take O(sqrt(arr[i])) time, where arr[i] is element in the given array at index i. After the whole traversal, we can simply traverse the count array from last index to index 1. If we found an index with a value greater than 1, then this means that it is a divisor of 2 elements and also the max GCD.Below is the implementation of above approach : C++ Java Python C# PHP Javascript // C++ Code to find pair with// maximum GCD in an array#include <bits/stdc++.h> using namespace std; // function to find GCD of pair with// max GCD in the arrayint findMaxGCD(int arr[], int n){ // Computing highest element int high = 0; for (int i = 0; i < n; i++) high = max(high, arr[i]); // Array to store the count of divisors // i.e. Potential GCDs int divisors[high + 1] = { 0 }; // Iterating over every element for (int i = 0; i < n; i++) { // Calculating all the divisors for (int j = 1; j <= sqrt(arr[i]); j++) { // Divisor found if (arr[i] % j == 0) { // Incrementing count for divisor divisors[j]++; // Element/divisor is also a divisor // Checking if both divisors are // not same if (j != arr[i] / j) divisors[arr[i] / j]++; } } } // Checking the highest potential GCD for (int i = high; i >= 1; i--) // If this divisor can divide at least 2 // numbers, it is a GCD of at least 1 pair if (divisors[i] > 1) return i; } // Driver codeint main(){ // Array in which pair with max GCD // is to be found int arr[] = { 1, 2, 4, 8, 8, 12 }; // Size of array int n = sizeof(arr) / sizeof(arr[0]); cout << findMaxGCD(arr,n); return 0;} // JAVA Code for Find pair with maximum GCD in an arrayclass GFG { // function to find GCD of pair with // max GCD in the array public static int findMaxGCD(int arr[], int n) { // Computing highest element int high = 0; for (int i = 0; i < n; i++) high = Math.max(high, arr[i]); // Array to store the count of divisors // i.e. Potential GCDs int divisors[] =new int[high + 1]; // Iterating over every element for (int i = 0; i < n; i++) { // Calculating all the divisors for (int j = 1; j <= Math.sqrt(arr[i]); j++) { // Divisor found if (arr[i] % j == 0) { // Incrementing count for divisor divisors[j]++; // Element/divisor is also a divisor // Checking if both divisors are // not same if (j != arr[i] / j) divisors[arr[i] / j]++; } } } // Checking the highest potential GCD for (int i = high; i >= 1; i--) // If this divisor can divide at least 2 // numbers, it is a GCD of at least 1 pair if (divisors[i] > 1) return i; return 1; } /* Driver program to test above function */ public static void main(String[] args) { // Array in which pair with max GCD // is to be found int arr[] = { 1, 2, 4, 8, 8, 12 }; // Size of array int n = arr.length; System.out.println(findMaxGCD(arr,n)); } } // This code is contributed by Arnav Kr. Mandal. # Python program to Find pair with# maximum GCD in an arrayimport math # function to find GCD of pair with# max GCD in the arraydef findMaxGCD(arr, n) : # Computing highest element high = 0 i = 0 while i < n : high = max(high, arr[i]) i = i + 1 # Array to store the count of divisors # i.e. Potential GCDs divisors = [0] * (high + 1) # Iterating over every element i = 0 while i < n : # Calculating all the divisors j = 1 while j <= math.sqrt(arr[i]) : # Divisor found if (arr[i] % j == 0) : # Incrementing count for divisor divisors[j]= divisors[j]+1 # Element/divisor is also a divisor # Checking if both divisors are # not same if (j != arr[i] / j) : divisors[arr[i] / j] = divisors[arr[i] / j] + 1 j = j + 1 i = i + 1 # Checking the highest potential GCD i = high while i >= 1 : # If this divisor can divide at least 2 # numbers, it is a GCD of at least 1 pair if (divisors[i] > 1) : return i i = i - 1 return 1 # Driver code # Array in which pair with max GCD# is to be foundarr = [ 1, 2, 4, 8, 8, 12 ] # Size of arrayn = len(arr) print findMaxGCD(arr,n) # This code is contributed by Nikita Tiwari. // C# Code for Find pair with// maximum GCD in an arrayusing System; class GFG { // Function to find GCD of pair // with max GCD in the array public static int findMaxGCD(int []arr, int n) { // Computing highest element int high = 0; for (int i = 0; i < n; i++) high = Math.Max(high, arr[i]); // Array to store the count of // divisors i.e. Potential GCDs int []divisors =new int[high + 1]; // Iterating over every element for (int i = 0; i < n; i++) { // Calculating all the divisors for (int j = 1; j <= Math.Sqrt(arr[i]); j++) { // Divisor found if (arr[i] % j == 0) { // Incrementing count // for divisor divisors[j]++; // Element / divisor is also // a divisor Checking if both // divisors are not same if (j != arr[i] / j) divisors[arr[i] / j]++; } } } // Checking the highest potential GCD for (int i = high; i >= 1; i--) // If this divisor can divide at // least 2 numbers, it is a // GCD of at least 1 pair if (divisors[i] > 1) return i; return 1; } // Driver Code public static void Main(String []args) { // Array in which pair with // max GCD is to be found int []arr = {1, 2, 4, 8, 8, 12}; // Size of array int n = arr.Length; Console.WriteLine(findMaxGCD(arr,n)); }} // This code is contributed by vt_m. <?php// PHP Code for Find pair with// maximum GCD in an array // Function to find GCD// of pair with max GCD// in the arrayfunction findMaxGCD($arr, $n){ // Computing highest element $high = 0; for ($i = 0; $i < $n; $i++) $high = max($high, $arr[$i]); // Array to store the // count of divisors // i.e. Potential GCDs $divisors = array_fill(0, $high + 1, 0); // Iterating over every element for ($i = 0; $i < $n; $i++) { // Calculating all // the divisors for ($j = 1; $j <= (int)(sqrt($arr[$i])); $j++) { // Divisor found if ($arr[$i] % $j == 0) { // Incrementing count // for divisor $divisors[$j]++; // Element/divisor is also // a divisor Checking if // both divisors are not same if ($j != (int)($arr[$i] / $j)) $divisors[(int)($arr[$i] / $j)]++; } } } // Checking the highest // potential GCD for ($i = $high; $i >= 1; $i--) // If this divisor can divide // at least 2 numbers, it is // a GCD of at least 1 pair if ($divisors[$i] > 1) return $i;} // Driver code // Array in which pair// with max GCD is to// be found$arr = array( 1, 2, 4, 8, 8, 12 ); // Size of array$n = sizeof($arr); echo findMaxGCD($arr,$n); // This code is contributed by mits?> <script> // JavaScript Code for Find pair with// maximum GCD in an array // function to find GCD of pair with// max GCD in the arrayfunction findMaxGCD(arr , n){ // Computing highest element var high = 0; for (var i = 0; i < n; i++) high = Math.max(high, arr[i]); // Array to store the count of divisors // i.e. Potential GCDs var divisors = Array.from({length: high + 1}, (_, i) => 0); // Iterating over every element for (var i = 0; i < n; i++) { // Calculating all the divisors for (var j = 1; j <= Math.sqrt(arr[i]); j++) { // Divisor found if (arr[i] % j == 0) { // Incrementing count for divisor divisors[j]++; // Element/divisor is also a divisor // Checking if both divisors are // not same if (j != arr[i] / j) divisors[arr[i] / j]++; } } } // Checking the highest potential GCD for (var i = high; i >= 1; i--) // If this divisor can divide at least 2 // numbers, it is a GCD of at least 1 pair if (divisors[i] > 1) return i; return 1;} /* Driver program to test above function */ // Array in which pair with max GCD// is to be found var arr = [ 1, 2, 4, 8, 8, 12 ]; // Size of array var n = arr.length; document.write(findMaxGCD(arr,n)); // This code contributed by shikhasingrajput </script> Output: 8 Time Complexity: O(N * sqrt(arr[i]) + H) , where arr[i] denotes the element of the array and H denotes the largest number of the array.Method 3 (Most Efficient): This approach is based on the idea of Sieve Of Eratosthenes. First let’s solve a simpler problem, given a value X we have to tell whether a pair has a GCD equal to X. This can be done by checking that how many elements in the array are multiples of X. If the number of such multiples is greater than 1, then X will be a GCD of some pair. Now for pair with maximum GCD, we maintain a count array of the original array. Our method is based on the above problem with Sieve-like approach for loop. Below is the step by step algorithm of this approach: Iterate ‘i’ from MAX (maximum array element) to 1.Iterate ‘j’ from ‘i’ to MAX. We will check if the count array is 1 at index ‘j’.Increment the index ‘j’ everytime with ‘i’. This way, we can check for i, 2i, 3i, and so on.If we get 1 two times at count array that means 2 multiples of i exists. This makes it the highest GCD. Iterate ‘i’ from MAX (maximum array element) to 1. Iterate ‘j’ from ‘i’ to MAX. We will check if the count array is 1 at index ‘j’. Increment the index ‘j’ everytime with ‘i’. This way, we can check for i, 2i, 3i, and so on. If we get 1 two times at count array that means 2 multiples of i exists. This makes it the highest GCD. Below is the implementation of above approach : C++ Java Python3 C# PHP Javascript // C++ Code to// Find pair with// maximum GCD in// an array#include <bits/stdc++.h>using namespace std; // function to find// GCD of pair with// max GCD in the// arrayint findMaxGCD(int arr[], int n){ // Calculating MAX in array int high = 0; for (int i = 0; i < n; i++) high = max(high, arr[i]); // Maintaining count array int count[high + 1] = {0}; for (int i = 0; i < n; i++) count[arr[i]]++; // Variable to store the // multiples of a number int counter = 0; // Iterating from MAX to 1 // GCD is always between // MAX and 1. The first // GCD found will be the // highest as we are // decrementing the potential // GCD for (int i = high; i >= 1; i--) { int j = i; counter = 0; // Iterating from current // potential GCD // till it is less than // MAX while (j <= high) { // A multiple found if(count[j] >=2) return j; else if (count[j] == 1) counter++; // Incrementing potential // GCD by itself // To check i, 2i, 3i.... j += i; // 2 multiples found, // max GCD found if (counter == 2) return i; } }} // Driver codeint main(){ // Array in which pair // with max GCD is to // be found int arr[] = { 1, 2, 4, 8, 8, 12 }; // Size of array int n = sizeof(arr) / sizeof(arr[0]); cout << findMaxGCD(arr, n); return 0;} // Java Code to// Find pair with// maximum GCD in// an array class GFG { // function to find // GCD of pair with // max GCD in the // array public static int findMaxGCD(int arr[], int n) { // Calculating MAX in // array int high = 0; for (int i = 0; i < n; i++) high = Math.max(high, arr[i]); // Maintaining count array int count[]=new int[high + 1]; for (int i = 0; i < n; i++) count[arr[i]]++; // Variable to store // the multiples of // a number int counter = 0; // Iterating from MAX // to 1 GCD is always // between MAX and 1 // The first GCD found // will be the highest // as we are decrementing // the potential GCD for (int i = high; i >= 1; i--) { int j = i; // Iterating from current // potential GCD till it // is less than MAX while (j <= high) { // A multiple found if (count[j]>0) counter+=count[j]; // Incrementing potential // GCD by itself // To check i, 2i, 3i.... j += i; // 2 multiples found, // max GCD found if (counter == 2) return i; } counter=0; } return 1; } /* Driver program to test above function */ public static void main(String[] args) { // Array in which pair // with max GCD is to // be found int arr[] = {1, 2, 4, 8, 8, 12}; // Size of array int n = arr.length; System.out.println(findMaxGCD(arr,n)); }} // This code is contributed by Arnav Kr. Mandal. # Python3 Code to# Find pair with# maximum GCD in# an array # function to find# GCD of pair with# max GCD in the# arraydef findMaxGCD(arr, n) : # Calculating MAX in # array high = 0 for i in range(0, n) : high = max(high, arr[i]) # Maintaining count array count = [0] * (high + 1) for i in range(0, n) : count[arr[i]]+=1 # Variable to store the # multiples of a number counter = 0 # Iterating from MAX # to 1 GCD is always # between MAX and 1 # The first GCD found # will be the highest # as we are decrementing # the potential GCD for i in range(high, 0, -1) : j = i # Iterating from current # potential GCD till it # is less than MAX while (j <= high) : # A multiple found if (count[j] >0) : counter+=count[j] # Incrementing potential # GCD by itself # To check i, 2i, 3i.... j += i # 2 multiples found, # max GCD found if (counter == 2) : return i counter=0 # Driver code # Array in which pair# with max GCD is to# be foundarr = [1, 2, 4, 8, 8, 12]# Size of arrayn = len(arr)print(findMaxGCD(arr, n)) #This code is contributed by Nikita Tiwari. // C# Code to find pair with// maximum GCD in an arrayusing System; class GFG { // function to find GCD // of pair with max // max GCD in the array public static int findMaxGCD(int []arr, int n) { // Calculating Max // in array int high = 0; for (int i = 0; i < n; i++) high = Math.Max(high, arr[i]); // Maintaining count array int []count=new int[high + 1]; for (int i = 0; i < n; i++) count[arr[i]]++; // Variable to store // the multiples of // a number int counter = 0; // Iterating from MAX // to 1 GCD is always // between MAX and 1 // The first GCD found // will be the highest // as we are decrementing // the potential GCD for (int i = high; i >= 1; i--) { int j = i; // Iterating from current // potential GCD till it // is less than MAX while (j <= high) { // A multiple found if (count[j]>0) counter+=count[j]; // Incrementing potential // GCD by itself // To check i, 2i, 3i.... j += i; // 2 multiples found, // max GCD found if (counter == 2) return i; } counter=0; } return 1; } // Driver Code public static void Main(String []args) { // Array in which pair // with max GCD is to // be found int []arr = {1, 2, 4, 8, 8, 12}; // Size of array int n = arr.Length; Console.WriteLine(findMaxGCD(arr,n)); }} // This code is contributed by vt_m. <?php// PHP Code to Find pair with maximum// GCD in an array // function to find GCD of pair with// max GCD in the arrayfunction findMaxGCD($arr, $n){ // Calculating MAX in array $high = 0; for ($i = 0; $i < $n; $i++) $high = max($high, $arr[$i]); // Maintaining count array $count = array_fill(0, $high + 1, 0); for ($i = 0; $i < $n; $i++) $count[$arr[$i]]++; // Variable to store the multiples // of a number $counter = 0; // Iterating from MAX to 1 GCD is always // between MAX and 1. The first GCD found // will be the highest as we are decrementing // the potential GCD for ($i = $high; $i >= 1; $i--) { $j = $i; $counter = 0; // Iterating from current potential GCD // till it is less than MAX while ($j <= $high) { // A multiple found if($count[$j] >= 2) return $j; else if ($count[$j] == 1) $counter++; // Incrementing potential GCD by itself // To check i, 2i, 3i.... $j += $i; // 2 multiples found, max GCD found if ($counter == 2) return $i; } }} // Driver code // Array in which pair with max GCD// is to be found$arr = array( 1, 2, 4, 8, 8, 12 ); // Size of array$n = count($arr); print(findMaxGCD($arr, $n)); // This code is contributed by mits?> <script>// javascript Code to// Find pair with// maximum GCD in// an array // function to find // GCD of pair with // max GCD in the // array function findMaxGCD(arr , n) { // Calculating MAX in // array var high = 0; for (let i = 0; i < n; i++) high = Math.max(high, arr[i]); // Maintaining count array var count = Array(high + 1).fill(0); for (let i = 0; i < n; i++) count[arr[i]]++; // Variable to store // the multiples of // a number var counter = 0; // Iterating from MAX // to 1 GCD is always // between MAX and 1 // The first GCD found // will be the highest // as we are decrementing // the potential GCD for (let i = high; i >= 1; i--) { var j = i; // Iterating from current // potential GCD till it // is less than MAX while (j <= high) { // A multiple found if (count[j] > 0) counter += count[j]; // Incrementing potential // GCD by itself // To check i, 2i, 3i.... j += i; // 2 multiples found, // max GCD found if (counter == 2) return i; } counter = 0; } return 1; } /* Driver program to test above function */ // Array in which pair // with max GCD is to // be found var arr = [ 1, 2, 4, 8, 8, 12 ]; // Size of array var n = arr.length; document.write(findMaxGCD(arr, n)); // This code is contributed by aashish1995</script> Output: 8 Time Complexity: The time complexity of this approach is till an open problem known as the Dirichlet divisor problem. This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. vt_m Mithun Kumar manikantkumar Jainish Shah 1 Akanksha_Rai harshit23 aashish1995 shikhasingrajput GCD-LCM sieve Mathematical Mathematical sieve Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Program to find sum of elements in a given array Operators in C / C++ Program for factorial of a number Algorithm to solve Rubik's Cube Print all possible combinations of r elements in a given array of size n The Knight's tour problem | Backtracking-1 Minimum number of jumps to reach end
[ { "code": null, "e": 24548, "s": 24520, "text": "\n20 May, 2021" }, { "code": null, "e": 24644, "s": 24548, "text": "We are given an array of positive integers. Find the pair in array with maximum GCD.Examples: " }, { "code": null, "e": 24870, "s": 24644, "text": "Input : arr[] : { 1 2 3 4 5 }\nOutput : 2\nExplanation : Pair {2, 4} has GCD 2 which is highest. Other pairs have a GCD of 1.\n\nInput : arr[] : { 2 3 4 8 8 11 12 }\nOutput : 8\nExplanation : Pair {8, 8} has GCD 8 which is highest." }, { "code": null, "e": 25899, "s": 24872, "text": "Method 1 (Brute-force): The simplest method to solve this problem is to use two loops to generate all possible pairs of elements of the array and calculate and compare the GCD at the same time. We can use the Extended Euclidean algorithm for efficiently computing GCD of two numbers. Time Complexity: O(N^2 * log(max(a, b))) Here, log(max(a, b)) is the time complexity to calculate GCD of a and b.Method 2 : (Efficient) In this method, we maintain a count array to store the count of divisors of every element. We will traverse the given array and for every element, we will calculate its divisors and increment at the index of count array. The process of computing divisors will take O(sqrt(arr[i])) time, where arr[i] is element in the given array at index i. After the whole traversal, we can simply traverse the count array from last index to index 1. If we found an index with a value greater than 1, then this means that it is a divisor of 2 elements and also the max GCD.Below is the implementation of above approach : " }, { "code": null, "e": 25903, "s": 25899, "text": "C++" }, { "code": null, "e": 25908, "s": 25903, "text": "Java" }, { "code": null, "e": 25915, "s": 25908, "text": "Python" }, { "code": null, "e": 25918, "s": 25915, "text": "C#" }, { "code": null, "e": 25922, "s": 25918, "text": "PHP" }, { "code": null, "e": 25933, "s": 25922, "text": "Javascript" }, { "code": "// C++ Code to find pair with// maximum GCD in an array#include <bits/stdc++.h> using namespace std; // function to find GCD of pair with// max GCD in the arrayint findMaxGCD(int arr[], int n){ // Computing highest element int high = 0; for (int i = 0; i < n; i++) high = max(high, arr[i]); // Array to store the count of divisors // i.e. Potential GCDs int divisors[high + 1] = { 0 }; // Iterating over every element for (int i = 0; i < n; i++) { // Calculating all the divisors for (int j = 1; j <= sqrt(arr[i]); j++) { // Divisor found if (arr[i] % j == 0) { // Incrementing count for divisor divisors[j]++; // Element/divisor is also a divisor // Checking if both divisors are // not same if (j != arr[i] / j) divisors[arr[i] / j]++; } } } // Checking the highest potential GCD for (int i = high; i >= 1; i--) // If this divisor can divide at least 2 // numbers, it is a GCD of at least 1 pair if (divisors[i] > 1) return i; } // Driver codeint main(){ // Array in which pair with max GCD // is to be found int arr[] = { 1, 2, 4, 8, 8, 12 }; // Size of array int n = sizeof(arr) / sizeof(arr[0]); cout << findMaxGCD(arr,n); return 0;}", "e": 27362, "s": 25933, "text": null }, { "code": "// JAVA Code for Find pair with maximum GCD in an arrayclass GFG { // function to find GCD of pair with // max GCD in the array public static int findMaxGCD(int arr[], int n) { // Computing highest element int high = 0; for (int i = 0; i < n; i++) high = Math.max(high, arr[i]); // Array to store the count of divisors // i.e. Potential GCDs int divisors[] =new int[high + 1]; // Iterating over every element for (int i = 0; i < n; i++) { // Calculating all the divisors for (int j = 1; j <= Math.sqrt(arr[i]); j++) { // Divisor found if (arr[i] % j == 0) { // Incrementing count for divisor divisors[j]++; // Element/divisor is also a divisor // Checking if both divisors are // not same if (j != arr[i] / j) divisors[arr[i] / j]++; } } } // Checking the highest potential GCD for (int i = high; i >= 1; i--) // If this divisor can divide at least 2 // numbers, it is a GCD of at least 1 pair if (divisors[i] > 1) return i; return 1; } /* Driver program to test above function */ public static void main(String[] args) { // Array in which pair with max GCD // is to be found int arr[] = { 1, 2, 4, 8, 8, 12 }; // Size of array int n = arr.length; System.out.println(findMaxGCD(arr,n)); } } // This code is contributed by Arnav Kr. Mandal.", "e": 29122, "s": 27362, "text": null }, { "code": "# Python program to Find pair with# maximum GCD in an arrayimport math # function to find GCD of pair with# max GCD in the arraydef findMaxGCD(arr, n) : # Computing highest element high = 0 i = 0 while i < n : high = max(high, arr[i]) i = i + 1 # Array to store the count of divisors # i.e. Potential GCDs divisors = [0] * (high + 1) # Iterating over every element i = 0 while i < n : # Calculating all the divisors j = 1 while j <= math.sqrt(arr[i]) : # Divisor found if (arr[i] % j == 0) : # Incrementing count for divisor divisors[j]= divisors[j]+1 # Element/divisor is also a divisor # Checking if both divisors are # not same if (j != arr[i] / j) : divisors[arr[i] / j] = divisors[arr[i] / j] + 1 j = j + 1 i = i + 1 # Checking the highest potential GCD i = high while i >= 1 : # If this divisor can divide at least 2 # numbers, it is a GCD of at least 1 pair if (divisors[i] > 1) : return i i = i - 1 return 1 # Driver code # Array in which pair with max GCD# is to be foundarr = [ 1, 2, 4, 8, 8, 12 ] # Size of arrayn = len(arr) print findMaxGCD(arr,n) # This code is contributed by Nikita Tiwari.", "e": 30650, "s": 29122, "text": null }, { "code": "// C# Code for Find pair with// maximum GCD in an arrayusing System; class GFG { // Function to find GCD of pair // with max GCD in the array public static int findMaxGCD(int []arr, int n) { // Computing highest element int high = 0; for (int i = 0; i < n; i++) high = Math.Max(high, arr[i]); // Array to store the count of // divisors i.e. Potential GCDs int []divisors =new int[high + 1]; // Iterating over every element for (int i = 0; i < n; i++) { // Calculating all the divisors for (int j = 1; j <= Math.Sqrt(arr[i]); j++) { // Divisor found if (arr[i] % j == 0) { // Incrementing count // for divisor divisors[j]++; // Element / divisor is also // a divisor Checking if both // divisors are not same if (j != arr[i] / j) divisors[arr[i] / j]++; } } } // Checking the highest potential GCD for (int i = high; i >= 1; i--) // If this divisor can divide at // least 2 numbers, it is a // GCD of at least 1 pair if (divisors[i] > 1) return i; return 1; } // Driver Code public static void Main(String []args) { // Array in which pair with // max GCD is to be found int []arr = {1, 2, 4, 8, 8, 12}; // Size of array int n = arr.Length; Console.WriteLine(findMaxGCD(arr,n)); }} // This code is contributed by vt_m.", "e": 32454, "s": 30650, "text": null }, { "code": "<?php// PHP Code for Find pair with// maximum GCD in an array // Function to find GCD// of pair with max GCD// in the arrayfunction findMaxGCD($arr, $n){ // Computing highest element $high = 0; for ($i = 0; $i < $n; $i++) $high = max($high, $arr[$i]); // Array to store the // count of divisors // i.e. Potential GCDs $divisors = array_fill(0, $high + 1, 0); // Iterating over every element for ($i = 0; $i < $n; $i++) { // Calculating all // the divisors for ($j = 1; $j <= (int)(sqrt($arr[$i])); $j++) { // Divisor found if ($arr[$i] % $j == 0) { // Incrementing count // for divisor $divisors[$j]++; // Element/divisor is also // a divisor Checking if // both divisors are not same if ($j != (int)($arr[$i] / $j)) $divisors[(int)($arr[$i] / $j)]++; } } } // Checking the highest // potential GCD for ($i = $high; $i >= 1; $i--) // If this divisor can divide // at least 2 numbers, it is // a GCD of at least 1 pair if ($divisors[$i] > 1) return $i;} // Driver code // Array in which pair// with max GCD is to// be found$arr = array( 1, 2, 4, 8, 8, 12 ); // Size of array$n = sizeof($arr); echo findMaxGCD($arr,$n); // This code is contributed by mits?>", "e": 33922, "s": 32454, "text": null }, { "code": "<script> // JavaScript Code for Find pair with// maximum GCD in an array // function to find GCD of pair with// max GCD in the arrayfunction findMaxGCD(arr , n){ // Computing highest element var high = 0; for (var i = 0; i < n; i++) high = Math.max(high, arr[i]); // Array to store the count of divisors // i.e. Potential GCDs var divisors = Array.from({length: high + 1}, (_, i) => 0); // Iterating over every element for (var i = 0; i < n; i++) { // Calculating all the divisors for (var j = 1; j <= Math.sqrt(arr[i]); j++) { // Divisor found if (arr[i] % j == 0) { // Incrementing count for divisor divisors[j]++; // Element/divisor is also a divisor // Checking if both divisors are // not same if (j != arr[i] / j) divisors[arr[i] / j]++; } } } // Checking the highest potential GCD for (var i = high; i >= 1; i--) // If this divisor can divide at least 2 // numbers, it is a GCD of at least 1 pair if (divisors[i] > 1) return i; return 1;} /* Driver program to test above function */ // Array in which pair with max GCD// is to be found var arr = [ 1, 2, 4, 8, 8, 12 ]; // Size of array var n = arr.length; document.write(findMaxGCD(arr,n)); // This code contributed by shikhasingrajput </script>", "e": 35423, "s": 33922, "text": null }, { "code": null, "e": 35433, "s": 35423, "text": "Output: " }, { "code": null, "e": 35435, "s": 35433, "text": "8" }, { "code": null, "e": 36147, "s": 35435, "text": "Time Complexity: O(N * sqrt(arr[i]) + H) , where arr[i] denotes the element of the array and H denotes the largest number of the array.Method 3 (Most Efficient): This approach is based on the idea of Sieve Of Eratosthenes. First let’s solve a simpler problem, given a value X we have to tell whether a pair has a GCD equal to X. This can be done by checking that how many elements in the array are multiples of X. If the number of such multiples is greater than 1, then X will be a GCD of some pair. Now for pair with maximum GCD, we maintain a count array of the original array. Our method is based on the above problem with Sieve-like approach for loop. Below is the step by step algorithm of this approach: " }, { "code": null, "e": 36473, "s": 36147, "text": "Iterate ‘i’ from MAX (maximum array element) to 1.Iterate ‘j’ from ‘i’ to MAX. We will check if the count array is 1 at index ‘j’.Increment the index ‘j’ everytime with ‘i’. This way, we can check for i, 2i, 3i, and so on.If we get 1 two times at count array that means 2 multiples of i exists. This makes it the highest GCD." }, { "code": null, "e": 36524, "s": 36473, "text": "Iterate ‘i’ from MAX (maximum array element) to 1." }, { "code": null, "e": 36605, "s": 36524, "text": "Iterate ‘j’ from ‘i’ to MAX. We will check if the count array is 1 at index ‘j’." }, { "code": null, "e": 36698, "s": 36605, "text": "Increment the index ‘j’ everytime with ‘i’. This way, we can check for i, 2i, 3i, and so on." }, { "code": null, "e": 36802, "s": 36698, "text": "If we get 1 two times at count array that means 2 multiples of i exists. This makes it the highest GCD." }, { "code": null, "e": 36852, "s": 36802, "text": "Below is the implementation of above approach : " }, { "code": null, "e": 36856, "s": 36852, "text": "C++" }, { "code": null, "e": 36861, "s": 36856, "text": "Java" }, { "code": null, "e": 36869, "s": 36861, "text": "Python3" }, { "code": null, "e": 36872, "s": 36869, "text": "C#" }, { "code": null, "e": 36876, "s": 36872, "text": "PHP" }, { "code": null, "e": 36887, "s": 36876, "text": "Javascript" }, { "code": "// C++ Code to// Find pair with// maximum GCD in// an array#include <bits/stdc++.h>using namespace std; // function to find// GCD of pair with// max GCD in the// arrayint findMaxGCD(int arr[], int n){ // Calculating MAX in array int high = 0; for (int i = 0; i < n; i++) high = max(high, arr[i]); // Maintaining count array int count[high + 1] = {0}; for (int i = 0; i < n; i++) count[arr[i]]++; // Variable to store the // multiples of a number int counter = 0; // Iterating from MAX to 1 // GCD is always between // MAX and 1. The first // GCD found will be the // highest as we are // decrementing the potential // GCD for (int i = high; i >= 1; i--) { int j = i; counter = 0; // Iterating from current // potential GCD // till it is less than // MAX while (j <= high) { // A multiple found if(count[j] >=2) return j; else if (count[j] == 1) counter++; // Incrementing potential // GCD by itself // To check i, 2i, 3i.... j += i; // 2 multiples found, // max GCD found if (counter == 2) return i; } }} // Driver codeint main(){ // Array in which pair // with max GCD is to // be found int arr[] = { 1, 2, 4, 8, 8, 12 }; // Size of array int n = sizeof(arr) / sizeof(arr[0]); cout << findMaxGCD(arr, n); return 0;}", "e": 38451, "s": 36887, "text": null }, { "code": "// Java Code to// Find pair with// maximum GCD in// an array class GFG { // function to find // GCD of pair with // max GCD in the // array public static int findMaxGCD(int arr[], int n) { // Calculating MAX in // array int high = 0; for (int i = 0; i < n; i++) high = Math.max(high, arr[i]); // Maintaining count array int count[]=new int[high + 1]; for (int i = 0; i < n; i++) count[arr[i]]++; // Variable to store // the multiples of // a number int counter = 0; // Iterating from MAX // to 1 GCD is always // between MAX and 1 // The first GCD found // will be the highest // as we are decrementing // the potential GCD for (int i = high; i >= 1; i--) { int j = i; // Iterating from current // potential GCD till it // is less than MAX while (j <= high) { // A multiple found if (count[j]>0) counter+=count[j]; // Incrementing potential // GCD by itself // To check i, 2i, 3i.... j += i; // 2 multiples found, // max GCD found if (counter == 2) return i; } counter=0; } return 1; } /* Driver program to test above function */ public static void main(String[] args) { // Array in which pair // with max GCD is to // be found int arr[] = {1, 2, 4, 8, 8, 12}; // Size of array int n = arr.length; System.out.println(findMaxGCD(arr,n)); }} // This code is contributed by Arnav Kr. Mandal.", "e": 40325, "s": 38451, "text": null }, { "code": "# Python3 Code to# Find pair with# maximum GCD in# an array # function to find# GCD of pair with# max GCD in the# arraydef findMaxGCD(arr, n) : # Calculating MAX in # array high = 0 for i in range(0, n) : high = max(high, arr[i]) # Maintaining count array count = [0] * (high + 1) for i in range(0, n) : count[arr[i]]+=1 # Variable to store the # multiples of a number counter = 0 # Iterating from MAX # to 1 GCD is always # between MAX and 1 # The first GCD found # will be the highest # as we are decrementing # the potential GCD for i in range(high, 0, -1) : j = i # Iterating from current # potential GCD till it # is less than MAX while (j <= high) : # A multiple found if (count[j] >0) : counter+=count[j] # Incrementing potential # GCD by itself # To check i, 2i, 3i.... j += i # 2 multiples found, # max GCD found if (counter == 2) : return i counter=0 # Driver code # Array in which pair# with max GCD is to# be foundarr = [1, 2, 4, 8, 8, 12]# Size of arrayn = len(arr)print(findMaxGCD(arr, n)) #This code is contributed by Nikita Tiwari.", "e": 41635, "s": 40325, "text": null }, { "code": "// C# Code to find pair with// maximum GCD in an arrayusing System; class GFG { // function to find GCD // of pair with max // max GCD in the array public static int findMaxGCD(int []arr, int n) { // Calculating Max // in array int high = 0; for (int i = 0; i < n; i++) high = Math.Max(high, arr[i]); // Maintaining count array int []count=new int[high + 1]; for (int i = 0; i < n; i++) count[arr[i]]++; // Variable to store // the multiples of // a number int counter = 0; // Iterating from MAX // to 1 GCD is always // between MAX and 1 // The first GCD found // will be the highest // as we are decrementing // the potential GCD for (int i = high; i >= 1; i--) { int j = i; // Iterating from current // potential GCD till it // is less than MAX while (j <= high) { // A multiple found if (count[j]>0) counter+=count[j]; // Incrementing potential // GCD by itself // To check i, 2i, 3i.... j += i; // 2 multiples found, // max GCD found if (counter == 2) return i; } counter=0; } return 1; } // Driver Code public static void Main(String []args) { // Array in which pair // with max GCD is to // be found int []arr = {1, 2, 4, 8, 8, 12}; // Size of array int n = arr.Length; Console.WriteLine(findMaxGCD(arr,n)); }} // This code is contributed by vt_m.", "e": 43495, "s": 41635, "text": null }, { "code": "<?php// PHP Code to Find pair with maximum// GCD in an array // function to find GCD of pair with// max GCD in the arrayfunction findMaxGCD($arr, $n){ // Calculating MAX in array $high = 0; for ($i = 0; $i < $n; $i++) $high = max($high, $arr[$i]); // Maintaining count array $count = array_fill(0, $high + 1, 0); for ($i = 0; $i < $n; $i++) $count[$arr[$i]]++; // Variable to store the multiples // of a number $counter = 0; // Iterating from MAX to 1 GCD is always // between MAX and 1. The first GCD found // will be the highest as we are decrementing // the potential GCD for ($i = $high; $i >= 1; $i--) { $j = $i; $counter = 0; // Iterating from current potential GCD // till it is less than MAX while ($j <= $high) { // A multiple found if($count[$j] >= 2) return $j; else if ($count[$j] == 1) $counter++; // Incrementing potential GCD by itself // To check i, 2i, 3i.... $j += $i; // 2 multiples found, max GCD found if ($counter == 2) return $i; } }} // Driver code // Array in which pair with max GCD// is to be found$arr = array( 1, 2, 4, 8, 8, 12 ); // Size of array$n = count($arr); print(findMaxGCD($arr, $n)); // This code is contributed by mits?>", "e": 44912, "s": 43495, "text": null }, { "code": "<script>// javascript Code to// Find pair with// maximum GCD in// an array // function to find // GCD of pair with // max GCD in the // array function findMaxGCD(arr , n) { // Calculating MAX in // array var high = 0; for (let i = 0; i < n; i++) high = Math.max(high, arr[i]); // Maintaining count array var count = Array(high + 1).fill(0); for (let i = 0; i < n; i++) count[arr[i]]++; // Variable to store // the multiples of // a number var counter = 0; // Iterating from MAX // to 1 GCD is always // between MAX and 1 // The first GCD found // will be the highest // as we are decrementing // the potential GCD for (let i = high; i >= 1; i--) { var j = i; // Iterating from current // potential GCD till it // is less than MAX while (j <= high) { // A multiple found if (count[j] > 0) counter += count[j]; // Incrementing potential // GCD by itself // To check i, 2i, 3i.... j += i; // 2 multiples found, // max GCD found if (counter == 2) return i; } counter = 0; } return 1; } /* Driver program to test above function */ // Array in which pair // with max GCD is to // be found var arr = [ 1, 2, 4, 8, 8, 12 ]; // Size of array var n = arr.length; document.write(findMaxGCD(arr, n)); // This code is contributed by aashish1995</script>", "e": 46688, "s": 44912, "text": null }, { "code": null, "e": 46698, "s": 46688, "text": "Output: " }, { "code": null, "e": 46700, "s": 46698, "text": "8" }, { "code": null, "e": 47242, "s": 46700, "text": "Time Complexity: The time complexity of this approach is till an open problem known as the Dirichlet divisor problem. This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 47247, "s": 47242, "text": "vt_m" }, { "code": null, "e": 47260, "s": 47247, "text": "Mithun Kumar" }, { "code": null, "e": 47274, "s": 47260, "text": "manikantkumar" }, { "code": null, "e": 47289, "s": 47274, "text": "Jainish Shah 1" }, { "code": null, "e": 47302, "s": 47289, "text": "Akanksha_Rai" }, { "code": null, "e": 47312, "s": 47302, "text": "harshit23" }, { "code": null, "e": 47324, "s": 47312, "text": "aashish1995" }, { "code": null, "e": 47341, "s": 47324, "text": "shikhasingrajput" }, { "code": null, "e": 47349, "s": 47341, "text": "GCD-LCM" }, { "code": null, "e": 47355, "s": 47349, "text": "sieve" }, { "code": null, "e": 47368, "s": 47355, "text": "Mathematical" }, { "code": null, "e": 47381, "s": 47368, "text": "Mathematical" }, { "code": null, "e": 47387, "s": 47381, "text": "sieve" }, { "code": null, "e": 47485, "s": 47387, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 47494, "s": 47485, "text": "Comments" }, { "code": null, "e": 47507, "s": 47494, "text": "Old Comments" }, { "code": null, "e": 47531, "s": 47507, "text": "Merge two sorted arrays" }, { "code": null, "e": 47574, "s": 47531, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 47588, "s": 47574, "text": "Prime Numbers" }, { "code": null, "e": 47637, "s": 47588, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 47658, "s": 47637, "text": "Operators in C / C++" }, { "code": null, "e": 47692, "s": 47658, "text": "Program for factorial of a number" }, { "code": null, "e": 47724, "s": 47692, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 47797, "s": 47724, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 47840, "s": 47797, "text": "The Knight's tour problem | Backtracking-1" } ]
Swap nodes in a linked list without swapping data - GeeksforGeeks
25 Feb, 2022 Given a linked list and two keys in it, swap nodes for two given keys. Nodes should be swapped by changing links. Swapping data of nodes may be expensive in many situations when data contains many fields. It may be assumed that all keys in the linked list are distinct. Examples: Input : 10->15->12->13->20->14, x = 12, y = 20 Output: 10->15->20->13->12->14 Input : 10->15->12->13->20->14, x = 10, y = 20 Output: 20->15->12->13->10->14 Input : 10->15->12->13->20->14, x = 12, y = 13 Output: 10->15->13->12->20->14 This may look like a simple problem, but is an interesting question as it has the following cases to be handled. x and y may or may not be adjacent.Either x or y may be a head node.Either x or y may be the last node.x and/or y may not be present in the linked list. x and y may or may not be adjacent. Either x or y may be a head node. Either x or y may be the last node. x and/or y may not be present in the linked list. How to write a clean working code that handles all the above possibilities. The idea is to first search x and y in the given linked list. If any of them is not present, then return. While searching for x and y, keep track of current and previous pointers. First change next of previous pointers, then change next of current pointers. Below is the implementation of the above approach. C++ C Java Python C# Javascript /* This program swaps the nodes of linked list ratherthan swapping the field from the nodes.*/#include <bits/stdc++.h>using namespace std; /* A linked list node */class Node {public: int data; Node* next;}; /* Function to swap nodes x and y in linked list bychanging links */void swapNodes(Node** head_ref, int x, int y){ // Nothing to do if x and y are same if (x == y) return; // Search for x (keep track of prevX and CurrX Node *prevX = NULL, *currX = *head_ref; while (currX && currX->data != x) { prevX = currX; currX = currX->next; } // Search for y (keep track of prevY and CurrY Node *prevY = NULL, *currY = *head_ref; while (currY && currY->data != y) { prevY = currY; currY = currY->next; } // If either x or y is not present, nothing to do if (currX == NULL || currY == NULL) return; // If x is not head of linked list if (prevX != NULL) prevX->next = currY; else // Else make y as new head *head_ref = currY; // If y is not head of linked list if (prevY != NULL) prevY->next = currX; else // Else make x as new head *head_ref = currX; // Swap next pointers Node* temp = currY->next; currY->next = currX->next; currX->next = temp;} /* Function to add a node at the beginning of List */void push(Node** head_ref, int new_data){ /* allocate node */ Node* new_node = new Node(); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print nodes in a given linked list */void printList(Node* node){ while (node != NULL) { cout << node->data << " "; node = node->next; }} /* Driver program to test above function */int main(){ Node* start = NULL; /* The constructed linked list is: 1->2->3->4->5->6->7 */ push(&start, 7); push(&start, 6); push(&start, 5); push(&start, 4); push(&start, 3); push(&start, 2); push(&start, 1); cout << "Linked list before calling swapNodes() "; printList(start); swapNodes(&start, 4, 3); cout << "\nLinked list after calling swapNodes() "; printList(start); return 0;} // This is code is contributed by rathbhupendra /* This program swaps the nodes of linked list rather than swapping the field from the nodes.*/ #include <stdio.h>#include <stdlib.h> /* A linked list node */struct Node { int data; struct Node* next;}; /* Function to swap nodes x and y in linked list by changing links */void swapNodes(struct Node** head_ref, int x, int y){ // Nothing to do if x and y are same if (x == y) return; // Search for x (keep track of prevX and CurrX struct Node *prevX = NULL, *currX = *head_ref; while (currX && currX->data != x) { prevX = currX; currX = currX->next; } // Search for y (keep track of prevY and CurrY struct Node *prevY = NULL, *currY = *head_ref; while (currY && currY->data != y) { prevY = currY; currY = currY->next; } // If either x or y is not present, nothing to do if (currX == NULL || currY == NULL) return; // If x is not head of linked list if (prevX != NULL) prevX->next = currY; else // Else make y as new head *head_ref = currY; // If y is not head of linked list if (prevY != NULL) prevY->next = currX; else // Else make x as new head *head_ref = currX; // Swap next pointers struct Node* temp = currY->next; currY->next = currX->next; currX->next = temp;} /* Function to add a node at the beginning of List */void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print nodes in a given linked list */void printList(struct Node* node){ while (node != NULL) { printf("%d ", node->data); node = node->next; }} /* Driver program to test above function */int main(){ struct Node* start = NULL; /* The constructed linked list is: 1->2->3->4->5->6->7 */ push(&start, 7); push(&start, 6); push(&start, 5); push(&start, 4); push(&start, 3); push(&start, 2); push(&start, 1); printf("\n Linked list before calling swapNodes() "); printList(start); swapNodes(&start, 4, 3); printf("\n Linked list after calling swapNodes() "); printList(start); return 0;} // Java program to swap two given nodes of a linked list class Node { int data; Node next; Node(int d) { data = d; next = null; }} class LinkedList { Node head; // head of list /* Function to swap Nodes x and y in linked list by changing links */ public void swapNodes(int x, int y) { // Nothing to do if x and y are same if (x == y) return; // Search for x (keep track of prevX and CurrX) Node prevX = null, currX = head; while (currX != null && currX.data != x) { prevX = currX; currX = currX.next; } // Search for y (keep track of prevY and currY) Node prevY = null, currY = head; while (currY != null && currY.data != y) { prevY = currY; currY = currY.next; } // If either x or y is not present, nothing to do if (currX == null || currY == null) return; // If x is not head of linked list if (prevX != null) prevX.next = currY; else // make y the new head head = currY; // If y is not head of linked list if (prevY != null) prevY.next = currX; else // make x the new head head = currX; // Swap next pointers Node temp = currX.next; currX.next = currY.next; currY.next = temp; } /* Function to add Node at beginning of list. */ public void push(int new_data) { /* 1. alloc the Node and put the data */ Node new_Node = new Node(new_data); /* 2. Make next of new Node as head */ new_Node.next = head; /* 3. Move the head to point to new Node */ head = new_Node; } /* This function prints contents of linked list starting from the given Node */ public void printList() { Node tNode = head; while (tNode != null) { System.out.print(tNode.data + " "); tNode = tNode.next; } } /* Driver program to test above function */ public static void main(String[] args) { LinkedList llist = new LinkedList(); /* The constructed linked list is: 1->2->3->4->5->6->7 */ llist.push(7); llist.push(6); llist.push(5); llist.push(4); llist.push(3); llist.push(2); llist.push(1); System.out.print( "\n Linked list before calling swapNodes() "); llist.printList(); llist.swapNodes(4, 3); System.out.print( "\n Linked list after calling swapNodes() "); llist.printList(); }}// This code is contributed by Rajat Mishra # Python program to swap two given nodes of a linked listclass LinkedList(object): def __init__(self): self.head = None # head of list class Node(object): def __init__(self, d): self.data = d self.next = None # Function to swap Nodes x and y in linked list by # changing links def swapNodes(self, x, y): # Nothing to do if x and y are same if x == y: return # Search for x (keep track of prevX and CurrX) prevX = None currX = self.head while currX != None and currX.data != x: prevX = currX currX = currX.next # Search for y (keep track of prevY and currY) prevY = None currY = self.head while currY != None and currY.data != y: prevY = currY currY = currY.next # If either x or y is not present, nothing to do if currX == None or currY == None: return # If x is not head of linked list if prevX != None: prevX.next = currY else: # make y the new head self.head = currY # If y is not head of linked list if prevY != None: prevY.next = currX else: # make x the new head self.head = currX # Swap next pointers temp = currX.next currX.next = currY.next currY.next = temp # Function to add Node at beginning of list. def push(self, new_data): # 1. alloc the Node and put the data new_Node = self.Node(new_data) # 2. Make next of new Node as head new_Node.next = self.head # 3. Move the head to point to new Node self.head = new_Node # This function prints contents of linked list starting # from the given Node def printList(self): tNode = self.head while tNode != None: print tNode.data, tNode = tNode.next # Driver program to test above functionllist = LinkedList() # The constructed linked list is:# 1->2->3->4->5->6->7llist.push(7)llist.push(6)llist.push(5)llist.push(4)llist.push(3)llist.push(2)llist.push(1)print "Linked list before calling swapNodes() "llist.printList()llist.swapNodes(4, 3)print "\nLinked list after calling swapNodes() "llist.printList() # This code is contributed by BHAVYA JAIN // C# program to swap two given// nodes of a linked listusing System; class Node { public int data; public Node next; public Node(int d) { data = d; next = null; }} public class LinkedList { Node head; // head of list /* Function to swap Nodes x and y in linked list by changing links */ public void swapNodes(int x, int y) { // Nothing to do if x and y are same if (x == y) return; // Search for x (keep track of prevX and CurrX) Node prevX = null, currX = head; while (currX != null && currX.data != x) { prevX = currX; currX = currX.next; } // Search for y (keep track of prevY and currY) Node prevY = null, currY = head; while (currY != null && currY.data != y) { prevY = currY; currY = currY.next; } // If either x or y is not present, nothing to do if (currX == null || currY == null) return; // If x is not head of linked list if (prevX != null) prevX.next = currY; else // make y the new head head = currY; // If y is not head of linked list if (prevY != null) prevY.next = currX; else // make x the new head head = currX; // Swap next pointers Node temp = currX.next; currX.next = currY.next; currY.next = temp; } /* Function to add Node at beginning of list. */ public void push(int new_data) { /* 1. alloc the Node and put the data */ Node new_Node = new Node(new_data); /* 2. Make next of new Node as head */ new_Node.next = head; /* 3. Move the head to point to new Node */ head = new_Node; } /* This function prints contents of linked list starting from the given Node */ public void printList() { Node tNode = head; while (tNode != null) { Console.Write(tNode.data + " "); tNode = tNode.next; } } /* Driver code */ public static void Main(String[] args) { LinkedList llist = new LinkedList(); /* The constructed linked list is: 1->2->3->4->5->6->7 */ llist.push(7); llist.push(6); llist.push(5); llist.push(4); llist.push(3); llist.push(2); llist.push(1); Console.Write( "\n Linked list before calling swapNodes() "); llist.printList(); llist.swapNodes(4, 3); Console.Write( "\n Linked list after calling swapNodes() "); llist.printList(); }} // This code is contributed by 29AjayKumar <script> // JavaScript program to swap two// given nodes of a linked list class Node { constructor(val) { this.data = val; this.next = null; }}var head; // head of list /* Function to swap Nodes x and y in linked list by changing links */ function swapNodes(x , y) { // Nothing to do if x and y are same if (x == y) return; // Search for x (keep track of prevX and CurrX) var prevX = null, currX = head; while (currX != null && currX.data != x) { prevX = currX; currX = currX.next; } // Search for y (keep track of prevY and currY) var prevY = null, currY = head; while (currY != null && currY.data != y) { prevY = currY; currY = currY.next; } // If either x or y is not present, nothing to do if (currX == null || currY == null) return; // If x is not head of linked list if (prevX != null) prevX.next = currY; else // make y the new head head = currY; // If y is not head of linked list if (prevY != null) prevY.next = currX; else // make x the new head head = currX; // Swap next pointers var temp = currX.next; currX.next = currY.next; currY.next = temp; } /* Function to add Node at beginning of list. */ function push(new_data) { /* 1. alloc the Node and put the data */var new_Node = new Node(new_data); /* 2. Make next of new Node as head */ new_Node.next = head; /* 3. Move the head to point to new Node */ head = new_Node; } /* This function prints contents of linked list starting from the given Node */ function printList() { var tNode = head; while (tNode != null) { document.write(tNode.data + " "); tNode = tNode.next; } } /* Driver program to test above function */ /* The constructed linked list is: 1->2->3->4->5->6->7 */ push(7); push(6); push(5); push(4); push(3); push(2); push(1); document.write( " Linked list before calling swapNodes()<br/> ") ; printList(); swapNodes(4, 3); document.write( "<br/> Linked list after calling swapNodes() <br/>" ); printList(); // This code is contributed by todaysgaurav </script> Linked list before calling swapNodes() 1 2 3 4 5 6 7 Linked list after calling swapNodes() 1 2 4 3 5 6 7 Optimizations: The above code can be optimized to search x and y in a single traversal. Two loops are used to keep the program simple. Simpler approach – C++ Java Python3 C# Javascript // C++ program to swap two given nodes of a linked list#include <iostream> using namespace std; // A linked list node classclass Node { public: int data; class Node* next; // constructor Node(int val, Node* next) : data(val) , next(next) { } // print list from this // to last till null void printList() { Node* node = this; while (node != NULL) { cout << node->data << " "; node = node->next; } cout << endl; }}; // Function to add a node// at the beginning of Listvoid push(Node** head_ref, int new_data){ // allocate node (*head_ref) = new Node(new_data, *head_ref);} void swap(Node*& a, Node*& b){ Node* temp = a; a = b; b = temp;} void swapNodes(Node** head_ref, int x, int y){ // Nothing to do if x and y are same if (x == y) return; Node **a = NULL, **b = NULL; // search for x and y in the linked list // and store their pointer in a and b while (*head_ref) { if ((*head_ref)->data == x) { a = head_ref; } else if ((*head_ref)->data == y) { b = head_ref; } head_ref = &((*head_ref)->next); } // if we have found both a and b // in the linked list swap current // pointer and next pointer of these if (a && b) { swap(*a, *b); swap(((*a)->next), ((*b)->next)); }} // Driver codeint main(){ Node* start = NULL; // The constructed linked list is: // 1->2->3->4->5->6->7 push(&start, 7); push(&start, 6); push(&start, 5); push(&start, 4); push(&start, 3); push(&start, 2); push(&start, 1); cout << "Linked list before calling swapNodes() "; start->printList(); swapNodes(&start, 6, 1); cout << "Linked list after calling swapNodes() "; start->printList();} // Java program to swap two given nodes of a linked listpublic class Solution { // Represent a node of the singly linked list class Node { int data; Node next; public Node(int data) { this.data = data; this.next = null; } } // Represent the head and tail of the singly linked list public Node head = null; public Node tail = null; // addNode() will add a new node to the list public void addNode(int data) { // Create a new node Node newNode = new Node(data); // Checks if the list is empty if (head == null) { // If list is empty, both head and // tail will point to new node head = newNode; tail = newNode; } else { // newNode will be added after tail such that // tail's next will point to newNode tail.next = newNode; // newNode will become new tail of the list tail = newNode; } } // swap() will swap the given two nodes public void swap(int n1, int n2) { Node prevNode1 = null, prevNode2 = null, node1 = head, node2 = head; // Checks if list is empty if (head == null) { return; } // If n1 and n2 are equal, then // list will remain the same if (n1 == n2) return; // Search for node1 while (node1 != null && node1.data != n1) { prevNode1 = node1; node1 = node1.next; } // Search for node2 while (node2 != null && node2.data != n2) { prevNode2 = node2; node2 = node2.next; } if (node1 != null && node2 != null) { // If previous node to node1 is not null then, // it will point to node2 if (prevNode1 != null) prevNode1.next = node2; else head = node2; // If previous node to node2 is not null then, // it will point to node1 if (prevNode2 != null) prevNode2.next = node1; else head = node1; // Swaps the next nodes of node1 and node2 Node temp = node1.next; node1.next = node2.next; node2.next = temp; } else { System.out.println("Swapping is not possible"); } } // display() will display all the // nodes present in the list public void display() { // Node current will point to head Node current = head; if (head == null) { System.out.println("List is empty"); return; } while (current != null) { // Prints each node by incrementing pointer System.out.print(current.data + " "); current = current.next; } System.out.println(); } public static void main(String[] args) { Solution sList = new Solution(); // Add nodes to the list sList.addNode(1); sList.addNode(2); sList.addNode(3); sList.addNode(4); sList.addNode(5); sList.addNode(6); sList.addNode(7); System.out.println("Original list: "); sList.display(); // Swaps the node 2 with node 5 sList.swap(6, 1); System.out.println("List after swapping nodes: "); sList.display(); }} # Python3 program to swap two given# nodes of a linked list # A linked list node class class Node: # constructor def __init__(self, val=None, next1=None): self.data = val self.next = next1 # print list from this # to last till None def printList(self): node = self while (node != None): print(node.data, end=" ") node = node.next print(" ") # Function to add a node# at the beginning of List def push(head_ref, new_data): # allocate node (head_ref) = Node(new_data, head_ref) return head_ref def swapNodes(head_ref, x, y): head = head_ref # Nothing to do if x and y are same if (x == y): return None a = None b = None # search for x and y in the linked list # and store their pointer in a and b while (head_ref.next != None): if ((head_ref.next).data == x): a = head_ref elif ((head_ref.next).data == y): b = head_ref head_ref = ((head_ref).next) # if we have found both a and b # in the linked list swap current # pointer and next pointer of these if (a != None and b != None): temp = a.next a.next = b.next b.next = temp temp = a.next.next a.next.next = b.next.next b.next.next = temp return head # Driver code start = None # The constructed linked list is:# 1.2.3.4.5.6.7start = push(start, 7)start = push(start, 6)start = push(start, 5)start = push(start, 4)start = push(start, 3)start = push(start, 2)start = push(start, 1) print("Linked list before calling swapNodes() ")start.printList() start = swapNodes(start, 6, 1) print("Linked list after calling swapNodes() ")start.printList() # This code is contributed by Arnab Kundu // C# program to swap two// given nodes of a linked listusing System; class GFG { // A linked list node class public class Node { public int data; public Node next; // constructor public Node(int val, Node next1) { data = val; next = next1; } // print list from this // to last till null public void printList() { Node node = this; while (node != null) { Console.Write(node.data + " "); node = node.next; } Console.WriteLine(); } } // Function to add a node // at the beginning of List static Node push(Node head_ref, int new_data) { // allocate node (head_ref) = new Node(new_data, head_ref); return head_ref; } static Node swapNodes(Node head_ref, int x, int y) { Node head = head_ref; // Nothing to do if x and y are same if (x == y) return null; Node a = null, b = null; // search for x and y in the linked list // and store their pointer in a and b while (head_ref.next != null) { if ((head_ref.next).data == x) { a = head_ref; } else if ((head_ref.next).data == y) { b = head_ref; } head_ref = ((head_ref).next); } // if we have found both a and b // in the linked list swap current // pointer and next pointer of these if (a != null && b != null) { Node temp = a.next; a.next = b.next; b.next = temp; temp = a.next.next; a.next.next = b.next.next; b.next.next = temp; } return head; } // Driver code public static void Main() { Node start = null; // The constructed linked list is: // 1.2.3.4.5.6.7 start = push(start, 7); start = push(start, 6); start = push(start, 5); start = push(start, 4); start = push(start, 3); start = push(start, 2); start = push(start, 1); Console.Write( "Linked list before calling swapNodes() "); start.printList(); start = swapNodes(start, 6, 1); Console.Write( "Linked list after calling swapNodes() "); start.printList(); }} /* This code contributed by PrinciRaj1992 */ <script>// javascript program to swap two given nodes of a linked list // Represent a node of the singly linked list class Node { constructor(val) { this.data = val; this.next = null; } } // Represent the head and tail of the singly linked list var head = null; var tail = null; // addNode() will add a new node to the list function addNode(data) { // Create a new nodevar newNode = new Node(data); // Checks if the list is empty if (head == null) { // If list is empty, both head and // tail will point to new node head = newNode; tail = newNode; } else { // newNode will be added after tail such that // tail's next will point to newNode tail.next = newNode; // newNode will become new tail of the list tail = newNode; } } // swap() will swap the given two nodes function swap(n1 , n2) {var prevNode1 = null, prevNode2 = null, node1 = head, node2 = head; // Checks if list is empty if (head == null) { return; } // If n1 and n2 are equal, then // list will remain the same if (n1 == n2) return; // Search for node1 while (node1 != null && node1.data != n1) { prevNode1 = node1; node1 = node1.next; } // Search for node2 while (node2 != null && node2.data != n2) { prevNode2 = node2; node2 = node2.next; } if (node1 != null && node2 != null) { // If previous node to node1 is not null then, // it will point to node2 if (prevNode1 != null) prevNode1.next = node2; else head = node2; // If previous node to node2 is not null then, // it will point to node1 if (prevNode2 != null) prevNode2.next = node1; else head = node1; // Swaps the next nodes of node1 and node2 var temp = node1.next; node1.next = node2.next; node2.next = temp; } else { document.write("Swapping is not possible"); } } // display() will display all the // nodes present in the list function display() { // Node current will point to headvar current = head; if (head == null) { document.write("List is empty"); return; } while (current != null) { // Prints each node by incrementing pointer document.write(current.data + " "); current = current.next; } document.write(); } // Add nodes to the list addNode(1); addNode(2); addNode(3); addNode(4); addNode(5); addNode(6); addNode(7); document.write("Original list:<br/> "); display(); // Swaps the node 2 with node 5 swap(6, 1); document.write("<br/>List after swapping nodes: <br/>"); display(); // This code contributed by aashish1995</script> Linked list before calling swapNodes() 1 2 3 4 5 6 7 Linked list after calling swapNodes() 6 2 3 4 5 1 7 https://www.youtube.com/watch?v=V4ZHvhvVmSE This article is contributed by Gautam. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. andrew1234 29AjayKumar princiraj1992 rathbhupendra Akanksha_Rai nidhi_biet arshita1902 che10 todaysgaurav aashish1995 simranarora5sos niharikatanwar61 surinderdawra388 Linked List Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Linked List | Set 1 (Introduction) Linked List | Set 2 (Inserting a node) Stack Data Structure (Introduction and Program) Linked List | Set 3 (Deleting a node) LinkedList in Java Linked List vs Array Delete a Linked List node at a given position Implementing a Linked List in Java using Class Detect loop in a linked list Queue - Linked List Implementation
[ { "code": null, "e": 30932, "s": 30904, "text": "\n25 Feb, 2022" }, { "code": null, "e": 31138, "s": 30932, "text": "Given a linked list and two keys in it, swap nodes for two given keys. Nodes should be swapped by changing links. Swapping data of nodes may be expensive in many situations when data contains many fields. " }, { "code": null, "e": 31203, "s": 31138, "text": "It may be assumed that all keys in the linked list are distinct." }, { "code": null, "e": 31214, "s": 31203, "text": "Examples: " }, { "code": null, "e": 31453, "s": 31214, "text": "Input : 10->15->12->13->20->14, x = 12, y = 20\nOutput: 10->15->20->13->12->14\n\nInput : 10->15->12->13->20->14, x = 10, y = 20\nOutput: 20->15->12->13->10->14\n\nInput : 10->15->12->13->20->14, x = 12, y = 13\nOutput: 10->15->13->12->20->14" }, { "code": null, "e": 31567, "s": 31453, "text": "This may look like a simple problem, but is an interesting question as it has the following cases to be handled. " }, { "code": null, "e": 31720, "s": 31567, "text": "x and y may or may not be adjacent.Either x or y may be a head node.Either x or y may be the last node.x and/or y may not be present in the linked list." }, { "code": null, "e": 31756, "s": 31720, "text": "x and y may or may not be adjacent." }, { "code": null, "e": 31790, "s": 31756, "text": "Either x or y may be a head node." }, { "code": null, "e": 31826, "s": 31790, "text": "Either x or y may be the last node." }, { "code": null, "e": 31876, "s": 31826, "text": "x and/or y may not be present in the linked list." }, { "code": null, "e": 31952, "s": 31876, "text": "How to write a clean working code that handles all the above possibilities." }, { "code": null, "e": 32211, "s": 31952, "text": "The idea is to first search x and y in the given linked list. If any of them is not present, then return. While searching for x and y, keep track of current and previous pointers. First change next of previous pointers, then change next of current pointers. " }, { "code": null, "e": 32263, "s": 32211, "text": "Below is the implementation of the above approach. " }, { "code": null, "e": 32267, "s": 32263, "text": "C++" }, { "code": null, "e": 32269, "s": 32267, "text": "C" }, { "code": null, "e": 32274, "s": 32269, "text": "Java" }, { "code": null, "e": 32281, "s": 32274, "text": "Python" }, { "code": null, "e": 32284, "s": 32281, "text": "C#" }, { "code": null, "e": 32295, "s": 32284, "text": "Javascript" }, { "code": "/* This program swaps the nodes of linked list ratherthan swapping the field from the nodes.*/#include <bits/stdc++.h>using namespace std; /* A linked list node */class Node {public: int data; Node* next;}; /* Function to swap nodes x and y in linked list bychanging links */void swapNodes(Node** head_ref, int x, int y){ // Nothing to do if x and y are same if (x == y) return; // Search for x (keep track of prevX and CurrX Node *prevX = NULL, *currX = *head_ref; while (currX && currX->data != x) { prevX = currX; currX = currX->next; } // Search for y (keep track of prevY and CurrY Node *prevY = NULL, *currY = *head_ref; while (currY && currY->data != y) { prevY = currY; currY = currY->next; } // If either x or y is not present, nothing to do if (currX == NULL || currY == NULL) return; // If x is not head of linked list if (prevX != NULL) prevX->next = currY; else // Else make y as new head *head_ref = currY; // If y is not head of linked list if (prevY != NULL) prevY->next = currX; else // Else make x as new head *head_ref = currX; // Swap next pointers Node* temp = currY->next; currY->next = currX->next; currX->next = temp;} /* Function to add a node at the beginning of List */void push(Node** head_ref, int new_data){ /* allocate node */ Node* new_node = new Node(); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print nodes in a given linked list */void printList(Node* node){ while (node != NULL) { cout << node->data << \" \"; node = node->next; }} /* Driver program to test above function */int main(){ Node* start = NULL; /* The constructed linked list is: 1->2->3->4->5->6->7 */ push(&start, 7); push(&start, 6); push(&start, 5); push(&start, 4); push(&start, 3); push(&start, 2); push(&start, 1); cout << \"Linked list before calling swapNodes() \"; printList(start); swapNodes(&start, 4, 3); cout << \"\\nLinked list after calling swapNodes() \"; printList(start); return 0;} // This is code is contributed by rathbhupendra", "e": 34647, "s": 32295, "text": null }, { "code": "/* This program swaps the nodes of linked list rather than swapping the field from the nodes.*/ #include <stdio.h>#include <stdlib.h> /* A linked list node */struct Node { int data; struct Node* next;}; /* Function to swap nodes x and y in linked list by changing links */void swapNodes(struct Node** head_ref, int x, int y){ // Nothing to do if x and y are same if (x == y) return; // Search for x (keep track of prevX and CurrX struct Node *prevX = NULL, *currX = *head_ref; while (currX && currX->data != x) { prevX = currX; currX = currX->next; } // Search for y (keep track of prevY and CurrY struct Node *prevY = NULL, *currY = *head_ref; while (currY && currY->data != y) { prevY = currY; currY = currY->next; } // If either x or y is not present, nothing to do if (currX == NULL || currY == NULL) return; // If x is not head of linked list if (prevX != NULL) prevX->next = currY; else // Else make y as new head *head_ref = currY; // If y is not head of linked list if (prevY != NULL) prevY->next = currX; else // Else make x as new head *head_ref = currX; // Swap next pointers struct Node* temp = currY->next; currY->next = currX->next; currX->next = temp;} /* Function to add a node at the beginning of List */void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print nodes in a given linked list */void printList(struct Node* node){ while (node != NULL) { printf(\"%d \", node->data); node = node->next; }} /* Driver program to test above function */int main(){ struct Node* start = NULL; /* The constructed linked list is: 1->2->3->4->5->6->7 */ push(&start, 7); push(&start, 6); push(&start, 5); push(&start, 4); push(&start, 3); push(&start, 2); push(&start, 1); printf(\"\\n Linked list before calling swapNodes() \"); printList(start); swapNodes(&start, 4, 3); printf(\"\\n Linked list after calling swapNodes() \"); printList(start); return 0;}", "e": 37052, "s": 34647, "text": null }, { "code": "// Java program to swap two given nodes of a linked list class Node { int data; Node next; Node(int d) { data = d; next = null; }} class LinkedList { Node head; // head of list /* Function to swap Nodes x and y in linked list by changing links */ public void swapNodes(int x, int y) { // Nothing to do if x and y are same if (x == y) return; // Search for x (keep track of prevX and CurrX) Node prevX = null, currX = head; while (currX != null && currX.data != x) { prevX = currX; currX = currX.next; } // Search for y (keep track of prevY and currY) Node prevY = null, currY = head; while (currY != null && currY.data != y) { prevY = currY; currY = currY.next; } // If either x or y is not present, nothing to do if (currX == null || currY == null) return; // If x is not head of linked list if (prevX != null) prevX.next = currY; else // make y the new head head = currY; // If y is not head of linked list if (prevY != null) prevY.next = currX; else // make x the new head head = currX; // Swap next pointers Node temp = currX.next; currX.next = currY.next; currY.next = temp; } /* Function to add Node at beginning of list. */ public void push(int new_data) { /* 1. alloc the Node and put the data */ Node new_Node = new Node(new_data); /* 2. Make next of new Node as head */ new_Node.next = head; /* 3. Move the head to point to new Node */ head = new_Node; } /* This function prints contents of linked list starting from the given Node */ public void printList() { Node tNode = head; while (tNode != null) { System.out.print(tNode.data + \" \"); tNode = tNode.next; } } /* Driver program to test above function */ public static void main(String[] args) { LinkedList llist = new LinkedList(); /* The constructed linked list is: 1->2->3->4->5->6->7 */ llist.push(7); llist.push(6); llist.push(5); llist.push(4); llist.push(3); llist.push(2); llist.push(1); System.out.print( \"\\n Linked list before calling swapNodes() \"); llist.printList(); llist.swapNodes(4, 3); System.out.print( \"\\n Linked list after calling swapNodes() \"); llist.printList(); }}// This code is contributed by Rajat Mishra", "e": 39735, "s": 37052, "text": null }, { "code": "# Python program to swap two given nodes of a linked listclass LinkedList(object): def __init__(self): self.head = None # head of list class Node(object): def __init__(self, d): self.data = d self.next = None # Function to swap Nodes x and y in linked list by # changing links def swapNodes(self, x, y): # Nothing to do if x and y are same if x == y: return # Search for x (keep track of prevX and CurrX) prevX = None currX = self.head while currX != None and currX.data != x: prevX = currX currX = currX.next # Search for y (keep track of prevY and currY) prevY = None currY = self.head while currY != None and currY.data != y: prevY = currY currY = currY.next # If either x or y is not present, nothing to do if currX == None or currY == None: return # If x is not head of linked list if prevX != None: prevX.next = currY else: # make y the new head self.head = currY # If y is not head of linked list if prevY != None: prevY.next = currX else: # make x the new head self.head = currX # Swap next pointers temp = currX.next currX.next = currY.next currY.next = temp # Function to add Node at beginning of list. def push(self, new_data): # 1. alloc the Node and put the data new_Node = self.Node(new_data) # 2. Make next of new Node as head new_Node.next = self.head # 3. Move the head to point to new Node self.head = new_Node # This function prints contents of linked list starting # from the given Node def printList(self): tNode = self.head while tNode != None: print tNode.data, tNode = tNode.next # Driver program to test above functionllist = LinkedList() # The constructed linked list is:# 1->2->3->4->5->6->7llist.push(7)llist.push(6)llist.push(5)llist.push(4)llist.push(3)llist.push(2)llist.push(1)print \"Linked list before calling swapNodes() \"llist.printList()llist.swapNodes(4, 3)print \"\\nLinked list after calling swapNodes() \"llist.printList() # This code is contributed by BHAVYA JAIN", "e": 42064, "s": 39735, "text": null }, { "code": "// C# program to swap two given// nodes of a linked listusing System; class Node { public int data; public Node next; public Node(int d) { data = d; next = null; }} public class LinkedList { Node head; // head of list /* Function to swap Nodes x and y in linked list by changing links */ public void swapNodes(int x, int y) { // Nothing to do if x and y are same if (x == y) return; // Search for x (keep track of prevX and CurrX) Node prevX = null, currX = head; while (currX != null && currX.data != x) { prevX = currX; currX = currX.next; } // Search for y (keep track of prevY and currY) Node prevY = null, currY = head; while (currY != null && currY.data != y) { prevY = currY; currY = currY.next; } // If either x or y is not present, nothing to do if (currX == null || currY == null) return; // If x is not head of linked list if (prevX != null) prevX.next = currY; else // make y the new head head = currY; // If y is not head of linked list if (prevY != null) prevY.next = currX; else // make x the new head head = currX; // Swap next pointers Node temp = currX.next; currX.next = currY.next; currY.next = temp; } /* Function to add Node at beginning of list. */ public void push(int new_data) { /* 1. alloc the Node and put the data */ Node new_Node = new Node(new_data); /* 2. Make next of new Node as head */ new_Node.next = head; /* 3. Move the head to point to new Node */ head = new_Node; } /* This function prints contents of linked list starting from the given Node */ public void printList() { Node tNode = head; while (tNode != null) { Console.Write(tNode.data + \" \"); tNode = tNode.next; } } /* Driver code */ public static void Main(String[] args) { LinkedList llist = new LinkedList(); /* The constructed linked list is: 1->2->3->4->5->6->7 */ llist.push(7); llist.push(6); llist.push(5); llist.push(4); llist.push(3); llist.push(2); llist.push(1); Console.Write( \"\\n Linked list before calling swapNodes() \"); llist.printList(); llist.swapNodes(4, 3); Console.Write( \"\\n Linked list after calling swapNodes() \"); llist.printList(); }} // This code is contributed by 29AjayKumar", "e": 44747, "s": 42064, "text": null }, { "code": "<script> // JavaScript program to swap two// given nodes of a linked list class Node { constructor(val) { this.data = val; this.next = null; }}var head; // head of list /* Function to swap Nodes x and y in linked list by changing links */ function swapNodes(x , y) { // Nothing to do if x and y are same if (x == y) return; // Search for x (keep track of prevX and CurrX) var prevX = null, currX = head; while (currX != null && currX.data != x) { prevX = currX; currX = currX.next; } // Search for y (keep track of prevY and currY) var prevY = null, currY = head; while (currY != null && currY.data != y) { prevY = currY; currY = currY.next; } // If either x or y is not present, nothing to do if (currX == null || currY == null) return; // If x is not head of linked list if (prevX != null) prevX.next = currY; else // make y the new head head = currY; // If y is not head of linked list if (prevY != null) prevY.next = currX; else // make x the new head head = currX; // Swap next pointers var temp = currX.next; currX.next = currY.next; currY.next = temp; } /* Function to add Node at beginning of list. */ function push(new_data) { /* 1. alloc the Node and put the data */var new_Node = new Node(new_data); /* 2. Make next of new Node as head */ new_Node.next = head; /* 3. Move the head to point to new Node */ head = new_Node; } /* This function prints contents of linked list starting from the given Node */ function printList() { var tNode = head; while (tNode != null) { document.write(tNode.data + \" \"); tNode = tNode.next; } } /* Driver program to test above function */ /* The constructed linked list is: 1->2->3->4->5->6->7 */ push(7); push(6); push(5); push(4); push(3); push(2); push(1); document.write( \" Linked list before calling swapNodes()<br/> \") ; printList(); swapNodes(4, 3); document.write( \"<br/> Linked list after calling swapNodes() <br/>\" ); printList(); // This code is contributed by todaysgaurav </script>", "e": 47266, "s": 44747, "text": null }, { "code": null, "e": 47373, "s": 47266, "text": "Linked list before calling swapNodes() 1 2 3 4 5 6 7 \nLinked list after calling swapNodes() 1 2 4 3 5 6 7 " }, { "code": null, "e": 47508, "s": 47373, "text": "Optimizations: The above code can be optimized to search x and y in a single traversal. Two loops are used to keep the program simple." }, { "code": null, "e": 47527, "s": 47508, "text": "Simpler approach –" }, { "code": null, "e": 47531, "s": 47527, "text": "C++" }, { "code": null, "e": 47536, "s": 47531, "text": "Java" }, { "code": null, "e": 47544, "s": 47536, "text": "Python3" }, { "code": null, "e": 47547, "s": 47544, "text": "C#" }, { "code": null, "e": 47558, "s": 47547, "text": "Javascript" }, { "code": "// C++ program to swap two given nodes of a linked list#include <iostream> using namespace std; // A linked list node classclass Node { public: int data; class Node* next; // constructor Node(int val, Node* next) : data(val) , next(next) { } // print list from this // to last till null void printList() { Node* node = this; while (node != NULL) { cout << node->data << \" \"; node = node->next; } cout << endl; }}; // Function to add a node// at the beginning of Listvoid push(Node** head_ref, int new_data){ // allocate node (*head_ref) = new Node(new_data, *head_ref);} void swap(Node*& a, Node*& b){ Node* temp = a; a = b; b = temp;} void swapNodes(Node** head_ref, int x, int y){ // Nothing to do if x and y are same if (x == y) return; Node **a = NULL, **b = NULL; // search for x and y in the linked list // and store their pointer in a and b while (*head_ref) { if ((*head_ref)->data == x) { a = head_ref; } else if ((*head_ref)->data == y) { b = head_ref; } head_ref = &((*head_ref)->next); } // if we have found both a and b // in the linked list swap current // pointer and next pointer of these if (a && b) { swap(*a, *b); swap(((*a)->next), ((*b)->next)); }} // Driver codeint main(){ Node* start = NULL; // The constructed linked list is: // 1->2->3->4->5->6->7 push(&start, 7); push(&start, 6); push(&start, 5); push(&start, 4); push(&start, 3); push(&start, 2); push(&start, 1); cout << \"Linked list before calling swapNodes() \"; start->printList(); swapNodes(&start, 6, 1); cout << \"Linked list after calling swapNodes() \"; start->printList();}", "e": 49410, "s": 47558, "text": null }, { "code": "// Java program to swap two given nodes of a linked listpublic class Solution { // Represent a node of the singly linked list class Node { int data; Node next; public Node(int data) { this.data = data; this.next = null; } } // Represent the head and tail of the singly linked list public Node head = null; public Node tail = null; // addNode() will add a new node to the list public void addNode(int data) { // Create a new node Node newNode = new Node(data); // Checks if the list is empty if (head == null) { // If list is empty, both head and // tail will point to new node head = newNode; tail = newNode; } else { // newNode will be added after tail such that // tail's next will point to newNode tail.next = newNode; // newNode will become new tail of the list tail = newNode; } } // swap() will swap the given two nodes public void swap(int n1, int n2) { Node prevNode1 = null, prevNode2 = null, node1 = head, node2 = head; // Checks if list is empty if (head == null) { return; } // If n1 and n2 are equal, then // list will remain the same if (n1 == n2) return; // Search for node1 while (node1 != null && node1.data != n1) { prevNode1 = node1; node1 = node1.next; } // Search for node2 while (node2 != null && node2.data != n2) { prevNode2 = node2; node2 = node2.next; } if (node1 != null && node2 != null) { // If previous node to node1 is not null then, // it will point to node2 if (prevNode1 != null) prevNode1.next = node2; else head = node2; // If previous node to node2 is not null then, // it will point to node1 if (prevNode2 != null) prevNode2.next = node1; else head = node1; // Swaps the next nodes of node1 and node2 Node temp = node1.next; node1.next = node2.next; node2.next = temp; } else { System.out.println(\"Swapping is not possible\"); } } // display() will display all the // nodes present in the list public void display() { // Node current will point to head Node current = head; if (head == null) { System.out.println(\"List is empty\"); return; } while (current != null) { // Prints each node by incrementing pointer System.out.print(current.data + \" \"); current = current.next; } System.out.println(); } public static void main(String[] args) { Solution sList = new Solution(); // Add nodes to the list sList.addNode(1); sList.addNode(2); sList.addNode(3); sList.addNode(4); sList.addNode(5); sList.addNode(6); sList.addNode(7); System.out.println(\"Original list: \"); sList.display(); // Swaps the node 2 with node 5 sList.swap(6, 1); System.out.println(\"List after swapping nodes: \"); sList.display(); }}", "e": 52850, "s": 49410, "text": null }, { "code": "# Python3 program to swap two given# nodes of a linked list # A linked list node class class Node: # constructor def __init__(self, val=None, next1=None): self.data = val self.next = next1 # print list from this # to last till None def printList(self): node = self while (node != None): print(node.data, end=\" \") node = node.next print(\" \") # Function to add a node# at the beginning of List def push(head_ref, new_data): # allocate node (head_ref) = Node(new_data, head_ref) return head_ref def swapNodes(head_ref, x, y): head = head_ref # Nothing to do if x and y are same if (x == y): return None a = None b = None # search for x and y in the linked list # and store their pointer in a and b while (head_ref.next != None): if ((head_ref.next).data == x): a = head_ref elif ((head_ref.next).data == y): b = head_ref head_ref = ((head_ref).next) # if we have found both a and b # in the linked list swap current # pointer and next pointer of these if (a != None and b != None): temp = a.next a.next = b.next b.next = temp temp = a.next.next a.next.next = b.next.next b.next.next = temp return head # Driver code start = None # The constructed linked list is:# 1.2.3.4.5.6.7start = push(start, 7)start = push(start, 6)start = push(start, 5)start = push(start, 4)start = push(start, 3)start = push(start, 2)start = push(start, 1) print(\"Linked list before calling swapNodes() \")start.printList() start = swapNodes(start, 6, 1) print(\"Linked list after calling swapNodes() \")start.printList() # This code is contributed by Arnab Kundu", "e": 54612, "s": 52850, "text": null }, { "code": "// C# program to swap two// given nodes of a linked listusing System; class GFG { // A linked list node class public class Node { public int data; public Node next; // constructor public Node(int val, Node next1) { data = val; next = next1; } // print list from this // to last till null public void printList() { Node node = this; while (node != null) { Console.Write(node.data + \" \"); node = node.next; } Console.WriteLine(); } } // Function to add a node // at the beginning of List static Node push(Node head_ref, int new_data) { // allocate node (head_ref) = new Node(new_data, head_ref); return head_ref; } static Node swapNodes(Node head_ref, int x, int y) { Node head = head_ref; // Nothing to do if x and y are same if (x == y) return null; Node a = null, b = null; // search for x and y in the linked list // and store their pointer in a and b while (head_ref.next != null) { if ((head_ref.next).data == x) { a = head_ref; } else if ((head_ref.next).data == y) { b = head_ref; } head_ref = ((head_ref).next); } // if we have found both a and b // in the linked list swap current // pointer and next pointer of these if (a != null && b != null) { Node temp = a.next; a.next = b.next; b.next = temp; temp = a.next.next; a.next.next = b.next.next; b.next.next = temp; } return head; } // Driver code public static void Main() { Node start = null; // The constructed linked list is: // 1.2.3.4.5.6.7 start = push(start, 7); start = push(start, 6); start = push(start, 5); start = push(start, 4); start = push(start, 3); start = push(start, 2); start = push(start, 1); Console.Write( \"Linked list before calling swapNodes() \"); start.printList(); start = swapNodes(start, 6, 1); Console.Write( \"Linked list after calling swapNodes() \"); start.printList(); }} /* This code contributed by PrinciRaj1992 */", "e": 57068, "s": 54612, "text": null }, { "code": "<script>// javascript program to swap two given nodes of a linked list // Represent a node of the singly linked list class Node { constructor(val) { this.data = val; this.next = null; } } // Represent the head and tail of the singly linked list var head = null; var tail = null; // addNode() will add a new node to the list function addNode(data) { // Create a new nodevar newNode = new Node(data); // Checks if the list is empty if (head == null) { // If list is empty, both head and // tail will point to new node head = newNode; tail = newNode; } else { // newNode will be added after tail such that // tail's next will point to newNode tail.next = newNode; // newNode will become new tail of the list tail = newNode; } } // swap() will swap the given two nodes function swap(n1 , n2) {var prevNode1 = null, prevNode2 = null, node1 = head, node2 = head; // Checks if list is empty if (head == null) { return; } // If n1 and n2 are equal, then // list will remain the same if (n1 == n2) return; // Search for node1 while (node1 != null && node1.data != n1) { prevNode1 = node1; node1 = node1.next; } // Search for node2 while (node2 != null && node2.data != n2) { prevNode2 = node2; node2 = node2.next; } if (node1 != null && node2 != null) { // If previous node to node1 is not null then, // it will point to node2 if (prevNode1 != null) prevNode1.next = node2; else head = node2; // If previous node to node2 is not null then, // it will point to node1 if (prevNode2 != null) prevNode2.next = node1; else head = node1; // Swaps the next nodes of node1 and node2 var temp = node1.next; node1.next = node2.next; node2.next = temp; } else { document.write(\"Swapping is not possible\"); } } // display() will display all the // nodes present in the list function display() { // Node current will point to headvar current = head; if (head == null) { document.write(\"List is empty\"); return; } while (current != null) { // Prints each node by incrementing pointer document.write(current.data + \" \"); current = current.next; } document.write(); } // Add nodes to the list addNode(1); addNode(2); addNode(3); addNode(4); addNode(5); addNode(6); addNode(7); document.write(\"Original list:<br/> \"); display(); // Swaps the node 2 with node 5 swap(6, 1); document.write(\"<br/>List after swapping nodes: <br/>\"); display(); // This code contributed by aashish1995</script>", "e": 60273, "s": 57068, "text": null }, { "code": null, "e": 60380, "s": 60273, "text": "Linked list before calling swapNodes() 1 2 3 4 5 6 7 \nLinked list after calling swapNodes() 6 2 3 4 5 1 7 " }, { "code": null, "e": 60424, "s": 60380, "text": "https://www.youtube.com/watch?v=V4ZHvhvVmSE" }, { "code": null, "e": 60588, "s": 60424, "text": "This article is contributed by Gautam. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 60599, "s": 60588, "text": "andrew1234" }, { "code": null, "e": 60611, "s": 60599, "text": "29AjayKumar" }, { "code": null, "e": 60625, "s": 60611, "text": "princiraj1992" }, { "code": null, "e": 60639, "s": 60625, "text": "rathbhupendra" }, { "code": null, "e": 60652, "s": 60639, "text": "Akanksha_Rai" }, { "code": null, "e": 60663, "s": 60652, "text": "nidhi_biet" }, { "code": null, "e": 60675, "s": 60663, "text": "arshita1902" }, { "code": null, "e": 60681, "s": 60675, "text": "che10" }, { "code": null, "e": 60694, "s": 60681, "text": "todaysgaurav" }, { "code": null, "e": 60706, "s": 60694, "text": "aashish1995" }, { "code": null, "e": 60722, "s": 60706, "text": "simranarora5sos" }, { "code": null, "e": 60739, "s": 60722, "text": "niharikatanwar61" }, { "code": null, "e": 60756, "s": 60739, "text": "surinderdawra388" }, { "code": null, "e": 60768, "s": 60756, "text": "Linked List" }, { "code": null, "e": 60780, "s": 60768, "text": "Linked List" }, { "code": null, "e": 60878, "s": 60780, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 60887, "s": 60878, "text": "Comments" }, { "code": null, "e": 60900, "s": 60887, "text": "Old Comments" }, { "code": null, "e": 60935, "s": 60900, "text": "Linked List | Set 1 (Introduction)" }, { "code": null, "e": 60974, "s": 60935, "text": "Linked List | Set 2 (Inserting a node)" }, { "code": null, "e": 61022, "s": 60974, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 61060, "s": 61022, "text": "Linked List | Set 3 (Deleting a node)" }, { "code": null, "e": 61079, "s": 61060, "text": "LinkedList in Java" }, { "code": null, "e": 61100, "s": 61079, "text": "Linked List vs Array" }, { "code": null, "e": 61146, "s": 61100, "text": "Delete a Linked List node at a given position" }, { "code": null, "e": 61193, "s": 61146, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 61222, "s": 61193, "text": "Detect loop in a linked list" } ]
Merging with AI: How to Make a Brain-Computer Interface to Communicate with Google using Keras and OpenBCI | by Jag Singh | Towards Data Science
Elon Musk and Neuralink want to build a Brain-Computer Interface that can act as the third layer of the brain, allowing humans to form a symbiotic relationship with Artificial Intelligence. But what if you can already do that? In a (very) limited form, you actually can. Brain-Computer Interface (BCI) broadly refers to any system that establishes a direct connection between the nervous system and an electronic device. These devices may be surgically implanted in the brain, or they may be external. Typical paradigms include allowing a user to control an actuator or keyboard, allowing a device to send sensory data to the user, or bilateral communication involving both sensory data and motor control (i.e. a prosthetic arm that receives motor control input and sends sensory data on pressure or temperature) Historically, neuroprosthetics have been the primary motive for BCI research. These include artificial limbs for amputees, cochlear implants for the deaf, and deep brain stimulation for individuals suffering from seizures. Already, these devices have improved the lives of millions of people, and their widespread use demonstrates the benefits of achieving direct bilateral communication between the brain and electronic devices. However, the possible applications of the technology extend far beyond healthcare. Even within the realm of neuroprosthetics, we can imagine going beyond just repairing and consider augmenting our abilities beyond normal human levels. Artificial limbs may one day progress to the point where they are, by any objective criterion, superior to their natural counterparts. These limbs may look and feel just like normal limbs, but would be far stronger and more agile. Another example would be artificial eyes that are capable of far higher resolution than human eyes, an ability zoom in or out, and to see in the UV or IR spectrum. The possibilities get even more interesting when considering cognition and skill formation. A recent study demonstrates that stimulating certain parts of the brain improves memory formation and recall. Other experiments have managed to artificially implant memories in animals. As an example, it may be possible to apply the methods of these studies to improve your ability to quickly learn an instrument. Or perhaps it may be possible to combine various neurostimulators and sensors to develop an “arithmetic processing unit” that can detect when particular areas of the brain associated with mathematical or logical reasoning are activated, and communicates with them to enhance abilities. It is an extension of this cognitive augmentation that Elon Musk and Neuralink want to pursue. According to Musk and many leading AI theorists, a key barrier in humanity’s intellectual progress relative to AI is the bandwidth problem: although computers and AI are becoming ever faster and more capable of processing and generating knowledge, we face immediate and fundamental limitations in our ability to do the same. We acquire information primarily through our senses and ability to interpret language. In the time it takes your eyes and visual cortex to read and understand a single sentence, a computer can scan through thousands of pages of text. It’s conceivable that in a few decades time, we may have advanced AI running on specialized neuromorphic hardware with incredibly accurate models of how the world works and an ability to analyze and understand millions of documents in minutes, making decisions and inferences that are far beyond human comprehension. In a world increasingly dependent on AI driven decision making, humans may find themselves obsolete in all parts of the business, scientific, and political decision making process. Our brains did not evolve to play a game of chess with trillions of pieces or to comprehend calculated strategies that plan millions of moves ahead. It is a fear of this super-intelligent black box that motivates much of the current work at Neuralink, Kernel, and several other related organizations. Most of the leading edge research in BCI technology seeks to maximize the information bandwidth, typically through invasive methods that implant electrodes directly into the brain or nerves. However, non invasive methods, specifically electroencephalography (EEG) and electromyography (EMG) are routinely used with considerable success. These involve placing electrodes on the surface of your head (EEG) or skin above muscles (EMG) to measure the cumulative electrical activity underneath. The granularity of this data is low, and it is a far cry from the level of precision and bandwidth that will ultimately be needed to realize the more ambitious goals of BCI research. Nevertheless, EEG/EMG enabled BCIs have achieved incredible feats, like controlling drones, video games, and keyboards with thought, and they provide a small glimpse into the possibilities that further research may unlock. Furthermore, several companies like Cognixion and Neurable are exploring real world applications of EEG based BCIs and have received considerable funding and support with many exciting projects underway. In this project, we establish a direct connection between your nervous system and an external AI agent. This agent may be anything you can get an API for: Google Assistant, Siri, Alexa, Watson, etc. Services like Dictionary or YouTube would qualify as well, but these would limit applications to content queries rather than general purpose requests. For the purposes of this project, we will query Google Search directly as it provides the most flexibility and is the easiest to set up. Upon completion, you should be able to query a handful of terms on Google simply by thinking about them. The technique we use exploits the nerve signals generated by your brain in the process of subvocalization. This is the “internal monologue” that takes place inside your head when you slowly and deliberately read or think. You may have noticed yourself doing this when reading silently, sometimes to the point where you’re subtly moving your jaw and tongue without even realizing it. You may also have come across the concept when receiving tips for SAT, MCAT, GRE or other standardized test preparation. Test takers are advised to avoid subvocalization as it’s a bad habit that slows down reading speed. We are able to exploit subvocalization because the brain sends signals to your larynx corresponding to words you think to say, even if you don’t intend to actually say them out loud. By placing electrodes on your face over the laryngeal and mandibular nerves, we can record signals corresponding to specific words and use them to train deep learning models that discern between different words. In other words (no pun intended), we can discern when you’re thinking about a particular word simply from the act of you thinking about it. This technology has its limitations, and it is by no means perfect or ready for practical use. However, since its first real world demonstration two years ago by the MIT Media Lab, it has been used successfully in devices that allow users to do math, make phone calls, order pizza, and even receive assistance while playing chess. The primary hardware tool required is an OpenBCI Ganglion board. There are a variety of other hardware options available, but I found OpenBCI to have one of the largest communities of developers for support. It sets you back about $200, but it’s well worth it given the incredible stuff you can build with it. In addition to the board, you’ll need electrodes and wires. A set of gold cup electrodes and electrode gel should cost $50 and should work fine. Ganglion Board Electrodes Electrode Gel Alternatively, you can get a complete OpenBCI starter kit, which includes the board and multiple types of dry electrodes, as well as an electrode headband, for $465. It’s a bit pricey, so the gold cup setup is completely fine. Though, if you plan to experiment with other applications of BCI, like VR (tutorial with Unity VR coming soon!), the headband and dry electrodes make for a far better experience. Biosensing Starter Kit OpenBCI also offers 8 and 16 channel boards. These will offer superior data quality, but the 4 channel Ganglion will be adequate for this project. On a Linux machine, check if you have Python 3.4 or higher. Open your terminal and type the following command: python3 --version If you don’t have Python, or if you have an older version, enter: $ sudo apt-get update$ sudo apt-get install python3.6 Now, download or clone the pyOpenBCI directory. Change directory into the repository, and run the following command to install the prerequisite packages: $ pip install numpy pyserial bitstring xmltodict requests bluepy You’re now ready to install pyOpenBCI $ pip install pyOpenBCI To see some action, change directory to pyOpenBCI/Examples and find print_raw_example.py. Open this file with your favorite code editor, and make the following change on line 7: board = OpenBCICyton(daisy = False) Should be changed to: board = OpenBCIGanglion(mac=’*’) This allows pyOpenBCI to employ the appropriate modules for the particular board we are using. Now, power on your board. On your computer, from the Examples directory in your terminal, type the following command: $ sudo python print_raw_example Boom!! Your terminal should now be flooded with a stream of raw input data from the board. Now that we can obtain raw signals, we can start designing and building the data pipeline. To start, we must first convert the raw data into an LSL stream. LSL refers to Lab Streaming Layer, and is a protocol developed at the Swartz Center for Computational Neuroscience at UC San Diego to facilitate the recording and analysis of live data streams. LSL will stream our EEG data onto the local host, from where it can be picked up by other applications or scripts. Modify the lsl_example.py file in pyOpenBCI/Examples to remove the AUX stream, which we do not need, an add a markers stream: We must now define an experimental setup that will record the data in the form we want and store it for further use. We want the experiment to generate a data set of time series EEG data separated into intervals, with each interval corresponding to the subvocalization of a single word. To achieve this, we can execute an experiment that starts a recording session of N intervals, with each interval lasting T seconds. All samples within a given interval are annotated with the interval index and the particular word the user is instructed to subvocalize. The lsl-record.py file from neurotech-berkeley serves as a good starting point. Modify the file in accordance with our defined setup: You may adjust the termBank (line 64) to try various combinations of words in various contexts. You may also adjust the default duration (line 12) before each session. Now it’s time for the fun part! Plug the electrodes into your board: Tape them to your face in the following configuration: Find a quiet place to sit, and enter the following lines into separate terminals: // Terminal 1: converts raw data to LSL and streams it$ sudo python lsl_example// Terminal 2: reads LSL data stream and executes experiment$ sudo python lsl_record Note: we run as sudo to allow the script to detect the MAC address of the board This should start a recording session of the specified duration. You will be prompted with a random word from your term-bank to subvocalize over 2 second intervals. The recording sessions may get uncomfortable and sleep inducing, so it’s better to do multiple small sessions with breaks in between. Additionally, our experimental setup may lead to poor data quality if frequent disturbances occur (i.e. abrupt movements or subvocalizing the incorrect word). You may design and implement a more flexible setup with an option to hit a key that deletes the current and previous intervals upon noticing a disturbance. Another workaround is to do multiple small sessions and combine the data at the end, discarding sessions with excessive disturbances. Some noise is inevitable, and you don’t have to be too picky as the model becomes more resilient with increased sample count. For optimal results, you should have at least 1000 high quality samples for every word in your word bank. Once you have enough data, it’s time to prepare it for use in machine learning. Combine and preprocess your data as appropriate so that it has the following format: Words are indices from 1 to NumIntervals, which is the sum of SessionDuration/2 over the total number of sessions Terms correspond to the word displayed at each interval [A, B, C, D] are the EEG channels Each word, term combination corresponds to approximately 800 lines of data Import your CSV files into python using numpy. You should have all your data loaded in a NumLines x 6 ndarray in your script. The first step is to filter the data to remove noise that is outside the frequencies we’re interested in. Informative EEG frequencies correspond to the following bands: Filtering for frequencies between 4 Hz and 100 Hz may seem reasonable, but would fail because 60 Hz is the frequency of the power grid (may vary by country), which is bound to be a significant source of noise. For optimal results, we should filter between 4 Hz and 50 Hz. We can use Scipy’s Butterworth filter to select the frequency range we want to keep. Define a filter with the following code: Then, generate a timestamp column (as we combined multiple datasets and rendered the original timestamps invalid), and apply the filter to each channel: Once filtered, use the following code to restructure your data into a three dimensional ndarrray array with dimensions IntervalLength x ChannelCount x IntervalCount. What we’ve effectively done with the above code is converted time series data into image data. It might sound a bit weird, but you can think of each 2 second interval as an image, with each pixel corresponding to the signal value acquired at a particular (channelNumber, lineNumber) coordinate. In other words, we have a stack of IntervalCount images that are each IntervalLength x CannelCount in size. This technique, demonstrated by Justin Alvey in a similar project, is incredibly powerful because it allows us to treat time series data as if it were image data, allowing us to leverage the power of computer vision and Convolutional Neural Networks (CNNs). You can even visualize a particular subvocalization by plotting it as an image Additionally, using CNNs allows us to skip Fourier transformations as various frequencies (emerging as patterns on each image) may be learned by the neural network without explicitly specifying what frequencies it should look for. Now we’re ready to start building the CNN. Since we only have 1 color dimension, we can use a 1D CNN with input dimensions of IntervalLength and ChannelCount. You may experiment with different hyperparameters and architectures. I settled on a single convolution layer, two fully connected layers, and two pooling layers. For a more detailed analysis on single dimensional CNNs and how they are applied to time series data, refer to this article by Nils Ackermann. We now have a model that should be able to match an interval of EEG data to a specific word in your word bank. Let’s see how well it does. Apply the model to the test data, and compare the predicted results against the actual results. # Test Modely_predicted = model.predict(X_test) With two words in the term bank, I was able to achieve 90% accuracy. As expected, accuracy diminished slightly with additional words, with 86% for three way and 81% for four way. One possible way to increase the size of the term bank without compromising accuracy is to create a hierarchical “term tree” with multiple-word queries. You may then perform depth first search on the tree -with each layer of words only being compared to others in that same layer of the same subtree- to find the best match. We now have all the pieces necessary to query Google using your BCI. Define a mapping between specific subvocalizations and queries, and make the appropriate call: and.... To do live queries as you think of them, modify and import the lsl_record.py script as a module. You may then call it to read the LSL stream in response to user input for a single 2 second interval. That’s it! You can now search Google without saying or typing a single word. You can’t do too much with a three or four word term-bank (barring implementation of the term-tree mentioned earlier). Going through all these steps to search for directions to your nearest gas station is slightly more complicated than just Googling it the normal way. Nevertheless, it’s important to consider where further developments in this technology could lead to. We can imagine an improved and less conspicuous version of this device, not too different from the one the MIT team already has, being used for navigation, web queries, text messaging, smart home management, or any number of routine tasks. When combined with the power of ever improving AI assistants capable of context dependent interpretation, the possibilities expand even further. The applications of EEG based BCIs are a small subset of what could ultimately be made possible by the cutting edge research taking place at companies and university labs across the world. Telepathic communication, superhuman intelligence, additional senses, simulated experiences, digitization of human consciousness, and merging with artificial intelligence are all worth considering. If these possibilities are realized, they won’t just redefine our relationship with technology: they’ll redefine what it means to be human. REFERENCES The following are a list of resources and organizations I found helpful in completing this project and in learning about BCIs in general. I’d like to especially acknowledge the AlterEgo Team at the MIT Media Lab for being the original inspiration for this project, as well as Mr. Alvey and NeuroTech Berkeley for their prior code and tutorial contributions to the BCI community. Additionally, I’d like to thank faculty at the University of California, Davis, notably Dr. Ilias Tagkopoulos, Dr. Karen Moxon, and Dr. Erkin Seker, for ongoing assistance and support. AlterEgo: A Personalized Wearable Silent Speech Interface Using deep learning to “read your thoughts” — with Keras and EEG — Justin Alvey Neurotech Berkeley Github Open BCI Gitub Brain-Computer Interfacing: An Introduction — Rajesh Rao Finally, I’d like to give a huge shout out to the growing BCI/ Neurotech communities which have provided endless support, resources, and enthusiasm for the future. NeuroTechX Reddit BCI Reddit Neuralink OpenBCI If you’d like to discuss further or connect, please feel free to reach out on LinkedIn
[ { "code": null, "e": 361, "s": 171, "text": "Elon Musk and Neuralink want to build a Brain-Computer Interface that can act as the third layer of the brain, allowing humans to form a symbiotic relationship with Artificial Intelligence." }, { "code": null, "e": 398, "s": 361, "text": "But what if you can already do that?" }, { "code": null, "e": 442, "s": 398, "text": "In a (very) limited form, you actually can." }, { "code": null, "e": 984, "s": 442, "text": "Brain-Computer Interface (BCI) broadly refers to any system that establishes a direct connection between the nervous system and an electronic device. These devices may be surgically implanted in the brain, or they may be external. Typical paradigms include allowing a user to control an actuator or keyboard, allowing a device to send sensory data to the user, or bilateral communication involving both sensory data and motor control (i.e. a prosthetic arm that receives motor control input and sends sensory data on pressure or temperature)" }, { "code": null, "e": 2044, "s": 984, "text": "Historically, neuroprosthetics have been the primary motive for BCI research. These include artificial limbs for amputees, cochlear implants for the deaf, and deep brain stimulation for individuals suffering from seizures. Already, these devices have improved the lives of millions of people, and their widespread use demonstrates the benefits of achieving direct bilateral communication between the brain and electronic devices. However, the possible applications of the technology extend far beyond healthcare. Even within the realm of neuroprosthetics, we can imagine going beyond just repairing and consider augmenting our abilities beyond normal human levels. Artificial limbs may one day progress to the point where they are, by any objective criterion, superior to their natural counterparts. These limbs may look and feel just like normal limbs, but would be far stronger and more agile. Another example would be artificial eyes that are capable of far higher resolution than human eyes, an ability zoom in or out, and to see in the UV or IR spectrum." }, { "code": null, "e": 2736, "s": 2044, "text": "The possibilities get even more interesting when considering cognition and skill formation. A recent study demonstrates that stimulating certain parts of the brain improves memory formation and recall. Other experiments have managed to artificially implant memories in animals. As an example, it may be possible to apply the methods of these studies to improve your ability to quickly learn an instrument. Or perhaps it may be possible to combine various neurostimulators and sensors to develop an “arithmetic processing unit” that can detect when particular areas of the brain associated with mathematical or logical reasoning are activated, and communicates with them to enhance abilities." }, { "code": null, "e": 4189, "s": 2736, "text": "It is an extension of this cognitive augmentation that Elon Musk and Neuralink want to pursue. According to Musk and many leading AI theorists, a key barrier in humanity’s intellectual progress relative to AI is the bandwidth problem: although computers and AI are becoming ever faster and more capable of processing and generating knowledge, we face immediate and fundamental limitations in our ability to do the same. We acquire information primarily through our senses and ability to interpret language. In the time it takes your eyes and visual cortex to read and understand a single sentence, a computer can scan through thousands of pages of text. It’s conceivable that in a few decades time, we may have advanced AI running on specialized neuromorphic hardware with incredibly accurate models of how the world works and an ability to analyze and understand millions of documents in minutes, making decisions and inferences that are far beyond human comprehension. In a world increasingly dependent on AI driven decision making, humans may find themselves obsolete in all parts of the business, scientific, and political decision making process. Our brains did not evolve to play a game of chess with trillions of pieces or to comprehend calculated strategies that plan millions of moves ahead. It is a fear of this super-intelligent black box that motivates much of the current work at Neuralink, Kernel, and several other related organizations." }, { "code": null, "e": 5289, "s": 4189, "text": "Most of the leading edge research in BCI technology seeks to maximize the information bandwidth, typically through invasive methods that implant electrodes directly into the brain or nerves. However, non invasive methods, specifically electroencephalography (EEG) and electromyography (EMG) are routinely used with considerable success. These involve placing electrodes on the surface of your head (EEG) or skin above muscles (EMG) to measure the cumulative electrical activity underneath. The granularity of this data is low, and it is a far cry from the level of precision and bandwidth that will ultimately be needed to realize the more ambitious goals of BCI research. Nevertheless, EEG/EMG enabled BCIs have achieved incredible feats, like controlling drones, video games, and keyboards with thought, and they provide a small glimpse into the possibilities that further research may unlock. Furthermore, several companies like Cognixion and Neurable are exploring real world applications of EEG based BCIs and have received considerable funding and support with many exciting projects underway." }, { "code": null, "e": 5639, "s": 5289, "text": "In this project, we establish a direct connection between your nervous system and an external AI agent. This agent may be anything you can get an API for: Google Assistant, Siri, Alexa, Watson, etc. Services like Dictionary or YouTube would qualify as well, but these would limit applications to content queries rather than general purpose requests." }, { "code": null, "e": 5881, "s": 5639, "text": "For the purposes of this project, we will query Google Search directly as it provides the most flexibility and is the easiest to set up. Upon completion, you should be able to query a handful of terms on Google simply by thinking about them." }, { "code": null, "e": 6485, "s": 5881, "text": "The technique we use exploits the nerve signals generated by your brain in the process of subvocalization. This is the “internal monologue” that takes place inside your head when you slowly and deliberately read or think. You may have noticed yourself doing this when reading silently, sometimes to the point where you’re subtly moving your jaw and tongue without even realizing it. You may also have come across the concept when receiving tips for SAT, MCAT, GRE or other standardized test preparation. Test takers are advised to avoid subvocalization as it’s a bad habit that slows down reading speed." }, { "code": null, "e": 7020, "s": 6485, "text": "We are able to exploit subvocalization because the brain sends signals to your larynx corresponding to words you think to say, even if you don’t intend to actually say them out loud. By placing electrodes on your face over the laryngeal and mandibular nerves, we can record signals corresponding to specific words and use them to train deep learning models that discern between different words. In other words (no pun intended), we can discern when you’re thinking about a particular word simply from the act of you thinking about it." }, { "code": null, "e": 7351, "s": 7020, "text": "This technology has its limitations, and it is by no means perfect or ready for practical use. However, since its first real world demonstration two years ago by the MIT Media Lab, it has been used successfully in devices that allow users to do math, make phone calls, order pizza, and even receive assistance while playing chess." }, { "code": null, "e": 7661, "s": 7351, "text": "The primary hardware tool required is an OpenBCI Ganglion board. There are a variety of other hardware options available, but I found OpenBCI to have one of the largest communities of developers for support. It sets you back about $200, but it’s well worth it given the incredible stuff you can build with it." }, { "code": null, "e": 7806, "s": 7661, "text": "In addition to the board, you’ll need electrodes and wires. A set of gold cup electrodes and electrode gel should cost $50 and should work fine." }, { "code": null, "e": 7821, "s": 7806, "text": "Ganglion Board" }, { "code": null, "e": 7832, "s": 7821, "text": "Electrodes" }, { "code": null, "e": 7846, "s": 7832, "text": "Electrode Gel" }, { "code": null, "e": 8252, "s": 7846, "text": "Alternatively, you can get a complete OpenBCI starter kit, which includes the board and multiple types of dry electrodes, as well as an electrode headband, for $465. It’s a bit pricey, so the gold cup setup is completely fine. Though, if you plan to experiment with other applications of BCI, like VR (tutorial with Unity VR coming soon!), the headband and dry electrodes make for a far better experience." }, { "code": null, "e": 8275, "s": 8252, "text": "Biosensing Starter Kit" }, { "code": null, "e": 8422, "s": 8275, "text": "OpenBCI also offers 8 and 16 channel boards. These will offer superior data quality, but the 4 channel Ganglion will be adequate for this project." }, { "code": null, "e": 8533, "s": 8422, "text": "On a Linux machine, check if you have Python 3.4 or higher. Open your terminal and type the following command:" }, { "code": null, "e": 8551, "s": 8533, "text": "python3 --version" }, { "code": null, "e": 8617, "s": 8551, "text": "If you don’t have Python, or if you have an older version, enter:" }, { "code": null, "e": 8671, "s": 8617, "text": "$ sudo apt-get update$ sudo apt-get install python3.6" }, { "code": null, "e": 8719, "s": 8671, "text": "Now, download or clone the pyOpenBCI directory." }, { "code": null, "e": 8825, "s": 8719, "text": "Change directory into the repository, and run the following command to install the prerequisite packages:" }, { "code": null, "e": 8890, "s": 8825, "text": "$ pip install numpy pyserial bitstring xmltodict requests bluepy" }, { "code": null, "e": 8928, "s": 8890, "text": "You’re now ready to install pyOpenBCI" }, { "code": null, "e": 8952, "s": 8928, "text": "$ pip install pyOpenBCI" }, { "code": null, "e": 9130, "s": 8952, "text": "To see some action, change directory to pyOpenBCI/Examples and find print_raw_example.py. Open this file with your favorite code editor, and make the following change on line 7:" }, { "code": null, "e": 9166, "s": 9130, "text": "board = OpenBCICyton(daisy = False)" }, { "code": null, "e": 9188, "s": 9166, "text": "Should be changed to:" }, { "code": null, "e": 9221, "s": 9188, "text": "board = OpenBCIGanglion(mac=’*’)" }, { "code": null, "e": 9316, "s": 9221, "text": "This allows pyOpenBCI to employ the appropriate modules for the particular board we are using." }, { "code": null, "e": 9342, "s": 9316, "text": "Now, power on your board." }, { "code": null, "e": 9434, "s": 9342, "text": "On your computer, from the Examples directory in your terminal, type the following command:" }, { "code": null, "e": 9466, "s": 9434, "text": "$ sudo python print_raw_example" }, { "code": null, "e": 9557, "s": 9466, "text": "Boom!! Your terminal should now be flooded with a stream of raw input data from the board." }, { "code": null, "e": 10022, "s": 9557, "text": "Now that we can obtain raw signals, we can start designing and building the data pipeline. To start, we must first convert the raw data into an LSL stream. LSL refers to Lab Streaming Layer, and is a protocol developed at the Swartz Center for Computational Neuroscience at UC San Diego to facilitate the recording and analysis of live data streams. LSL will stream our EEG data onto the local host, from where it can be picked up by other applications or scripts." }, { "code": null, "e": 10148, "s": 10022, "text": "Modify the lsl_example.py file in pyOpenBCI/Examples to remove the AUX stream, which we do not need, an add a markers stream:" }, { "code": null, "e": 10704, "s": 10148, "text": "We must now define an experimental setup that will record the data in the form we want and store it for further use. We want the experiment to generate a data set of time series EEG data separated into intervals, with each interval corresponding to the subvocalization of a single word. To achieve this, we can execute an experiment that starts a recording session of N intervals, with each interval lasting T seconds. All samples within a given interval are annotated with the interval index and the particular word the user is instructed to subvocalize." }, { "code": null, "e": 10838, "s": 10704, "text": "The lsl-record.py file from neurotech-berkeley serves as a good starting point. Modify the file in accordance with our defined setup:" }, { "code": null, "e": 11006, "s": 10838, "text": "You may adjust the termBank (line 64) to try various combinations of words in various contexts. You may also adjust the default duration (line 12) before each session." }, { "code": null, "e": 11075, "s": 11006, "text": "Now it’s time for the fun part! Plug the electrodes into your board:" }, { "code": null, "e": 11130, "s": 11075, "text": "Tape them to your face in the following configuration:" }, { "code": null, "e": 11212, "s": 11130, "text": "Find a quiet place to sit, and enter the following lines into separate terminals:" }, { "code": null, "e": 11376, "s": 11212, "text": "// Terminal 1: converts raw data to LSL and streams it$ sudo python lsl_example// Terminal 2: reads LSL data stream and executes experiment$ sudo python lsl_record" }, { "code": null, "e": 11456, "s": 11376, "text": "Note: we run as sudo to allow the script to detect the MAC address of the board" }, { "code": null, "e": 11914, "s": 11456, "text": "This should start a recording session of the specified duration. You will be prompted with a random word from your term-bank to subvocalize over 2 second intervals. The recording sessions may get uncomfortable and sleep inducing, so it’s better to do multiple small sessions with breaks in between. Additionally, our experimental setup may lead to poor data quality if frequent disturbances occur (i.e. abrupt movements or subvocalizing the incorrect word)." }, { "code": null, "e": 12330, "s": 11914, "text": "You may design and implement a more flexible setup with an option to hit a key that deletes the current and previous intervals upon noticing a disturbance. Another workaround is to do multiple small sessions and combine the data at the end, discarding sessions with excessive disturbances. Some noise is inevitable, and you don’t have to be too picky as the model becomes more resilient with increased sample count." }, { "code": null, "e": 12436, "s": 12330, "text": "For optimal results, you should have at least 1000 high quality samples for every word in your word bank." }, { "code": null, "e": 12516, "s": 12436, "text": "Once you have enough data, it’s time to prepare it for use in machine learning." }, { "code": null, "e": 12601, "s": 12516, "text": "Combine and preprocess your data as appropriate so that it has the following format:" }, { "code": null, "e": 12715, "s": 12601, "text": "Words are indices from 1 to NumIntervals, which is the sum of SessionDuration/2 over the total number of sessions" }, { "code": null, "e": 12771, "s": 12715, "text": "Terms correspond to the word displayed at each interval" }, { "code": null, "e": 12805, "s": 12771, "text": "[A, B, C, D] are the EEG channels" }, { "code": null, "e": 12880, "s": 12805, "text": "Each word, term combination corresponds to approximately 800 lines of data" }, { "code": null, "e": 13006, "s": 12880, "text": "Import your CSV files into python using numpy. You should have all your data loaded in a NumLines x 6 ndarray in your script." }, { "code": null, "e": 13175, "s": 13006, "text": "The first step is to filter the data to remove noise that is outside the frequencies we’re interested in. Informative EEG frequencies correspond to the following bands:" }, { "code": null, "e": 13447, "s": 13175, "text": "Filtering for frequencies between 4 Hz and 100 Hz may seem reasonable, but would fail because 60 Hz is the frequency of the power grid (may vary by country), which is bound to be a significant source of noise. For optimal results, we should filter between 4 Hz and 50 Hz." }, { "code": null, "e": 13573, "s": 13447, "text": "We can use Scipy’s Butterworth filter to select the frequency range we want to keep. Define a filter with the following code:" }, { "code": null, "e": 13726, "s": 13573, "text": "Then, generate a timestamp column (as we combined multiple datasets and rendered the original timestamps invalid), and apply the filter to each channel:" }, { "code": null, "e": 13892, "s": 13726, "text": "Once filtered, use the following code to restructure your data into a three dimensional ndarrray array with dimensions IntervalLength x ChannelCount x IntervalCount." }, { "code": null, "e": 14295, "s": 13892, "text": "What we’ve effectively done with the above code is converted time series data into image data. It might sound a bit weird, but you can think of each 2 second interval as an image, with each pixel corresponding to the signal value acquired at a particular (channelNumber, lineNumber) coordinate. In other words, we have a stack of IntervalCount images that are each IntervalLength x CannelCount in size." }, { "code": null, "e": 14632, "s": 14295, "text": "This technique, demonstrated by Justin Alvey in a similar project, is incredibly powerful because it allows us to treat time series data as if it were image data, allowing us to leverage the power of computer vision and Convolutional Neural Networks (CNNs). You can even visualize a particular subvocalization by plotting it as an image" }, { "code": null, "e": 14863, "s": 14632, "text": "Additionally, using CNNs allows us to skip Fourier transformations as various frequencies (emerging as patterns on each image) may be learned by the neural network without explicitly specifying what frequencies it should look for." }, { "code": null, "e": 15184, "s": 14863, "text": "Now we’re ready to start building the CNN. Since we only have 1 color dimension, we can use a 1D CNN with input dimensions of IntervalLength and ChannelCount. You may experiment with different hyperparameters and architectures. I settled on a single convolution layer, two fully connected layers, and two pooling layers." }, { "code": null, "e": 15327, "s": 15184, "text": "For a more detailed analysis on single dimensional CNNs and how they are applied to time series data, refer to this article by Nils Ackermann." }, { "code": null, "e": 15438, "s": 15327, "text": "We now have a model that should be able to match an interval of EEG data to a specific word in your word bank." }, { "code": null, "e": 15562, "s": 15438, "text": "Let’s see how well it does. Apply the model to the test data, and compare the predicted results against the actual results." }, { "code": null, "e": 15610, "s": 15562, "text": "# Test Modely_predicted = model.predict(X_test)" }, { "code": null, "e": 15789, "s": 15610, "text": "With two words in the term bank, I was able to achieve 90% accuracy. As expected, accuracy diminished slightly with additional words, with 86% for three way and 81% for four way." }, { "code": null, "e": 16114, "s": 15789, "text": "One possible way to increase the size of the term bank without compromising accuracy is to create a hierarchical “term tree” with multiple-word queries. You may then perform depth first search on the tree -with each layer of words only being compared to others in that same layer of the same subtree- to find the best match." }, { "code": null, "e": 16278, "s": 16114, "text": "We now have all the pieces necessary to query Google using your BCI. Define a mapping between specific subvocalizations and queries, and make the appropriate call:" }, { "code": null, "e": 16286, "s": 16278, "text": "and...." }, { "code": null, "e": 16485, "s": 16286, "text": "To do live queries as you think of them, modify and import the lsl_record.py script as a module. You may then call it to read the LSL stream in response to user input for a single 2 second interval." }, { "code": null, "e": 16562, "s": 16485, "text": "That’s it! You can now search Google without saying or typing a single word." }, { "code": null, "e": 17318, "s": 16562, "text": "You can’t do too much with a three or four word term-bank (barring implementation of the term-tree mentioned earlier). Going through all these steps to search for directions to your nearest gas station is slightly more complicated than just Googling it the normal way. Nevertheless, it’s important to consider where further developments in this technology could lead to. We can imagine an improved and less conspicuous version of this device, not too different from the one the MIT team already has, being used for navigation, web queries, text messaging, smart home management, or any number of routine tasks. When combined with the power of ever improving AI assistants capable of context dependent interpretation, the possibilities expand even further." }, { "code": null, "e": 17845, "s": 17318, "text": "The applications of EEG based BCIs are a small subset of what could ultimately be made possible by the cutting edge research taking place at companies and university labs across the world. Telepathic communication, superhuman intelligence, additional senses, simulated experiences, digitization of human consciousness, and merging with artificial intelligence are all worth considering. If these possibilities are realized, they won’t just redefine our relationship with technology: they’ll redefine what it means to be human." }, { "code": null, "e": 17856, "s": 17845, "text": "REFERENCES" }, { "code": null, "e": 18420, "s": 17856, "text": "The following are a list of resources and organizations I found helpful in completing this project and in learning about BCIs in general. I’d like to especially acknowledge the AlterEgo Team at the MIT Media Lab for being the original inspiration for this project, as well as Mr. Alvey and NeuroTech Berkeley for their prior code and tutorial contributions to the BCI community. Additionally, I’d like to thank faculty at the University of California, Davis, notably Dr. Ilias Tagkopoulos, Dr. Karen Moxon, and Dr. Erkin Seker, for ongoing assistance and support." }, { "code": null, "e": 18478, "s": 18420, "text": "AlterEgo: A Personalized Wearable Silent Speech Interface" }, { "code": null, "e": 18558, "s": 18478, "text": "Using deep learning to “read your thoughts” — with Keras and EEG — Justin Alvey" }, { "code": null, "e": 18584, "s": 18558, "text": "Neurotech Berkeley Github" }, { "code": null, "e": 18599, "s": 18584, "text": "Open BCI Gitub" }, { "code": null, "e": 18656, "s": 18599, "text": "Brain-Computer Interfacing: An Introduction — Rajesh Rao" }, { "code": null, "e": 18820, "s": 18656, "text": "Finally, I’d like to give a huge shout out to the growing BCI/ Neurotech communities which have provided endless support, resources, and enthusiasm for the future." }, { "code": null, "e": 18831, "s": 18820, "text": "NeuroTechX" }, { "code": null, "e": 18842, "s": 18831, "text": "Reddit BCI" }, { "code": null, "e": 18859, "s": 18842, "text": "Reddit Neuralink" }, { "code": null, "e": 18867, "s": 18859, "text": "OpenBCI" } ]
Convert BST to Max Heap - GeeksforGeeks
01 Feb, 2022 Given a Binary Search Tree which is also a Complete Binary Tree. The problem is to convert a given BST into a Special Max Heap with the condition that all the values in the left subtree of a node should be less than all the values in the right subtree of the node. This condition is applied on all the nodes in the so converted Max Heap. Examples: Input : 4 / \ 2 6 / \ / \ 1 3 5 7 Output : 7 / \ 3 6 / \ / \ 1 2 4 5 The given BST has been transformed into a Max Heap. All the nodes in the Max Heap satisfies the given condition, that is, values in the left subtree of a node should be less than the values in the right subtree of the node. Pre Requisites: Binary Search Tree | Heaps Approach 1. Create an array arr[] of size n, where n is the number of nodes in the given BST. 2. Perform the inorder traversal of the BST and copy the node values in the arr[] in sorted order. 3. Now perform the postorder traversal of the tree. 4. While traversing the root during the postorder traversal, one by one copy the values from the array arr[] to the nodes. C++ Java Python3 C# Javascript // C++ implementation to convert a given// BST to Max Heap#include <bits/stdc++.h>using namespace std; struct Node { int data; Node *left, *right;}; /* Helper function that allocates a new nodewith the given data and NULL left and rightpointers. */struct Node* getNode(int data){ struct Node* newNode = new Node; newNode->data = data; newNode->left = newNode->right = NULL; return newNode;} // Function prototype for postorder traversal// of the given treevoid postorderTraversal(Node*); // Function for the inorder traversal of the tree// so as to store the node values in 'arr' in// sorted ordervoid inorderTraversal(Node* root, vector<int>& arr){ if (root == NULL) return; // first recur on left subtree inorderTraversal(root->left, arr); // then copy the data of the node arr.push_back(root->data); // now recur for right subtree inorderTraversal(root->right, arr);} void BSTToMaxHeap(Node* root, vector<int> &arr, int* i){ if (root == NULL) return; // recur on left subtree BSTToMaxHeap(root->left, arr, i); // recur on right subtree BSTToMaxHeap(root->right, arr, i); // copy data at index 'i' of 'arr' to // the node root->data = arr[++*i];} // Utility function to convert the given BST to// MAX HEAPvoid convertToMaxHeapUtil(Node* root){ // vector to store the data of all the // nodes of the BST vector<int> arr; int i = -1; // inorder traversal to populate 'arr' inorderTraversal(root, arr); // BST to MAX HEAP conversion BSTToMaxHeap(root, arr, &i);} // Function to Print Postorder Traversal of the treevoid postorderTraversal(Node* root){ if (!root) return; // recur on left subtree postorderTraversal(root->left); // then recur on right subtree postorderTraversal(root->right); // print the root's data cout << root->data << " ";} // Driver Codeint main(){ // BST formation struct Node* root = getNode(4); root->left = getNode(2); root->right = getNode(6); root->left->left = getNode(1); root->left->right = getNode(3); root->right->left = getNode(5); root->right->right = getNode(7); convertToMaxHeapUtil(root); cout << "Postorder Traversal of Tree:" << endl; postorderTraversal(root); return 0;} // Java implementation to convert a given// BST to Max Heapimport java.util.*; class GFG{ static int i;static class Node{ int data; Node left, right;}; /* Helper function that allocates a new nodewith the given data and null left and rightpointers. */static Node getNode(int data){ Node newNode = new Node(); newNode.data = data; newNode.left = newNode.right = null; return newNode;} // Function for the inorder traversal of the tree// so as to store the node values in 'arr' in// sorted orderstatic void inorderTraversal(Node root, Vector<Integer> arr){ if (root == null) return; // first recur on left subtree inorderTraversal(root.left, arr); // then copy the data of the node arr.add(root.data); // now recur for right subtree inorderTraversal(root.right, arr);} static void BSTToMaxHeap(Node root, Vector<Integer> arr){ if (root == null) return; // recur on left subtree BSTToMaxHeap(root.left, arr); // recur on right subtree BSTToMaxHeap(root.right, arr); // copy data at index 'i' of 'arr' to // the node root.data = arr.get(i++);} // Utility function to convert the given BST to// MAX HEAPstatic void convertToMaxHeapUtil(Node root){ // vector to store the data of all the // nodes of the BST Vector<Integer> arr = new Vector<Integer>(); int i = -1; // inorder traversal to populate 'arr' inorderTraversal(root, arr); // BST to MAX HEAP conversion BSTToMaxHeap(root, arr);} // Function to Print Postorder Traversal of the treestatic void postorderTraversal(Node root){ if (root == null) return; // recur on left subtree postorderTraversal(root.left); // then recur on right subtree postorderTraversal(root.right); // print the root's data System.out.print(root.data + " ");} // Driver Codepublic static void main(String[] args){ // BST formation Node root = getNode(4); root.left = getNode(2); root.right = getNode(6); root.left.left = getNode(1); root.left.right = getNode(3); root.right.left = getNode(5); root.right.right = getNode(7); convertToMaxHeapUtil(root); System.out.print("Postorder Traversal of Tree:" +"\n"); postorderTraversal(root); }} // This code is contributed by 29AjayKumar # Python3 implementation to convert a given# BST to Max Heapi = 0class Node: def __init__(self): self.data = 0 self.left = None self.right = None # Helper function that allocates a new node# with the given data and None left and right# pointers.def getNode(data): newNode = Node() newNode.data = data newNode.left = newNode.right = None return newNode arr = [] # Function for the inorder traversal of the tree# so as to store the node values in 'arr' in# sorted orderdef inorderTraversal( root): if (root == None): return arr # first recur on left subtree inorderTraversal(root.left) # then copy the data of the node arr.append(root.data) # now recur for right subtree inorderTraversal(root.right) def BSTToMaxHeap(root): global i if (root == None): return None # recur on left subtree root.left = BSTToMaxHeap(root.left) # recur on right subtree root.right = BSTToMaxHeap(root.right) # copy data at index 'i' of 'arr' to # the node root.data = arr[i] i = i + 1 return root # Utility function to convert the given BST to# MAX HEAPdef convertToMaxHeapUtil( root): global i # vector to store the data of all the # nodes of the BST i = 0 # inorder traversal to populate 'arr' inorderTraversal(root) # BST to MAX HEAP conversion root = BSTToMaxHeap(root) return root # Function to Print Postorder Traversal of the treedef postorderTraversal(root): if (root == None): return # recur on left subtree postorderTraversal(root.left) # then recur on right subtree postorderTraversal(root.right) # print the root's data print(root.data ,end= " ") # Driver Code # BST formationroot = getNode(4)root.left = getNode(2)root.right = getNode(6)root.left.left = getNode(1)root.left.right = getNode(3)root.right.left = getNode(5)root.right.right = getNode(7) root = convertToMaxHeapUtil(root)print("Postorder Traversal of Tree:" )postorderTraversal(root) # This code is contributed by Arnab Kundu // C# implementation to convert a given// BST to Max Heapusing System;using System.Collections.Generic; public class GFG{ static int i; public class Node { public int data; public Node left, right; }; /* Helper function that allocates a new nodewith the given data and null left and rightpointers. */ static Node getNode(int data) { Node newNode = new Node(); newNode.data = data; newNode.left = newNode.right = null; return newNode; } // Function for the inorder traversal of the tree // so as to store the node values in 'arr' in // sorted order static void inorderTraversal(Node root, List<int> arr) { if (root == null) return; // first recur on left subtree inorderTraversal(root.left, arr); // then copy the data of the node arr.Add(root.data); // now recur for right subtree inorderTraversal(root.right, arr); } static void BSTToMaxHeap(Node root, List<int> arr) { if (root == null) return; // recur on left subtree BSTToMaxHeap(root.left, arr); // recur on right subtree BSTToMaxHeap(root.right, arr); // copy data at index 'i' of 'arr' to // the node root.data = arr[i++]; } // Utility function to convert the given BST to // MAX HEAP static void convertToMaxHeapUtil(Node root) { // vector to store the data of all the // nodes of the BST List<int> arr = new List<int>(); int i = -1; // inorder traversal to populate 'arr' inorderTraversal(root, arr); // BST to MAX HEAP conversion BSTToMaxHeap(root, arr); } // Function to Print Postorder Traversal of the tree static void postorderTraversal(Node root) { if (root == null) return; // recur on left subtree postorderTraversal(root.left); // then recur on right subtree postorderTraversal(root.right); // print the root's data Console.Write(root.data + " "); } // Driver Code public static void Main(String[] args) { // BST formation Node root = getNode(4); root.left = getNode(2); root.right = getNode(6); root.left.left = getNode(1); root.left.right = getNode(3); root.right.left = getNode(5); root.right.right = getNode(7); convertToMaxHeapUtil(root); Console.Write("Postorder Traversal of Tree:" +"\n"); postorderTraversal(root); }} // This code is contributed by Rajput-Ji <script>// Javascript implementation to convert a given// BST to Max Heap let i = 0; class Node{ constructor() { this.data = 0; this.left = this.right = null; }} /* Helper function that allocates a new node with the given data and null left and right pointers. */function getNode(data){ let newNode = new Node(); newNode.data = data; newNode.left = newNode.right = null; return newNode;} // Function for the inorder traversal of the tree// so as to store the node values in 'arr' in// sorted orderfunction inorderTraversal(root, arr){ if (root == null) return; // first recur on left subtree inorderTraversal(root.left, arr); // then copy the data of the node arr.push(root.data); // now recur for right subtree inorderTraversal(root.right, arr);} function BSTToMaxHeap(root,arr){ if (root == null) return; // recur on left subtree BSTToMaxHeap(root.left, arr); // recur on right subtree BSTToMaxHeap(root.right, arr); // copy data at index 'i' of 'arr' to // the node root.data = arr[i++]; } // Utility function to convert the given BST to// MAX HEAPfunction convertToMaxHeapUtil(root){ // vector to store the data of all the // nodes of the BST let arr = []; // inorder traversal to populate 'arr' inorderTraversal(root, arr); // BST to MAX HEAP conversion BSTToMaxHeap(root, arr); } // Function to Print Postorder Traversal of the treefunction postorderTraversal(root){ if (root == null) return; // recur on left subtree postorderTraversal(root.left); // then recur on right subtree postorderTraversal(root.right); // print the root's data document.write(root.data + " ");} // Driver Code// BST formationlet root = getNode(4);root.left = getNode(2);root.right = getNode(6);root.left.left = getNode(1);root.left.right = getNode(3);root.right.left = getNode(5);root.right.right = getNode(7); convertToMaxHeapUtil(root);document.write("Postorder Traversal of Tree:" +"\n");postorderTraversal(root); // This code is contributed by rag2127</script> Output: Postorder Traversal of Tree: 1 2 3 4 5 6 7 Time Complexity: O(n) Auxiliary Space: O(n) where, n is the number of nodes in the tree 29AjayKumar andrew1234 rag2127 simmytarika5 pratikkumarintern Rajput-Ji Binary Search Tree Heap Binary Search Tree Heap Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Construct a Binary Search Tree from given postorder set vs unordered_set in C++ STL Red Black Tree vs AVL Tree Convert BST to Min Heap Construct BST from given preorder traversal | Set 2 HeapSort Binary Heap Huffman Coding | Greedy Algo-3 K'th Smallest/Largest Element in Unsorted Array | Set 1 k largest(or smallest) elements in an array
[ { "code": null, "e": 25146, "s": 25118, "text": "\n01 Feb, 2022" }, { "code": null, "e": 25496, "s": 25146, "text": "Given a Binary Search Tree which is also a Complete Binary Tree. The problem is to convert a given BST into a Special Max Heap with the condition that all the values in the left subtree of a node should be less than all the values in the right subtree of the node. This condition is applied on all the nodes in the so converted Max Heap. Examples: " }, { "code": null, "e": 25939, "s": 25496, "text": "Input : 4\n / \\\n 2 6\n / \\ / \\\n 1 3 5 7 \n \nOutput : 7\n / \\\n 3 6\n / \\ / \\\n 1 2 4 5\nThe given BST has been transformed into a\nMax Heap.\nAll the nodes in the Max Heap satisfies the given\ncondition, that is, values in the left subtree of\na node should be less than the values in the right\nsubtree of the node. " }, { "code": null, "e": 26351, "s": 25939, "text": "Pre Requisites: Binary Search Tree | Heaps Approach 1. Create an array arr[] of size n, where n is the number of nodes in the given BST. 2. Perform the inorder traversal of the BST and copy the node values in the arr[] in sorted order. 3. Now perform the postorder traversal of the tree. 4. While traversing the root during the postorder traversal, one by one copy the values from the array arr[] to the nodes. " }, { "code": null, "e": 26355, "s": 26351, "text": "C++" }, { "code": null, "e": 26360, "s": 26355, "text": "Java" }, { "code": null, "e": 26368, "s": 26360, "text": "Python3" }, { "code": null, "e": 26371, "s": 26368, "text": "C#" }, { "code": null, "e": 26382, "s": 26371, "text": "Javascript" }, { "code": "// C++ implementation to convert a given// BST to Max Heap#include <bits/stdc++.h>using namespace std; struct Node { int data; Node *left, *right;}; /* Helper function that allocates a new nodewith the given data and NULL left and rightpointers. */struct Node* getNode(int data){ struct Node* newNode = new Node; newNode->data = data; newNode->left = newNode->right = NULL; return newNode;} // Function prototype for postorder traversal// of the given treevoid postorderTraversal(Node*); // Function for the inorder traversal of the tree// so as to store the node values in 'arr' in// sorted ordervoid inorderTraversal(Node* root, vector<int>& arr){ if (root == NULL) return; // first recur on left subtree inorderTraversal(root->left, arr); // then copy the data of the node arr.push_back(root->data); // now recur for right subtree inorderTraversal(root->right, arr);} void BSTToMaxHeap(Node* root, vector<int> &arr, int* i){ if (root == NULL) return; // recur on left subtree BSTToMaxHeap(root->left, arr, i); // recur on right subtree BSTToMaxHeap(root->right, arr, i); // copy data at index 'i' of 'arr' to // the node root->data = arr[++*i];} // Utility function to convert the given BST to// MAX HEAPvoid convertToMaxHeapUtil(Node* root){ // vector to store the data of all the // nodes of the BST vector<int> arr; int i = -1; // inorder traversal to populate 'arr' inorderTraversal(root, arr); // BST to MAX HEAP conversion BSTToMaxHeap(root, arr, &i);} // Function to Print Postorder Traversal of the treevoid postorderTraversal(Node* root){ if (!root) return; // recur on left subtree postorderTraversal(root->left); // then recur on right subtree postorderTraversal(root->right); // print the root's data cout << root->data << \" \";} // Driver Codeint main(){ // BST formation struct Node* root = getNode(4); root->left = getNode(2); root->right = getNode(6); root->left->left = getNode(1); root->left->right = getNode(3); root->right->left = getNode(5); root->right->right = getNode(7); convertToMaxHeapUtil(root); cout << \"Postorder Traversal of Tree:\" << endl; postorderTraversal(root); return 0;}", "e": 28671, "s": 26382, "text": null }, { "code": "// Java implementation to convert a given// BST to Max Heapimport java.util.*; class GFG{ static int i;static class Node{ int data; Node left, right;}; /* Helper function that allocates a new nodewith the given data and null left and rightpointers. */static Node getNode(int data){ Node newNode = new Node(); newNode.data = data; newNode.left = newNode.right = null; return newNode;} // Function for the inorder traversal of the tree// so as to store the node values in 'arr' in// sorted orderstatic void inorderTraversal(Node root, Vector<Integer> arr){ if (root == null) return; // first recur on left subtree inorderTraversal(root.left, arr); // then copy the data of the node arr.add(root.data); // now recur for right subtree inorderTraversal(root.right, arr);} static void BSTToMaxHeap(Node root, Vector<Integer> arr){ if (root == null) return; // recur on left subtree BSTToMaxHeap(root.left, arr); // recur on right subtree BSTToMaxHeap(root.right, arr); // copy data at index 'i' of 'arr' to // the node root.data = arr.get(i++);} // Utility function to convert the given BST to// MAX HEAPstatic void convertToMaxHeapUtil(Node root){ // vector to store the data of all the // nodes of the BST Vector<Integer> arr = new Vector<Integer>(); int i = -1; // inorder traversal to populate 'arr' inorderTraversal(root, arr); // BST to MAX HEAP conversion BSTToMaxHeap(root, arr);} // Function to Print Postorder Traversal of the treestatic void postorderTraversal(Node root){ if (root == null) return; // recur on left subtree postorderTraversal(root.left); // then recur on right subtree postorderTraversal(root.right); // print the root's data System.out.print(root.data + \" \");} // Driver Codepublic static void main(String[] args){ // BST formation Node root = getNode(4); root.left = getNode(2); root.right = getNode(6); root.left.left = getNode(1); root.left.right = getNode(3); root.right.left = getNode(5); root.right.right = getNode(7); convertToMaxHeapUtil(root); System.out.print(\"Postorder Traversal of Tree:\" +\"\\n\"); postorderTraversal(root); }} // This code is contributed by 29AjayKumar", "e": 30950, "s": 28671, "text": null }, { "code": "# Python3 implementation to convert a given# BST to Max Heapi = 0class Node: def __init__(self): self.data = 0 self.left = None self.right = None # Helper function that allocates a new node# with the given data and None left and right# pointers.def getNode(data): newNode = Node() newNode.data = data newNode.left = newNode.right = None return newNode arr = [] # Function for the inorder traversal of the tree# so as to store the node values in 'arr' in# sorted orderdef inorderTraversal( root): if (root == None): return arr # first recur on left subtree inorderTraversal(root.left) # then copy the data of the node arr.append(root.data) # now recur for right subtree inorderTraversal(root.right) def BSTToMaxHeap(root): global i if (root == None): return None # recur on left subtree root.left = BSTToMaxHeap(root.left) # recur on right subtree root.right = BSTToMaxHeap(root.right) # copy data at index 'i' of 'arr' to # the node root.data = arr[i] i = i + 1 return root # Utility function to convert the given BST to# MAX HEAPdef convertToMaxHeapUtil( root): global i # vector to store the data of all the # nodes of the BST i = 0 # inorder traversal to populate 'arr' inorderTraversal(root) # BST to MAX HEAP conversion root = BSTToMaxHeap(root) return root # Function to Print Postorder Traversal of the treedef postorderTraversal(root): if (root == None): return # recur on left subtree postorderTraversal(root.left) # then recur on right subtree postorderTraversal(root.right) # print the root's data print(root.data ,end= \" \") # Driver Code # BST formationroot = getNode(4)root.left = getNode(2)root.right = getNode(6)root.left.left = getNode(1)root.left.right = getNode(3)root.right.left = getNode(5)root.right.right = getNode(7) root = convertToMaxHeapUtil(root)print(\"Postorder Traversal of Tree:\" )postorderTraversal(root) # This code is contributed by Arnab Kundu", "e": 33007, "s": 30950, "text": null }, { "code": "// C# implementation to convert a given// BST to Max Heapusing System;using System.Collections.Generic; public class GFG{ static int i; public class Node { public int data; public Node left, right; }; /* Helper function that allocates a new nodewith the given data and null left and rightpointers. */ static Node getNode(int data) { Node newNode = new Node(); newNode.data = data; newNode.left = newNode.right = null; return newNode; } // Function for the inorder traversal of the tree // so as to store the node values in 'arr' in // sorted order static void inorderTraversal(Node root, List<int> arr) { if (root == null) return; // first recur on left subtree inorderTraversal(root.left, arr); // then copy the data of the node arr.Add(root.data); // now recur for right subtree inorderTraversal(root.right, arr); } static void BSTToMaxHeap(Node root, List<int> arr) { if (root == null) return; // recur on left subtree BSTToMaxHeap(root.left, arr); // recur on right subtree BSTToMaxHeap(root.right, arr); // copy data at index 'i' of 'arr' to // the node root.data = arr[i++]; } // Utility function to convert the given BST to // MAX HEAP static void convertToMaxHeapUtil(Node root) { // vector to store the data of all the // nodes of the BST List<int> arr = new List<int>(); int i = -1; // inorder traversal to populate 'arr' inorderTraversal(root, arr); // BST to MAX HEAP conversion BSTToMaxHeap(root, arr); } // Function to Print Postorder Traversal of the tree static void postorderTraversal(Node root) { if (root == null) return; // recur on left subtree postorderTraversal(root.left); // then recur on right subtree postorderTraversal(root.right); // print the root's data Console.Write(root.data + \" \"); } // Driver Code public static void Main(String[] args) { // BST formation Node root = getNode(4); root.left = getNode(2); root.right = getNode(6); root.left.left = getNode(1); root.left.right = getNode(3); root.right.left = getNode(5); root.right.right = getNode(7); convertToMaxHeapUtil(root); Console.Write(\"Postorder Traversal of Tree:\" +\"\\n\"); postorderTraversal(root); }} // This code is contributed by Rajput-Ji", "e": 35355, "s": 33007, "text": null }, { "code": "<script>// Javascript implementation to convert a given// BST to Max Heap let i = 0; class Node{ constructor() { this.data = 0; this.left = this.right = null; }} /* Helper function that allocates a new node with the given data and null left and right pointers. */function getNode(data){ let newNode = new Node(); newNode.data = data; newNode.left = newNode.right = null; return newNode;} // Function for the inorder traversal of the tree// so as to store the node values in 'arr' in// sorted orderfunction inorderTraversal(root, arr){ if (root == null) return; // first recur on left subtree inorderTraversal(root.left, arr); // then copy the data of the node arr.push(root.data); // now recur for right subtree inorderTraversal(root.right, arr);} function BSTToMaxHeap(root,arr){ if (root == null) return; // recur on left subtree BSTToMaxHeap(root.left, arr); // recur on right subtree BSTToMaxHeap(root.right, arr); // copy data at index 'i' of 'arr' to // the node root.data = arr[i++]; } // Utility function to convert the given BST to// MAX HEAPfunction convertToMaxHeapUtil(root){ // vector to store the data of all the // nodes of the BST let arr = []; // inorder traversal to populate 'arr' inorderTraversal(root, arr); // BST to MAX HEAP conversion BSTToMaxHeap(root, arr); } // Function to Print Postorder Traversal of the treefunction postorderTraversal(root){ if (root == null) return; // recur on left subtree postorderTraversal(root.left); // then recur on right subtree postorderTraversal(root.right); // print the root's data document.write(root.data + \" \");} // Driver Code// BST formationlet root = getNode(4);root.left = getNode(2);root.right = getNode(6);root.left.left = getNode(1);root.left.right = getNode(3);root.right.left = getNode(5);root.right.right = getNode(7); convertToMaxHeapUtil(root);document.write(\"Postorder Traversal of Tree:\" +\"\\n\");postorderTraversal(root); // This code is contributed by rag2127</script>", "e": 37516, "s": 35355, "text": null }, { "code": null, "e": 37526, "s": 37516, "text": "Output: " }, { "code": null, "e": 37570, "s": 37526, "text": "Postorder Traversal of Tree:\n1 2 3 4 5 6 7 " }, { "code": null, "e": 37659, "s": 37570, "text": "Time Complexity: O(n) Auxiliary Space: O(n) where, n is the number of nodes in the tree " }, { "code": null, "e": 37671, "s": 37659, "text": "29AjayKumar" }, { "code": null, "e": 37682, "s": 37671, "text": "andrew1234" }, { "code": null, "e": 37690, "s": 37682, "text": "rag2127" }, { "code": null, "e": 37703, "s": 37690, "text": "simmytarika5" }, { "code": null, "e": 37721, "s": 37703, "text": "pratikkumarintern" }, { "code": null, "e": 37731, "s": 37721, "text": "Rajput-Ji" }, { "code": null, "e": 37750, "s": 37731, "text": "Binary Search Tree" }, { "code": null, "e": 37755, "s": 37750, "text": "Heap" }, { "code": null, "e": 37774, "s": 37755, "text": "Binary Search Tree" }, { "code": null, "e": 37779, "s": 37774, "text": "Heap" }, { "code": null, "e": 37877, "s": 37779, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37886, "s": 37877, "text": "Comments" }, { "code": null, "e": 37899, "s": 37886, "text": "Old Comments" }, { "code": null, "e": 37951, "s": 37899, "text": "Construct a Binary Search Tree from given postorder" }, { "code": null, "e": 37983, "s": 37951, "text": "set vs unordered_set in C++ STL" }, { "code": null, "e": 38010, "s": 37983, "text": "Red Black Tree vs AVL Tree" }, { "code": null, "e": 38034, "s": 38010, "text": "Convert BST to Min Heap" }, { "code": null, "e": 38086, "s": 38034, "text": "Construct BST from given preorder traversal | Set 2" }, { "code": null, "e": 38095, "s": 38086, "text": "HeapSort" }, { "code": null, "e": 38107, "s": 38095, "text": "Binary Heap" }, { "code": null, "e": 38138, "s": 38107, "text": "Huffman Coding | Greedy Algo-3" }, { "code": null, "e": 38194, "s": 38138, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" } ]
ASP.NET - Configuration
The behavior of an ASP.NET application is affected by different settings in the configuration files: machine.config web.config The machine.config file contains default and the machine-specific value for all supported settings. The machine settings are controlled by the system administrator and applications are generally not given access to this file. An application however, can override the default values by creating web.config files in its roots folder. The web.config file is a subset of the machine.config file. If the application contains child directories, it can define a web.config file for each folder. Scope of each configuration file is determined in a hierarchical top-down manner. Any web.config file can locally extend, restrict, or override any settings defined on the upper level. Visual Studio generates a default web.config file for each project. An application can execute without a web.config file, however, you cannot debug an application without a web.config file. The following figure shows the Solution Explorer for the sample example used in the web services tutorial: In this application, there are two web.config files for two projects i.e., the web service and the web site calling the web service. The web.config file has the configuration element as the root node. Information inside this element is grouped into two main areas: the configuration section-handler declaration area, and the configuration section settings area. The following code snippet shows the basic syntax of a configuration file: <configuration> <!-- Configuration section-handler declaration area. --> <configSections> <section name="section1" type="section1Handler" /> <section name="section2" type="section2Handler" /> </configSections> <!-- Configuration section settings area. --> <section1> <s1Setting1 attribute1="attr1" /> </section1> <section2> <s2Setting1 attribute1="attr1" /> </section2> <system.web> <authentication mode="Windows" /> </system.web> </configuration> The configuration section handlers are contained within the <configSections> tags. Each configuration handler specifies name of a configuration section, contained within the file, which provides some configuration data. It has the following basic syntax: <configSections> <section /> <sectionGroup /> <remove /> <clear/> </configSections> It has the following elements: Clear - It removes all references to inherited sections and section groups. Clear - It removes all references to inherited sections and section groups. Remove - It removes a reference to an inherited section and section group. Remove - It removes a reference to an inherited section and section group. Section - It defines an association between a configuration section handler and a configuration element. Section - It defines an association between a configuration section handler and a configuration element. Section group - It defines an association between a configuration section handler and a configuration section. Section group - It defines an association between a configuration section handler and a configuration section. The application settings allow storing application-wide name-value pairs for read-only access. For example, you can define a custom application setting as: <configuration> <appSettings> <add key="Application Name" value="MyApplication" /> </appSettings> </configuration> For example, you can also store the name of a book and its ISBN number: <configuration> <appSettings> <add key="appISBN" value="0-273-68726-3" /> <add key="appBook" value="Corporate Finance" /> </appSettings> </configuration> The connection strings show which database connection strings are available to the website. For example: <connectionStrings> <add name="ASPDotNetStepByStepConnectionString" connectionString="Provider=Microsoft.Jet.OLEDB.4.0; Data Source=E:\\projects\datacaching\ / datacaching\App_Data\ASPDotNetStepByStep.mdb" providerName="System.Data.OleDb" /> <add name="booksConnectionString" connectionString="Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\ \databinding\App_Data\books.mdb" providerName="System.Data.OleDb" /> </connectionStrings> The system.web element specifies the root element for the ASP.NET configuration section and contains configuration elements that configure ASP.NET Web applications and control how the applications behave. It holds most of the configuration elements needed to be adjusted in common applications. The basic syntax for the element is as given: <system.web> <anonymousIdentification> <authentication> <authorization> <browserCaps> <caching> <clientTarget> <compilation> <customErrors> <deployment> <deviceFilters> <globalization> <healthMonitoring> <hostingEnvironment> <httpCookies> <httpHandlers> <httpModules> <httpRuntime> <identity> <machineKey> <membership> <mobileControls> <pages> <processModel> <profile> <roleManager> <securityPolicy> <sessionPageState> <sessionState> <siteMap> <trace> <trust> <urlMappings> <webControls> <webParts> <webServices> <xhtmlConformance> </system.web> The following table provides brief description of some of common sub elements of the system.web element: This is required to identify users who are not authenticated when authorization is required. It configures the authentication support. The basic syntax is as given: <authentication mode="[Windows|Forms|Passport|None]"> <forms>...</forms> <passport/> </authentication> It configures the authorization support. The basic syntax is as given: <authorization> <allow .../> <deny .../> </authorization> It Configures the cache settings. The basic syntax is as given: <caching> <cache>...</cache> <outputCache>...</outputCache> <outputCacheSettings>...</outputCacheSettings> <sqlCacheDependency>...</sqlCacheDependency> </caching> It defines custom error messages. The basic syntax is as given: <customErrors defaultRedirect="url" mode="On|Off|RemoteOnly"> <error. . ./> </customErrors> It defines configuration settings used for deployment. The basic syntax is as follows: <deployment retail="true|false" /> It defines configuration settings for hosting environment. The basic syntax is as follows: <hostingEnvironment idleTimeout="HH:MM:SS" shadowCopyBinAssemblies="true|false" shutdownTimeout="number" urlMetadataSlidingExpiration="HH:MM:SS" /> It configures the identity of the application. The basic syntax is as given: <identity impersonate="true|false" userName="domain\username" password="<secure password>"/> It configures keys to use for encryption and decryption of Forms authentication cookie data. It also allows configuring a validation key that performs message authentication checks on view-state data and forms authentication tickets. The basic syntax is: <machineKey validationKey="AutoGenerate,IsolateApps" [String] decryptionKey="AutoGenerate,IsolateApps" [String] validation="HMACSHA256" [SHA1 | MD5 | 3DES | AES | HMACSHA256 | HMACSHA384 | HMACSHA512 | alg:algorithm_name] decryption="Auto" [Auto | DES | 3DES | AES | alg:algorithm_name] /> This configures parameters of managing and authenticating user accounts. The basic syntax is: <membership defaultProvider="provider name" userIsOnlineTimeWindow="number of minutes" hashAlgorithmType="SHA1"> <providers>...</providers> </membership> It provides page-specific configurations. The basic syntax is: <pages asyncTimeout="number" autoEventWireup="[True|False]" buffer="[True|False]" clientIDMode="[AutoID|Predictable|Static]" compilationMode="[Always|Auto|Never]" controlRenderingCompatibilityVersion="[3.5|4.0]" enableEventValidation="[True|False]" enableSessionState="[True|False|ReadOnly]" enableViewState="[True|False]" enableViewStateMac="[True|False]" maintainScrollPositionOnPostBack="[True|False]" masterPageFile="file path" maxPageStateFieldLength="number" pageBaseType="typename, assembly" pageParserFilterType="string" smartNavigation="[True|False]" styleSheetTheme="string" theme="string" userControlBaseType="typename" validateRequest="[True|False]" viewStateEncryptionMode="[Always|Auto|Never]" > <controls>...</controls> <namespaces>...</namespaces> <tagMapping>...</tagMapping> <ignoreDeviceFilters>...</ignoreDeviceFilters> </pages> It configures user profile parameters. The basic syntax is: <profile enabled="true|false" inherits="fully qualified type reference" automaticSaveEnabled="true|false" defaultProvider="provider name"> <properties>...</properties> <providers>...</providers> </profile> It configures settings for user roles. The basic syntax is: <roleManager cacheRolesInCookie="true|false" cookieName="name" cookiePath="/" cookieProtection="All|Encryption|Validation|None" cookieRequireSSL="true|false " cookieSlidingExpiration="true|false " cookieTimeout="number of minutes" createPersistentCookie="true|false" defaultProvider="provider name" domain="cookie domain"> enabled="true|false" maxCachedResults="maximum number of role names cached" <providers>...</providers> </roleManager> It configures the security policy. The basic syntax is: <securityPolicy> <trustLevel /> </securityPolicy> It defines mappings to hide the original URL and provide a more user friendly URL. The basic syntax is: <urlMappings enabled="true|false"> <add.../> <clear /> <remove.../> </urlMappings> It provides the name of shared location for client scripts. The basic syntax is: <webControls clientScriptsLocation="String" /> This configures the web services. 51 Lectures 5.5 hours Anadi Sharma 44 Lectures 4.5 hours Kaushik Roy Chowdhury 42 Lectures 18 hours SHIVPRASAD KOIRALA 57 Lectures 3.5 hours University Code 40 Lectures 2.5 hours University Code 138 Lectures 9 hours Bhrugen Patel Print Add Notes Bookmark this page
[ { "code": null, "e": 2448, "s": 2347, "text": "The behavior of an ASP.NET application is affected by different settings in the configuration files:" }, { "code": null, "e": 2463, "s": 2448, "text": "machine.config" }, { "code": null, "e": 2474, "s": 2463, "text": "web.config" }, { "code": null, "e": 2700, "s": 2474, "text": "The machine.config file contains default and the machine-specific value for all supported settings. The machine settings are controlled by the system administrator and applications are generally not given access to this file." }, { "code": null, "e": 2866, "s": 2700, "text": "An application however, can override the default values by creating web.config files in its roots folder. The web.config file is a subset of the machine.config file." }, { "code": null, "e": 3044, "s": 2866, "text": "If the application contains child directories, it can define a web.config file for each folder. Scope of each configuration file is determined in a hierarchical top-down manner." }, { "code": null, "e": 3147, "s": 3044, "text": "Any web.config file can locally extend, restrict, or override any settings defined on the upper level." }, { "code": null, "e": 3337, "s": 3147, "text": "Visual Studio generates a default web.config file for each project. An application can execute without a web.config file, however, you cannot debug an application without a web.config file." }, { "code": null, "e": 3444, "s": 3337, "text": "The following figure shows the Solution Explorer for the sample example used in the web services tutorial:" }, { "code": null, "e": 3577, "s": 3444, "text": "In this application, there are two web.config files for two projects i.e., the web service and the web site calling the web service." }, { "code": null, "e": 3806, "s": 3577, "text": "The web.config file has the configuration element as the root node. Information inside this element is grouped into two main areas: the configuration section-handler declaration area, and the configuration section settings area." }, { "code": null, "e": 3881, "s": 3806, "text": "The following code snippet shows the basic syntax of a configuration file:" }, { "code": null, "e": 4418, "s": 3881, "text": "<configuration>\n\n <!-- Configuration section-handler declaration area. -->\n <configSections>\n <section name=\"section1\" type=\"section1Handler\" />\n <section name=\"section2\" type=\"section2Handler\" />\n </configSections>\n <!-- Configuration section settings area. -->\n \n <section1>\n <s1Setting1 attribute1=\"attr1\" />\n </section1>\n \n <section2>\n <s2Setting1 attribute1=\"attr1\" />\n </section2>\n \n <system.web>\n <authentication mode=\"Windows\" />\n </system.web>\n \n</configuration>" }, { "code": null, "e": 4673, "s": 4418, "text": "The configuration section handlers are contained within the <configSections> tags. Each configuration handler specifies name of a configuration section, contained within the file, which provides some configuration data. It has the following basic syntax:" }, { "code": null, "e": 4769, "s": 4673, "text": "<configSections>\n <section />\n <sectionGroup />\n <remove />\n <clear/>\n</configSections>" }, { "code": null, "e": 4800, "s": 4769, "text": "It has the following elements:" }, { "code": null, "e": 4876, "s": 4800, "text": "Clear - It removes all references to inherited sections and section groups." }, { "code": null, "e": 4952, "s": 4876, "text": "Clear - It removes all references to inherited sections and section groups." }, { "code": null, "e": 5027, "s": 4952, "text": "Remove - It removes a reference to an inherited section and section group." }, { "code": null, "e": 5102, "s": 5027, "text": "Remove - It removes a reference to an inherited section and section group." }, { "code": null, "e": 5207, "s": 5102, "text": "Section - It defines an association between a configuration section handler and a configuration element." }, { "code": null, "e": 5312, "s": 5207, "text": "Section - It defines an association between a configuration section handler and a configuration element." }, { "code": null, "e": 5423, "s": 5312, "text": "Section group - It defines an association between a configuration section handler and a configuration section." }, { "code": null, "e": 5534, "s": 5423, "text": "Section group - It defines an association between a configuration section handler and a configuration section." }, { "code": null, "e": 5690, "s": 5534, "text": "The application settings allow storing application-wide name-value pairs for read-only access. For example, you can define a custom application setting as:" }, { "code": null, "e": 5818, "s": 5690, "text": "<configuration>\n <appSettings>\n <add key=\"Application Name\" value=\"MyApplication\" /> \n </appSettings>\n</configuration>" }, { "code": null, "e": 5890, "s": 5818, "text": "For example, you can also store the name of a book and its ISBN number:" }, { "code": null, "e": 6062, "s": 5890, "text": "<configuration>\n <appSettings>\n <add key=\"appISBN\" value=\"0-273-68726-3\" />\n <add key=\"appBook\" value=\"Corporate Finance\" />\n </appSettings>\n</configuration>" }, { "code": null, "e": 6167, "s": 6062, "text": "The connection strings show which database connection strings are available to the website. For example:" }, { "code": null, "e": 6658, "s": 6167, "text": "<connectionStrings>\n <add name=\"ASPDotNetStepByStepConnectionString\" \n connectionString=\"Provider=Microsoft.Jet.OLEDB.4.0;\n Data Source=E:\\\\projects\\datacaching\\ /\n datacaching\\App_Data\\ASPDotNetStepByStep.mdb\"\n providerName=\"System.Data.OleDb\" />\n \n <add name=\"booksConnectionString\" \n connectionString=\"Provider=Microsoft.Jet.OLEDB.4.0;\n Data Source=C:\\ \\databinding\\App_Data\\books.mdb\"\n providerName=\"System.Data.OleDb\" />\n</connectionStrings>" }, { "code": null, "e": 6863, "s": 6658, "text": "The system.web element specifies the root element for the ASP.NET configuration section and contains configuration elements that configure ASP.NET Web applications and control how the applications behave." }, { "code": null, "e": 6999, "s": 6863, "text": "It holds most of the configuration elements needed to be adjusted in common applications. The basic syntax for the element is as given:" }, { "code": null, "e": 7690, "s": 6999, "text": "<system.web> \n <anonymousIdentification> \n <authentication> \n <authorization> \n <browserCaps> \n <caching> \n <clientTarget> \n <compilation> \n <customErrors> \n <deployment> \n <deviceFilters> \n <globalization> \n <healthMonitoring> \n <hostingEnvironment> \n <httpCookies> \n <httpHandlers> \n <httpModules> \n <httpRuntime> \n <identity> \n <machineKey> \n <membership> \n <mobileControls> \n <pages> \n <processModel> \n <profile> \n <roleManager> \n <securityPolicy> \n <sessionPageState> \n <sessionState> \n <siteMap> \n <trace> \n <trust> \n <urlMappings> \n <webControls> \n <webParts> \n <webServices> \n <xhtmlConformance> \n</system.web>" }, { "code": null, "e": 7795, "s": 7690, "text": "The following table provides brief description of some of common sub elements of the system.web element:" }, { "code": null, "e": 7888, "s": 7795, "text": "This is required to identify users who are not authenticated when authorization is required." }, { "code": null, "e": 7960, "s": 7888, "text": "It configures the authentication support. The basic syntax is as given:" }, { "code": null, "e": 8070, "s": 7960, "text": "<authentication mode=\"[Windows|Forms|Passport|None]\"> \n <forms>...</forms>\n <passport/>\n</authentication>" }, { "code": null, "e": 8141, "s": 8070, "text": "It configures the authorization support. The basic syntax is as given:" }, { "code": null, "e": 8206, "s": 8141, "text": "<authorization> \n <allow .../>\n <deny .../>\n</authorization>" }, { "code": null, "e": 8270, "s": 8206, "text": "It Configures the cache settings. The basic syntax is as given:" }, { "code": null, "e": 8445, "s": 8270, "text": "<caching>\n <cache>...</cache>\n <outputCache>...</outputCache>\n <outputCacheSettings>...</outputCacheSettings>\n <sqlCacheDependency>...</sqlCacheDependency>\n</caching>" }, { "code": null, "e": 8509, "s": 8445, "text": "It defines custom error messages. The basic syntax is as given:" }, { "code": null, "e": 8604, "s": 8509, "text": "<customErrors defaultRedirect=\"url\" mode=\"On|Off|RemoteOnly\">\n <error. . ./>\n</customErrors>" }, { "code": null, "e": 8691, "s": 8604, "text": "It defines configuration settings used for deployment. The basic syntax is as follows:" }, { "code": null, "e": 8726, "s": 8691, "text": "<deployment retail=\"true|false\" />" }, { "code": null, "e": 8817, "s": 8726, "text": "It defines configuration settings for hosting environment. The basic syntax is as follows:" }, { "code": null, "e": 8969, "s": 8817, "text": "<hostingEnvironment idleTimeout=\"HH:MM:SS\" shadowCopyBinAssemblies=\"true|false\" \n shutdownTimeout=\"number\" urlMetadataSlidingExpiration=\"HH:MM:SS\" />" }, { "code": null, "e": 9046, "s": 8969, "text": "It configures the identity of the application. The basic syntax is as given:" }, { "code": null, "e": 9142, "s": 9046, "text": "<identity impersonate=\"true|false\" userName=\"domain\\username\"\n password=\"<secure password>\"/>" }, { "code": null, "e": 9235, "s": 9142, "text": "It configures keys to use for encryption and decryption of Forms authentication cookie data." }, { "code": null, "e": 9397, "s": 9235, "text": "It also allows configuring a validation key that performs message authentication checks on view-state data and forms authentication tickets. The basic syntax is:" }, { "code": null, "e": 9700, "s": 9397, "text": "<machineKey validationKey=\"AutoGenerate,IsolateApps\" [String]\n decryptionKey=\"AutoGenerate,IsolateApps\" [String]\n validation=\"HMACSHA256\" [SHA1 | MD5 | 3DES | AES | HMACSHA256 | \n HMACSHA384 | HMACSHA512 | alg:algorithm_name]\n decryption=\"Auto\" [Auto | DES | 3DES | AES | alg:algorithm_name]\n/>" }, { "code": null, "e": 9794, "s": 9700, "text": "This configures parameters of managing and authenticating user accounts. The basic syntax is:" }, { "code": null, "e": 9954, "s": 9794, "text": "<membership defaultProvider=\"provider name\"\n userIsOnlineTimeWindow=\"number of minutes\" hashAlgorithmType=\"SHA1\">\n <providers>...</providers>\n</membership>" }, { "code": null, "e": 10017, "s": 9954, "text": "It provides page-specific configurations. The basic syntax is:" }, { "code": null, "e": 10995, "s": 10017, "text": "<pages asyncTimeout=\"number\" autoEventWireup=\"[True|False]\"\n buffer=\"[True|False]\" clientIDMode=\"[AutoID|Predictable|Static]\"\n compilationMode=\"[Always|Auto|Never]\" \n controlRenderingCompatibilityVersion=\"[3.5|4.0]\"\n enableEventValidation=\"[True|False]\"\n enableSessionState=\"[True|False|ReadOnly]\"\n enableViewState=\"[True|False]\"\n enableViewStateMac=\"[True|False]\"\n maintainScrollPositionOnPostBack=\"[True|False]\" \n masterPageFile=\"file path\" \n maxPageStateFieldLength=\"number\" \n pageBaseType=\"typename, assembly\"\n pageParserFilterType=\"string\" \n smartNavigation=\"[True|False]\"\n styleSheetTheme=\"string\"\n theme=\"string\"\n userControlBaseType=\"typename\"\n validateRequest=\"[True|False]\"\n viewStateEncryptionMode=\"[Always|Auto|Never]\" >\n \n <controls>...</controls>\n <namespaces>...</namespaces>\n <tagMapping>...</tagMapping>\n <ignoreDeviceFilters>...</ignoreDeviceFilters>\n</pages>" }, { "code": null, "e": 11055, "s": 10995, "text": "It configures user profile parameters. The basic syntax is:" }, { "code": null, "e": 11278, "s": 11055, "text": "<profile enabled=\"true|false\" inherits=\"fully qualified type reference\"\n automaticSaveEnabled=\"true|false\" defaultProvider=\"provider name\">\n \n <properties>...</properties>\n <providers>...</providers>\n \n</profile>" }, { "code": null, "e": 11338, "s": 11278, "text": "It configures settings for user roles. The basic syntax is:" }, { "code": null, "e": 11805, "s": 11338, "text": "<roleManager cacheRolesInCookie=\"true|false\" cookieName=\"name\"\n cookiePath=\"/\" cookieProtection=\"All|Encryption|Validation|None\"\n cookieRequireSSL=\"true|false \" cookieSlidingExpiration=\"true|false \"\n cookieTimeout=\"number of minutes\" createPersistentCookie=\"true|false\"\n defaultProvider=\"provider name\" domain=\"cookie domain\"> \n enabled=\"true|false\"\n maxCachedResults=\"maximum number of role names cached\"\n \n <providers>...</providers>\n</roleManager>" }, { "code": null, "e": 11861, "s": 11805, "text": "It configures the security policy. The basic syntax is:" }, { "code": null, "e": 11914, "s": 11861, "text": "<securityPolicy>\n <trustLevel />\n</securityPolicy>" }, { "code": null, "e": 12018, "s": 11914, "text": "It defines mappings to hide the original URL and provide a more user friendly URL. The basic syntax is:" }, { "code": null, "e": 12110, "s": 12018, "text": "<urlMappings enabled=\"true|false\">\n <add.../>\n <clear />\n <remove.../>\n</urlMappings>" }, { "code": null, "e": 12191, "s": 12110, "text": "It provides the name of shared location for client scripts. The basic syntax is:" }, { "code": null, "e": 12238, "s": 12191, "text": "<webControls clientScriptsLocation=\"String\" />" }, { "code": null, "e": 12272, "s": 12238, "text": "This configures the web services." }, { "code": null, "e": 12307, "s": 12272, "text": "\n 51 Lectures \n 5.5 hours \n" }, { "code": null, "e": 12321, "s": 12307, "text": " Anadi Sharma" }, { "code": null, "e": 12356, "s": 12321, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 12379, "s": 12356, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 12413, "s": 12379, "text": "\n 42 Lectures \n 18 hours \n" }, { "code": null, "e": 12433, "s": 12413, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 12468, "s": 12433, "text": "\n 57 Lectures \n 3.5 hours \n" }, { "code": null, "e": 12485, "s": 12468, "text": " University Code" }, { "code": null, "e": 12520, "s": 12485, "text": "\n 40 Lectures \n 2.5 hours \n" }, { "code": null, "e": 12537, "s": 12520, "text": " University Code" }, { "code": null, "e": 12571, "s": 12537, "text": "\n 138 Lectures \n 9 hours \n" }, { "code": null, "e": 12586, "s": 12571, "text": " Bhrugen Patel" }, { "code": null, "e": 12593, "s": 12586, "text": " Print" }, { "code": null, "e": 12604, "s": 12593, "text": " Add Notes" } ]
How to Show Gridlines on Matplotlib Plots? - GeeksforGeeks
28 Nov, 2021 In this article, we will see how we can add gridlines to a matplotlib graph and various configurable parameters that can be used in Python. Example: Create a matplotlib plot using sample data. Python # Importing the libraryimport matplotlib.pyplot as plt # Define X and Y data pointsX = [12, 34, 23, 45, 67, 89]Y = [1, 3, 67, 78, 7, 5] # Plot the graph using matplotlibplt.plot(X, Y) # Function to view the plotplt.show() Output The grid() method is used to define a grid in a matplotlib graph. The syntax is given by – Syntax: matplotlib.pyplot.grid(b=None, which=’major’, axis=’both’, **kwargs) Parameters: b: bool or None, optional: Whether to show the grid lines. If any kwargs are supplied, it is assumed you want the grid on and b will be set to True. If b is None and there are no kwargs, this toggles the visibility of the lines. which: {‘major’, ‘minor’, ‘both’}, optional: The grid lines to apply the changes on. axis: {‘both’, ‘x’, ‘y’}, optional: The axis to apply the changes on. **kwargs: Line2D properties: Define the line properties of the grid Example 1: Default Gridlines Python # Importing the libraryimport matplotlib.pyplot as plt # Define X and Y data pointsX = [12, 34, 23, 45, 67, 89]Y = [1, 3, 67, 78, 7, 5] # Plot the graph using matplotlibplt.plot(X, Y) # Add gridlines to the plotplt.grid(b=True)# `plt.grid()` also works # Function to view the plotplt.show() Output Example 2: Apply Gridlines to x- axis In the cases, where we would want to see only the vertical or horizontal gridlines, we can make use of the `axis` parameter. To view only vertical gridlines – Syntax: plt.grid(b=True, axis='x') Python3 # Importing the libraryimport matplotlib.pyplot as plt # Define X and Y data pointsX = [12, 34, 23, 45, 67, 89]Y = [1, 3, 67, 78, 7, 5] # Plot the graph using matplotlibplt.plot(X, Y) # Add gridlines to the plotplt.grid(b=True, axis='x')# `plt.grid()` also works # Function to view the plotplt.show() Output: Example 3: Apply Gridlines to y-axis In the cases, where we would want to see only the vertical or horizontal gridlines, we can make use of the `axis` parameter. To view only horizontal gridlines – Syntax: plt.grid(b=True, axis='y') Python3 # Importing the libraryimport matplotlib.pyplot as plt # Define X and Y data pointsX = [12, 34, 23, 45, 67, 89]Y = [1, 3, 67, 78, 7, 5] # Plot the graph using matplotlibplt.plot(X, Y) # Add gridlines to the plotplt.grid(b=True, axis='y')# `plt.grid()` also works # Function to view the plotplt.show() Output: Example 4: Provide a linestyle and linewidth We have seen the gridlines being a solid lines. We can change this to view a different line-style like dashes using an argument `linestyle` or `ls`. Similarly, we can change the thickness of the gridlines using the argument `linewidth`. These arguments are provided as part of the keyword arguments and can be viewed in the document link. To provide a line style – Syntax: plt.grid(linestyle='--') Python3 # Importing the libraryimport matplotlib.pyplot as plt # Define X and Y data pointsX = [12, 34, 23, 45, 67, 89]Y = [1, 3, 67, 78, 7, 5] # Plot the graph using matplotlibplt.plot(X, Y) # Add gridlines to the plotplt.grid(linestyle='--')# `plt.grid()` also works # Function to view the plotplt.show() Output: . Example 5: Change color of the Gridlines The keyword argument `color` can be used to define a different color to the plot. Syntax: plt.grid(linestyle, color) Python3 # Importing the libraryimport matplotlib.pyplot as plt # Define X and Y data pointsX = [12, 34, 23, 45, 67, 89]Y = [1, 3, 67, 78, 7, 5] # Plot the graph using matplotlibplt.plot(X, Y) # Add gridlines to the plotplt.grid(linestyle='--', color='pink')# `plt.grid()` also works # Function to view the plotplt.show() Output: Picked Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python OOPs Concepts How to Install PIP on Windows ? Bar Plot in Matplotlib Defaultdict in Python Python Classes and Objects Deque in Python Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python - Ways to remove duplicates from list Class method vs Static method in Python
[ { "code": null, "e": 23901, "s": 23873, "text": "\n28 Nov, 2021" }, { "code": null, "e": 24041, "s": 23901, "text": "In this article, we will see how we can add gridlines to a matplotlib graph and various configurable parameters that can be used in Python." }, { "code": null, "e": 24050, "s": 24041, "text": "Example:" }, { "code": null, "e": 24095, "s": 24050, "text": " Create a matplotlib plot using sample data." }, { "code": null, "e": 24102, "s": 24095, "text": "Python" }, { "code": "# Importing the libraryimport matplotlib.pyplot as plt # Define X and Y data pointsX = [12, 34, 23, 45, 67, 89]Y = [1, 3, 67, 78, 7, 5] # Plot the graph using matplotlibplt.plot(X, Y) # Function to view the plotplt.show()", "e": 24327, "s": 24102, "text": null }, { "code": null, "e": 24334, "s": 24327, "text": "Output" }, { "code": null, "e": 24425, "s": 24334, "text": "The grid() method is used to define a grid in a matplotlib graph. The syntax is given by –" }, { "code": null, "e": 24433, "s": 24425, "text": "Syntax:" }, { "code": null, "e": 24502, "s": 24433, "text": "matplotlib.pyplot.grid(b=None, which=’major’, axis=’both’, **kwargs)" }, { "code": null, "e": 24514, "s": 24502, "text": "Parameters:" }, { "code": null, "e": 24743, "s": 24514, "text": "b: bool or None, optional: Whether to show the grid lines. If any kwargs are supplied, it is assumed you want the grid on and b will be set to True. If b is None and there are no kwargs, this toggles the visibility of the lines." }, { "code": null, "e": 24828, "s": 24743, "text": "which: {‘major’, ‘minor’, ‘both’}, optional: The grid lines to apply the changes on." }, { "code": null, "e": 24898, "s": 24828, "text": "axis: {‘both’, ‘x’, ‘y’}, optional: The axis to apply the changes on." }, { "code": null, "e": 24966, "s": 24898, "text": "**kwargs: Line2D properties: Define the line properties of the grid" }, { "code": null, "e": 24995, "s": 24966, "text": "Example 1: Default Gridlines" }, { "code": null, "e": 25002, "s": 24995, "text": "Python" }, { "code": "# Importing the libraryimport matplotlib.pyplot as plt # Define X and Y data pointsX = [12, 34, 23, 45, 67, 89]Y = [1, 3, 67, 78, 7, 5] # Plot the graph using matplotlibplt.plot(X, Y) # Add gridlines to the plotplt.grid(b=True)# `plt.grid()` also works # Function to view the plotplt.show()", "e": 25297, "s": 25002, "text": null }, { "code": null, "e": 25304, "s": 25297, "text": "Output" }, { "code": null, "e": 25343, "s": 25304, "text": "Example 2: Apply Gridlines to x- axis" }, { "code": null, "e": 25502, "s": 25343, "text": "In the cases, where we would want to see only the vertical or horizontal gridlines, we can make use of the `axis` parameter. To view only vertical gridlines –" }, { "code": null, "e": 25510, "s": 25502, "text": "Syntax:" }, { "code": null, "e": 25537, "s": 25510, "text": "plt.grid(b=True, axis='x')" }, { "code": null, "e": 25545, "s": 25537, "text": "Python3" }, { "code": "# Importing the libraryimport matplotlib.pyplot as plt # Define X and Y data pointsX = [12, 34, 23, 45, 67, 89]Y = [1, 3, 67, 78, 7, 5] # Plot the graph using matplotlibplt.plot(X, Y) # Add gridlines to the plotplt.grid(b=True, axis='x')# `plt.grid()` also works # Function to view the plotplt.show()", "e": 25850, "s": 25545, "text": null }, { "code": null, "e": 25858, "s": 25850, "text": "Output:" }, { "code": null, "e": 25895, "s": 25858, "text": "Example 3: Apply Gridlines to y-axis" }, { "code": null, "e": 26056, "s": 25895, "text": "In the cases, where we would want to see only the vertical or horizontal gridlines, we can make use of the `axis` parameter. To view only horizontal gridlines –" }, { "code": null, "e": 26064, "s": 26056, "text": "Syntax:" }, { "code": null, "e": 26092, "s": 26064, "text": " plt.grid(b=True, axis='y')" }, { "code": null, "e": 26100, "s": 26092, "text": "Python3" }, { "code": "# Importing the libraryimport matplotlib.pyplot as plt # Define X and Y data pointsX = [12, 34, 23, 45, 67, 89]Y = [1, 3, 67, 78, 7, 5] # Plot the graph using matplotlibplt.plot(X, Y) # Add gridlines to the plotplt.grid(b=True, axis='y')# `plt.grid()` also works # Function to view the plotplt.show()", "e": 26405, "s": 26100, "text": null }, { "code": null, "e": 26413, "s": 26405, "text": "Output:" }, { "code": null, "e": 26458, "s": 26413, "text": "Example 4: Provide a linestyle and linewidth" }, { "code": null, "e": 26797, "s": 26458, "text": "We have seen the gridlines being a solid lines. We can change this to view a different line-style like dashes using an argument `linestyle` or `ls`. Similarly, we can change the thickness of the gridlines using the argument `linewidth`. These arguments are provided as part of the keyword arguments and can be viewed in the document link." }, { "code": null, "e": 26823, "s": 26797, "text": "To provide a line style –" }, { "code": null, "e": 26831, "s": 26823, "text": "Syntax:" }, { "code": null, "e": 26856, "s": 26831, "text": "plt.grid(linestyle='--')" }, { "code": null, "e": 26864, "s": 26856, "text": "Python3" }, { "code": "# Importing the libraryimport matplotlib.pyplot as plt # Define X and Y data pointsX = [12, 34, 23, 45, 67, 89]Y = [1, 3, 67, 78, 7, 5] # Plot the graph using matplotlibplt.plot(X, Y) # Add gridlines to the plotplt.grid(linestyle='--')# `plt.grid()` also works # Function to view the plotplt.show()", "e": 27167, "s": 26864, "text": null }, { "code": null, "e": 27175, "s": 27167, "text": "Output:" }, { "code": null, "e": 27177, "s": 27175, "text": "." }, { "code": null, "e": 27218, "s": 27177, "text": "Example 5: Change color of the Gridlines" }, { "code": null, "e": 27300, "s": 27218, "text": "The keyword argument `color` can be used to define a different color to the plot." }, { "code": null, "e": 27308, "s": 27300, "text": "Syntax:" }, { "code": null, "e": 27335, "s": 27308, "text": "plt.grid(linestyle, color)" }, { "code": null, "e": 27343, "s": 27335, "text": "Python3" }, { "code": "# Importing the libraryimport matplotlib.pyplot as plt # Define X and Y data pointsX = [12, 34, 23, 45, 67, 89]Y = [1, 3, 67, 78, 7, 5] # Plot the graph using matplotlibplt.plot(X, Y) # Add gridlines to the plotplt.grid(linestyle='--', color='pink')# `plt.grid()` also works # Function to view the plotplt.show()", "e": 27660, "s": 27343, "text": null }, { "code": null, "e": 27668, "s": 27660, "text": "Output:" }, { "code": null, "e": 27677, "s": 27670, "text": "Picked" }, { "code": null, "e": 27695, "s": 27677, "text": "Python-matplotlib" }, { "code": null, "e": 27702, "s": 27695, "text": "Python" }, { "code": null, "e": 27800, "s": 27702, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27809, "s": 27800, "text": "Comments" }, { "code": null, "e": 27822, "s": 27809, "text": "Old Comments" }, { "code": null, "e": 27843, "s": 27822, "text": "Python OOPs Concepts" }, { "code": null, "e": 27875, "s": 27843, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27898, "s": 27875, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 27920, "s": 27898, "text": "Defaultdict in Python" }, { "code": null, "e": 27947, "s": 27920, "text": "Python Classes and Objects" }, { "code": null, "e": 27963, "s": 27947, "text": "Deque in Python" }, { "code": null, "e": 28005, "s": 27963, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28061, "s": 28005, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28106, "s": 28061, "text": "Python - Ways to remove duplicates from list" } ]
A short tutorial on Fuzzy Time Series — Part II | by Petrônio Silva | Towards Data Science
In the first part of this tutorial I briefly explained time series analysis, fuzzy sets and what are the Fuzzy Time Series — FTS, with a short introduction to the pyFTS library. It was awesome! I got feedback from people around the world and I heard very good ideas coming from them. But, as occurs in every introductory study, we used very simple methods and data with the aim of to facilitate the general understanding of this approach. But now, with the assumption that the readers already know the background needed, we can advance a little bit and play with more useful things. To start we going to see an intuitive introduction to the concept of bias/variance, then we will go learn some of the most import FTS hyperparameters and their impact on model’s accuracy. To finish we will employ some FTS models to model and predict solar radiation time series, useful on photovoltaic energy prediction. All examples of this tutorial are available on Google Colab, on http://bit.ly/short_tutorial_colab2 . Feel free to get in touch, give ou feedback and ask questions. Now, let’s get started! The training of machine learning models is a clash to separate the signal from the noise, the general behavior from local specificities and random errors. On the training of every estimator there is a clash between the bias and the variance, between the underfit and the overfit. Given a numeric time series Y, its individual values y(t)∈Y, and an estimator for Y, a function ŷ(t+1) = f( y(t) ). The aim of f is to predict Y the best possible way, making the difference ε(t) between the real value y(t) and the predicted value ŷ(t) tends to zero, or in other words for ε(t) = y(t) — ŷ(t) and t → ∞, lim ε(t) = 0. Intuitively, a biased estimator is one whose expected value of ε (t) is different from zero — E [ε (t)] ≠ 0. The bias is a systematic “deviation” of the correct value and remember that the estimator will often have deviations from the real value and this is expected, but on average these deviations should tend to zero. The bias is typical of the underfitted model, when the model was not able to learn the signal, the component of the time series that interests us. In the other hand, the variance has to do with the power of generalization of the model, especially with data that were not presented during the training phase. The high variance is related to the overfitting, when the model start to learn specificities of the training sample that do not generalize well for the test data. In short: the model learned the noise of the data. It is known that is not possible to completely eliminate the bias and variance side effects, and the best fit is achieved by the balance between them — this is the challenge of estimation models. Several parameters determine the best fit of an FTS model, but the principal ones are the partitioning and the order. These two parameters account for 90% (empirical value) of the accuracy of the model. Partitioning is composed of three parameters, listed here according to their importance: 1a) Number of partitions (or fuzzy sets) This is simply the most influential parameter in the model accuracy. The more fuzzy sets the more precise is the capture of the characteristics of the time series. And there is a trap that lies right here: Too few fuzzy sets generate underfitting, due to signal over simplification; Too much fuzzy sets generates overfitting, making the model to start learning noise on data; The number of sets is a parameter that must be benchmarked. In time series that have been differentiated 10 partitions is a good number to start. In other cases, 35 partitions is a good number. 1b) Partitioning type There are many types of partitioning, from Grid partitioning (GridPartitioner) where all sets are evenly distributed and have the same format, going through partitioners where sets have distinct sizes — such as entropy-based and cluster-based partitioners. I will not go deep into this discussion here, but for the curious there are several examples of partitioning types in the PYFTS/notebooks repository. Always start with Grid partitioning, then if it is the case, explore the other types. 1c) Membership functions This is a parameter that has little real influence on the accuracy of the model, but depending on the case you may have a good reason for using a Gaussian or trapezoidal function instead of the triangular function, which is the default. One of the justifications may be the number of parameters (the Gaussian uses 2, the triangular 3 and the trapezoidal 4), the legibility of the model or even other issues related to the nature of the process and the data. Once again I will not delve into this discussion here, take a look at the PYFTS/notebooks repository for more details. The order of the model is the second most important parameter of the FTS, since they are autoregressive models (use lagged values to predict the next ones). The order parameter is the memory size of the model, or how much past information is needed to describe future events. To decide this parameter it is important to be familiar with the concept of Autocorrelation Function — ACF. The ACF is not only able to indicate the order as well as the indexes of the most important lags. The order is the amount of lags (past values) that are used by the models. This is really very important and depends on the type of time series being modeled. The question here is: how many lags do I need for the model to learn the temporal patterns, cycles, seasonalities, etc? Look at the ACF and see how many are the significant lags. However there is a trap here: as more lags the model uses (especially if the number of partitions is large!) and as larger the model is, slowest the learning and inference becomes. In my experience, it takes no more than 3 lags to describe a time series behavior. But of course everything depends on the data. By default, the most recent lags, in order, are chosen by the model. But depending on the seasonality of the time series these may not be the best lags. So look at the ACF and see which lags indexes are the most significant. The literature on FTS methods is very diversified, but two features are extremely important: The weights increase the accuracy of the model, balancing which sets in the rules of the model are more influential for the forecast. They slightly lessen the readability of the model, but nothing awfully. If you have to choose, always prefer the weighted models ! In the example below we can compare the model HOFTS (without weights), WHOFTS (with weights in consequent of the rules) and PWFTS (with weights in the consequent and the precedent of the rules): Most of the time we only have time series with one variable — the endogenous variable. Other times this variable is aided by other information (the exogenous variables) from which we can take advantage. For instance the date, usually associated with time series measurements, is a very valuable information in the case of seasonal data — such as social, environmental, etc. data. If you have multivariate data then the first thing is to know if there is correlation between variables, so use a correlation matrix to check it. The correlation coefficient point to simple linear relationship, so it should not be the unique tool you should use, the cross-entropy is a good alternative. Another tip: If you have a monovariate time series you can enrich your model by creating a multivariate series from it, where the other variables are transformations of the endogenous variable. For example, you can have a multivariate series with the original (endogenous) variable and the differentiated endogenous variable, providing extra information about the recent fluctuations of the values. It is time to have some fun! Just to remember: all codes and results are available at http://bit.ly/short_tutorial_colab2. I will use the solar radiation data from SONDA — National Environmental Data Organization System from Brazil, specifically from Brasília/DF station. Radiation data is in the ‘glo_avg’ variable, sampled per minute, 24 hours per day, from 2013 to 2014 for the training set and the year 2015 for testing. As expected, the data is a bit noisy and there is no big need for the per-minute sampling. I cleaned the data and removed the other variables (whose correlation with our main variable is not so relevant) and left only the date and the endogenous variable. The next step was to reduce the data volume and the clean up the noise, I did this by sampling the hourly average of the series. The preprocessed data is available at the address https://data.world/petroniocandido/sonda-bsb-averaged-hourly. Intuitively the solar radiation has two main cycles, the daily cycle (the sun rotation movement) and the yearly cycle (the sun’s translation movement). The biggest uncertainty that affects this kind of forecasting is the weather and the presence of clouds in the sky. As you already know the methods in the pyFTS library are on the models package. We will then analyze how several FTS models perform in the modeling of this time series. In the real world we should start by optimizing the hyperparameters of the models by testing numerous combinations of all the parameters mentioned above. In pyFTS, we could use the hyperparam package where you can run a distributed Grid Search, which will make a cartesian product between all possible values of each hyperparameter and test each one. You could also use a genetic algorithm (hyperparam.Evolutive) or use the hyperopt library. But let’s keep it simple, okay? We will partition our endogenous variable using a grid scheme (GridPartitioner) with 35 partitions, separated into 5 subgroups, VL— Very Low, L— Low, M — Medium, H— High and VH— Very High, each subgroup with 7 levels. This nomenclature will make the model more interpretable by generating rules such as: L5 , L6 → L6 , M0 , M1 This rule can be read as: IF y(t-1) is Low (sublevel 5) AND y(t) is Low (sublevel 6) THEN y(t+1) will be Low(sublevel 6) OR Medium (sublevel 0) OR Medium (sublevel 1). According to the chosen rules (due to the membersguo of the precedent of the rule in relation to the input values) the defuzzyfication will transform the consequent into a numerical value (a simple method is the weighted average of the sets). We already have the partitioning scheme, so let’s explore the methods. We chose the high order methods (order> 1) with and without weights and all of them were tested with the order of 1 to 3. The methods and examples of the rules generated are listed below: hofts.HighOrderFTS: High order weightless method L4,VL0 → VL0,VL1L5,VL0 → VL0,VL1 hofts.WeightedHighOrderFTS: High order weighted method, where the weights are only on the consequent of each rule. L4,VL0 → VL0 (0.5), VL1 (0.5)L5,VL0 → VL0 (0.5), VL1 (0.5) pwfts.ProbabilisticWeightedFTS: High order weighted method, where the probabilistic weights are on the precedent and consequent of each rule. (0.003) L0,VL1 → (0.876)VL0, (0.103)VL1, (0.015)VL2, (0.006)VL3, (0.001)VL4(0.003) L0,VL2 → (0.003)L0, (0.003)L1, (0.003)L2, (0.0)L3, (0.0)L4, (0.787)VL0, (0.164)VL1, (0.03)VL2, (0.002)VL3, (0.002)VL4, (0.005)VL5, (0.001)VL6 On pyFTS, multivariate models use Pandas Dataframes as data input (univariate models use lists or Numpy arrays) and the methods are in the models.multivariate package. Each variable has its own partitioning scheme and other parameters. You must first create an object of type Variable, stating the name of the variable, the data column in the dataframe, and the partitioner. Then the exogenous and endogenous variables are incorporated to the model using the append_variable function. The endogenous variable must be setted in the target_variable property. from pyFTS.models.multivariate import common, variable, mvftsfrom pyFTS.models.seasonal import partitioner as seasonalfrom pyFTS.models.seasonal.common import DateTimesp = {'seasonality': DateTime.day_of_year , 'names': ['Jan','Feb','Mar','Apr','May','Jun','Jul', 'Aug','Sep','Oct','Nov','Dec']}month = variable.Variable("Month", data_label="data", partitioner=seasonal.TimeGridPartitioner, npart=12,data=train_mv, partitioner_specific=sp)radiation = variable.Variable("Radiation", data_label="glo_avg", alias='rad',partitioner=Grid.GridPartitioner, npart=35, data=train_mv)model = mvfts.MultivariateFTS()model.append_variable(month)model.append_variable(radiation)model.target_variable = radiationmodel.fit(train_mv) Besides our endogenous variable ‘glo_avg’, we will use only the ‘date’ column and extract two exogenous variables from it: the month and the hour. The partitioning of the variables is showed below: You may be asking yourself: Why are the sets of hours and months overlapping? After all, this is very accurate information! Answer: That is fuzzy logic guys! We assume that neighbors things influence each other and have similar behaviors, hence the rules of a specific time are also influenced by neighboring hours and months. Let’s now take a look at the multivariate methods and see examples of the rules generated by them: mvfts.MultivariateFTS: Weightless first order method (order = 1); Jan,8hs,VL0 → VL1,VL2,VL3,VL4,VL5Jan,8hs,VL1 → VL1,VL2,VL3,VL4,VL5,L0,L1,L3,L4 wmvfts.WeightedMultivariatedFTS: Weighted first order method; Jan,8hs,VL0 → VL2 (0.353), VL1 (0.253), VL4 (0.147), VL3 (0.207), VL5 (0.04)Jan,8hs,VL1 → VL2 (0.276), VL3 (0.172), VL1 (0.198), VL5 (0.083), VL4 (0.151), VL6 (0.021), L0 (0.036), L4 (0.005), L1 (0.036), L2 (0.021) granular.GranularWMVFTS: Weighted high order method; Jan11hsV3,Jan12hsL1 → Jan13hsVL6 (1.0)Jan12hsL1,Jan13hsVL6 → Jan15hsVL3 (1.0) Obviously the main criterion for evaluating a predictive model is its accuracy. We will use the Root Mean Squared Error (RMSE) and the lower this value the better. But another important criterion is parsimony: simpler models will always be more desirable than complex models. So we aim to minimize RMSE and model size. Let’s see the five best-performing models: It was expected that the multivariate models performed better then the univariate ones, after all, they had more information to exploit. But see that the most parsimonious model is the PWFTS! The possibilities do not stop there. We could now decide to make an ensemble of the best models (models.ensemble), or use non-stationary fuzzy sets (models.nonstationary). But this is for another opportunity! When we adopt an forecasting model we are also interested in predict not only the next value, but a sequence of these values. This is really cool because with just a few lags of information we can generate an estimate for many steps ahead! For the specific case of solar radiation forecasting we will set our prediction horizon for 48 hours. For an monovariate model on pyFTS this is very simple, just use the steps_ahead parameter of the predict function. This parameter will feed back the output values in the input, by the next steps_ahead iterations. forecasts = model.predict(input_data, steps_ahead=48) For multivariate models this is a little bit tricky: we are not generating only the values of the endogenous variable but also the values of the exogenous variables. As this value generation depends on the nature of each variable, the predict function will require, in addition to the steps_ahead parameter, the generators parameter, which is a dictionary that must contain a key for each Pandas DataFrame column and whose values are lambda functions that receive the current value of the variable and return the next value. In our example this is quite simple since the values of the exogenous variables are datetime and to calculate the next value we just need to add one hour to the input value: generator = lambda x : pd.to_datetime(x) + pd.to_timedelta(1, unit='h')forecasts = model.predict(input_data, steps_ahead=48, generators={'date': generator}) Now you have enough knowledge on FTS and the pyFTS library to employ them on your personal projects. Off course that still remains to talk about a lot of stuff! In the next tutorial we talk about interval and probabilistic forecasting, data transformations, non-stationary and incremental models, etc. Please don’t hesitate in get in touch if you need help, ask your questions or give feedback. See you later, guys!
[ { "code": null, "e": 610, "s": 171, "text": "In the first part of this tutorial I briefly explained time series analysis, fuzzy sets and what are the Fuzzy Time Series — FTS, with a short introduction to the pyFTS library. It was awesome! I got feedback from people around the world and I heard very good ideas coming from them. But, as occurs in every introductory study, we used very simple methods and data with the aim of to facilitate the general understanding of this approach." }, { "code": null, "e": 1075, "s": 610, "text": "But now, with the assumption that the readers already know the background needed, we can advance a little bit and play with more useful things. To start we going to see an intuitive introduction to the concept of bias/variance, then we will go learn some of the most import FTS hyperparameters and their impact on model’s accuracy. To finish we will employ some FTS models to model and predict solar radiation time series, useful on photovoltaic energy prediction." }, { "code": null, "e": 1264, "s": 1075, "text": "All examples of this tutorial are available on Google Colab, on http://bit.ly/short_tutorial_colab2 . Feel free to get in touch, give ou feedback and ask questions. Now, let’s get started!" }, { "code": null, "e": 1544, "s": 1264, "text": "The training of machine learning models is a clash to separate the signal from the noise, the general behavior from local specificities and random errors. On the training of every estimator there is a clash between the bias and the variance, between the underfit and the overfit." }, { "code": null, "e": 1880, "s": 1544, "text": "Given a numeric time series Y, its individual values y(t)∈Y, and an estimator for Y, a function ŷ(t+1) = f( y(t) ). The aim of f is to predict Y the best possible way, making the difference ε(t) between the real value y(t) and the predicted value ŷ(t) tends to zero, or in other words for ε(t) = y(t) — ŷ(t) and t → ∞, lim ε(t) = 0." }, { "code": null, "e": 2349, "s": 1880, "text": "Intuitively, a biased estimator is one whose expected value of ε (t) is different from zero — E [ε (t)] ≠ 0. The bias is a systematic “deviation” of the correct value and remember that the estimator will often have deviations from the real value and this is expected, but on average these deviations should tend to zero. The bias is typical of the underfitted model, when the model was not able to learn the signal, the component of the time series that interests us." }, { "code": null, "e": 2724, "s": 2349, "text": "In the other hand, the variance has to do with the power of generalization of the model, especially with data that were not presented during the training phase. The high variance is related to the overfitting, when the model start to learn specificities of the training sample that do not generalize well for the test data. In short: the model learned the noise of the data." }, { "code": null, "e": 2920, "s": 2724, "text": "It is known that is not possible to completely eliminate the bias and variance side effects, and the best fit is achieved by the balance between them — this is the challenge of estimation models." }, { "code": null, "e": 3123, "s": 2920, "text": "Several parameters determine the best fit of an FTS model, but the principal ones are the partitioning and the order. These two parameters account for 90% (empirical value) of the accuracy of the model." }, { "code": null, "e": 3212, "s": 3123, "text": "Partitioning is composed of three parameters, listed here according to their importance:" }, { "code": null, "e": 3253, "s": 3212, "text": "1a) Number of partitions (or fuzzy sets)" }, { "code": null, "e": 3459, "s": 3253, "text": "This is simply the most influential parameter in the model accuracy. The more fuzzy sets the more precise is the capture of the characteristics of the time series. And there is a trap that lies right here:" }, { "code": null, "e": 3536, "s": 3459, "text": "Too few fuzzy sets generate underfitting, due to signal over simplification;" }, { "code": null, "e": 3629, "s": 3536, "text": "Too much fuzzy sets generates overfitting, making the model to start learning noise on data;" }, { "code": null, "e": 3823, "s": 3629, "text": "The number of sets is a parameter that must be benchmarked. In time series that have been differentiated 10 partitions is a good number to start. In other cases, 35 partitions is a good number." }, { "code": null, "e": 3845, "s": 3823, "text": "1b) Partitioning type" }, { "code": null, "e": 4252, "s": 3845, "text": "There are many types of partitioning, from Grid partitioning (GridPartitioner) where all sets are evenly distributed and have the same format, going through partitioners where sets have distinct sizes — such as entropy-based and cluster-based partitioners. I will not go deep into this discussion here, but for the curious there are several examples of partitioning types in the PYFTS/notebooks repository." }, { "code": null, "e": 4338, "s": 4252, "text": "Always start with Grid partitioning, then if it is the case, explore the other types." }, { "code": null, "e": 4363, "s": 4338, "text": "1c) Membership functions" }, { "code": null, "e": 4600, "s": 4363, "text": "This is a parameter that has little real influence on the accuracy of the model, but depending on the case you may have a good reason for using a Gaussian or trapezoidal function instead of the triangular function, which is the default." }, { "code": null, "e": 4821, "s": 4600, "text": "One of the justifications may be the number of parameters (the Gaussian uses 2, the triangular 3 and the trapezoidal 4), the legibility of the model or even other issues related to the nature of the process and the data." }, { "code": null, "e": 4940, "s": 4821, "text": "Once again I will not delve into this discussion here, take a look at the PYFTS/notebooks repository for more details." }, { "code": null, "e": 5216, "s": 4940, "text": "The order of the model is the second most important parameter of the FTS, since they are autoregressive models (use lagged values to predict the next ones). The order parameter is the memory size of the model, or how much past information is needed to describe future events." }, { "code": null, "e": 5422, "s": 5216, "text": "To decide this parameter it is important to be familiar with the concept of Autocorrelation Function — ACF. The ACF is not only able to indicate the order as well as the indexes of the most important lags." }, { "code": null, "e": 5760, "s": 5422, "text": "The order is the amount of lags (past values) that are used by the models. This is really very important and depends on the type of time series being modeled. The question here is: how many lags do I need for the model to learn the temporal patterns, cycles, seasonalities, etc? Look at the ACF and see how many are the significant lags." }, { "code": null, "e": 5941, "s": 5760, "text": "However there is a trap here: as more lags the model uses (especially if the number of partitions is large!) and as larger the model is, slowest the learning and inference becomes." }, { "code": null, "e": 6070, "s": 5941, "text": "In my experience, it takes no more than 3 lags to describe a time series behavior. But of course everything depends on the data." }, { "code": null, "e": 6295, "s": 6070, "text": "By default, the most recent lags, in order, are chosen by the model. But depending on the seasonality of the time series these may not be the best lags. So look at the ACF and see which lags indexes are the most significant." }, { "code": null, "e": 6388, "s": 6295, "text": "The literature on FTS methods is very diversified, but two features are extremely important:" }, { "code": null, "e": 6653, "s": 6388, "text": "The weights increase the accuracy of the model, balancing which sets in the rules of the model are more influential for the forecast. They slightly lessen the readability of the model, but nothing awfully. If you have to choose, always prefer the weighted models !" }, { "code": null, "e": 6848, "s": 6653, "text": "In the example below we can compare the model HOFTS (without weights), WHOFTS (with weights in consequent of the rules) and PWFTS (with weights in the consequent and the precedent of the rules):" }, { "code": null, "e": 7051, "s": 6848, "text": "Most of the time we only have time series with one variable — the endogenous variable. Other times this variable is aided by other information (the exogenous variables) from which we can take advantage." }, { "code": null, "e": 7228, "s": 7051, "text": "For instance the date, usually associated with time series measurements, is a very valuable information in the case of seasonal data — such as social, environmental, etc. data." }, { "code": null, "e": 7532, "s": 7228, "text": "If you have multivariate data then the first thing is to know if there is correlation between variables, so use a correlation matrix to check it. The correlation coefficient point to simple linear relationship, so it should not be the unique tool you should use, the cross-entropy is a good alternative." }, { "code": null, "e": 7931, "s": 7532, "text": "Another tip: If you have a monovariate time series you can enrich your model by creating a multivariate series from it, where the other variables are transformations of the endogenous variable. For example, you can have a multivariate series with the original (endogenous) variable and the differentiated endogenous variable, providing extra information about the recent fluctuations of the values." }, { "code": null, "e": 8357, "s": 7931, "text": "It is time to have some fun! Just to remember: all codes and results are available at http://bit.ly/short_tutorial_colab2. I will use the solar radiation data from SONDA — National Environmental Data Organization System from Brazil, specifically from Brasília/DF station. Radiation data is in the ‘glo_avg’ variable, sampled per minute, 24 hours per day, from 2013 to 2014 for the training set and the year 2015 for testing." }, { "code": null, "e": 8854, "s": 8357, "text": "As expected, the data is a bit noisy and there is no big need for the per-minute sampling. I cleaned the data and removed the other variables (whose correlation with our main variable is not so relevant) and left only the date and the endogenous variable. The next step was to reduce the data volume and the clean up the noise, I did this by sampling the hourly average of the series. The preprocessed data is available at the address https://data.world/petroniocandido/sonda-bsb-averaged-hourly." }, { "code": null, "e": 9122, "s": 8854, "text": "Intuitively the solar radiation has two main cycles, the daily cycle (the sun rotation movement) and the yearly cycle (the sun’s translation movement). The biggest uncertainty that affects this kind of forecasting is the weather and the presence of clouds in the sky." }, { "code": null, "e": 9765, "s": 9122, "text": "As you already know the methods in the pyFTS library are on the models package. We will then analyze how several FTS models perform in the modeling of this time series. In the real world we should start by optimizing the hyperparameters of the models by testing numerous combinations of all the parameters mentioned above. In pyFTS, we could use the hyperparam package where you can run a distributed Grid Search, which will make a cartesian product between all possible values of each hyperparameter and test each one. You could also use a genetic algorithm (hyperparam.Evolutive) or use the hyperopt library. But let’s keep it simple, okay?" }, { "code": null, "e": 10069, "s": 9765, "text": "We will partition our endogenous variable using a grid scheme (GridPartitioner) with 35 partitions, separated into 5 subgroups, VL— Very Low, L— Low, M — Medium, H— High and VH— Very High, each subgroup with 7 levels. This nomenclature will make the model more interpretable by generating rules such as:" }, { "code": null, "e": 10092, "s": 10069, "text": "L5 , L6 → L6 , M0 , M1" }, { "code": null, "e": 10118, "s": 10092, "text": "This rule can be read as:" }, { "code": null, "e": 10260, "s": 10118, "text": "IF y(t-1) is Low (sublevel 5) AND y(t) is Low (sublevel 6) THEN y(t+1) will be Low(sublevel 6) OR Medium (sublevel 0) OR Medium (sublevel 1)." }, { "code": null, "e": 10503, "s": 10260, "text": "According to the chosen rules (due to the membersguo of the precedent of the rule in relation to the input values) the defuzzyfication will transform the consequent into a numerical value (a simple method is the weighted average of the sets)." }, { "code": null, "e": 10762, "s": 10503, "text": "We already have the partitioning scheme, so let’s explore the methods. We chose the high order methods (order> 1) with and without weights and all of them were tested with the order of 1 to 3. The methods and examples of the rules generated are listed below:" }, { "code": null, "e": 10811, "s": 10762, "text": "hofts.HighOrderFTS: High order weightless method" }, { "code": null, "e": 10844, "s": 10811, "text": "L4,VL0 → VL0,VL1L5,VL0 → VL0,VL1" }, { "code": null, "e": 10959, "s": 10844, "text": "hofts.WeightedHighOrderFTS: High order weighted method, where the weights are only on the consequent of each rule." }, { "code": null, "e": 11018, "s": 10959, "text": "L4,VL0 → VL0 (0.5), VL1 (0.5)L5,VL0 → VL0 (0.5), VL1 (0.5)" }, { "code": null, "e": 11160, "s": 11018, "text": "pwfts.ProbabilisticWeightedFTS: High order weighted method, where the probabilistic weights are on the precedent and consequent of each rule." }, { "code": null, "e": 11385, "s": 11160, "text": "(0.003) L0,VL1 → (0.876)VL0, (0.103)VL1, (0.015)VL2, (0.006)VL3, (0.001)VL4(0.003) L0,VL2 → (0.003)L0, (0.003)L1, (0.003)L2, (0.0)L3, (0.0)L4, (0.787)VL0, (0.164)VL1, (0.03)VL2, (0.002)VL3, (0.002)VL4, (0.005)VL5, (0.001)VL6" }, { "code": null, "e": 11942, "s": 11385, "text": "On pyFTS, multivariate models use Pandas Dataframes as data input (univariate models use lists or Numpy arrays) and the methods are in the models.multivariate package. Each variable has its own partitioning scheme and other parameters. You must first create an object of type Variable, stating the name of the variable, the data column in the dataframe, and the partitioner. Then the exogenous and endogenous variables are incorporated to the model using the append_variable function. The endogenous variable must be setted in the target_variable property." }, { "code": null, "e": 12660, "s": 11942, "text": "from pyFTS.models.multivariate import common, variable, mvftsfrom pyFTS.models.seasonal import partitioner as seasonalfrom pyFTS.models.seasonal.common import DateTimesp = {'seasonality': DateTime.day_of_year , 'names': ['Jan','Feb','Mar','Apr','May','Jun','Jul', 'Aug','Sep','Oct','Nov','Dec']}month = variable.Variable(\"Month\", data_label=\"data\", partitioner=seasonal.TimeGridPartitioner, npart=12,data=train_mv, partitioner_specific=sp)radiation = variable.Variable(\"Radiation\", data_label=\"glo_avg\", alias='rad',partitioner=Grid.GridPartitioner, npart=35, data=train_mv)model = mvfts.MultivariateFTS()model.append_variable(month)model.append_variable(radiation)model.target_variable = radiationmodel.fit(train_mv)" }, { "code": null, "e": 12858, "s": 12660, "text": "Besides our endogenous variable ‘glo_avg’, we will use only the ‘date’ column and extract two exogenous variables from it: the month and the hour. The partitioning of the variables is showed below:" }, { "code": null, "e": 13185, "s": 12858, "text": "You may be asking yourself: Why are the sets of hours and months overlapping? After all, this is very accurate information! Answer: That is fuzzy logic guys! We assume that neighbors things influence each other and have similar behaviors, hence the rules of a specific time are also influenced by neighboring hours and months." }, { "code": null, "e": 13284, "s": 13185, "text": "Let’s now take a look at the multivariate methods and see examples of the rules generated by them:" }, { "code": null, "e": 13350, "s": 13284, "text": "mvfts.MultivariateFTS: Weightless first order method (order = 1);" }, { "code": null, "e": 13429, "s": 13350, "text": "Jan,8hs,VL0 → VL1,VL2,VL3,VL4,VL5Jan,8hs,VL1 → VL1,VL2,VL3,VL4,VL5,L0,L1,L3,L4" }, { "code": null, "e": 13491, "s": 13429, "text": "wmvfts.WeightedMultivariatedFTS: Weighted first order method;" }, { "code": null, "e": 13708, "s": 13491, "text": "Jan,8hs,VL0 → VL2 (0.353), VL1 (0.253), VL4 (0.147), VL3 (0.207), VL5 (0.04)Jan,8hs,VL1 → VL2 (0.276), VL3 (0.172), VL1 (0.198), VL5 (0.083), VL4 (0.151), VL6 (0.021), L0 (0.036), L4 (0.005), L1 (0.036), L2 (0.021)" }, { "code": null, "e": 13761, "s": 13708, "text": "granular.GranularWMVFTS: Weighted high order method;" }, { "code": null, "e": 13841, "s": 13761, "text": "Jan11hsV3,Jan12hsL1 → Jan13hsVL6 (1.0)Jan12hsL1,Jan13hsVL6 → Jan15hsVL3 (1.0)" }, { "code": null, "e": 14203, "s": 13841, "text": "Obviously the main criterion for evaluating a predictive model is its accuracy. We will use the Root Mean Squared Error (RMSE) and the lower this value the better. But another important criterion is parsimony: simpler models will always be more desirable than complex models. So we aim to minimize RMSE and model size. Let’s see the five best-performing models:" }, { "code": null, "e": 14395, "s": 14203, "text": "It was expected that the multivariate models performed better then the univariate ones, after all, they had more information to exploit. But see that the most parsimonious model is the PWFTS!" }, { "code": null, "e": 14604, "s": 14395, "text": "The possibilities do not stop there. We could now decide to make an ensemble of the best models (models.ensemble), or use non-stationary fuzzy sets (models.nonstationary). But this is for another opportunity!" }, { "code": null, "e": 14946, "s": 14604, "text": "When we adopt an forecasting model we are also interested in predict not only the next value, but a sequence of these values. This is really cool because with just a few lags of information we can generate an estimate for many steps ahead! For the specific case of solar radiation forecasting we will set our prediction horizon for 48 hours." }, { "code": null, "e": 15159, "s": 14946, "text": "For an monovariate model on pyFTS this is very simple, just use the steps_ahead parameter of the predict function. This parameter will feed back the output values in the input, by the next steps_ahead iterations." }, { "code": null, "e": 15213, "s": 15159, "text": "forecasts = model.predict(input_data, steps_ahead=48)" }, { "code": null, "e": 15912, "s": 15213, "text": "For multivariate models this is a little bit tricky: we are not generating only the values of the endogenous variable but also the values of the exogenous variables. As this value generation depends on the nature of each variable, the predict function will require, in addition to the steps_ahead parameter, the generators parameter, which is a dictionary that must contain a key for each Pandas DataFrame column and whose values are lambda functions that receive the current value of the variable and return the next value. In our example this is quite simple since the values of the exogenous variables are datetime and to calculate the next value we just need to add one hour to the input value:" }, { "code": null, "e": 16083, "s": 15912, "text": "generator = lambda x : pd.to_datetime(x) + pd.to_timedelta(1, unit='h')forecasts = model.predict(input_data, steps_ahead=48, generators={'date': generator})" }, { "code": null, "e": 16385, "s": 16083, "text": "Now you have enough knowledge on FTS and the pyFTS library to employ them on your personal projects. Off course that still remains to talk about a lot of stuff! In the next tutorial we talk about interval and probabilistic forecasting, data transformations, non-stationary and incremental models, etc." } ]
Replace even nodes of a doubly linked list with the elements of array - GeeksforGeeks
03 Nov, 2021 Given a doubly linked list and an array with only odd values. Both are of equal size N. The task is replace all node which have even value with the Array elements from left to right. Examples: Input : List = 6 9 8 7 4 Arr[] = {3, 5, 23, 17, 1} Output : List = 3 9 5 7 23Input : List = 9 14 7 12 8 13 Arr[] = {5, 1, 17, 21, 11, 7} Output : List = 9 5 7 1 17 13 Approach: The idea is to traverse the nodes of the doubly linked list one by one and get the pointer of the nodes having even data then replace by the value of the array and increment the index of the array and move to the next node in the linked list.Below is the implementation of above approach: C++ Java Python3 C# Javascript // C++ implementation to create// odd doubly linked list#include <bits/stdc++.h>using namespace std; // Node of the doubly linked liststruct Node { int data; Node *prev, *next;}; // function to insert a node at the beginning// of the Doubly Linked Listvoid push(Node** head_ref, int new_data){ // allocate node Node* new_node = (Node*)malloc(sizeof(struct Node)); // put in the data new_node->data = new_data; // since we are adding at the beginning, // prev is always NULL new_node->prev = NULL; // link the old list off the new node new_node->next = (*head_ref); // change prev of head node to new node if ((*head_ref) != NULL) (*head_ref)->prev = new_node; // move the head to point to the new node (*head_ref) = new_node;} // function to make all node is oddvoid makeOddNode(Node** head_ref, int A[], int n){ Node* ptr = *head_ref; Node* next; int i = 0; // traves list till last node while (ptr != NULL) { next = ptr->next; // check if node is even then // replace it and increment in i if (ptr->data % 2 == 0) { ptr->data = A[i]; i++; } ptr = next; } // return sum of nodes which is divided by K}// function to print nodes in a// given doubly linked listvoid printList(Node* head){ while (head != NULL) { cout << head->data << " "; head = head->next; }} // Driver program to test aboveint main(){ // start with the empty list Node* head = NULL; // create the doubly linked list // 6 <=> 9 <=> 8 <=> 7 <=> 4 int Arr[] = { 3, 5, 23, 17, 1 }; push(&head, 4); push(&head, 7); push(&head, 8); push(&head, 9); push(&head, 6); int n = sizeof(Arr) / sizeof(Arr[0]); cout << "Original List: "; printList(head); cout << endl; makeOddNode(&head, Arr, n); cout << "New odd List: "; printList(head);} // Java implementation to create// odd doubly linked listclass GFG{ // Node of the doubly linked liststatic class Node{ int data; Node prev, next;}; // function to insert a node at the beginning// of the Doubly Linked Liststatic Node push(Node head_ref, int new_data){ // allocate node Node new_node = new Node(); // put in the data new_node.data = new_data; // since we are adding at the beginning, // prev is always null new_node.prev = null; // link the old list off the new node new_node.next = (head_ref); // change prev of head node to new node if ((head_ref) != null) (head_ref).prev = new_node; // move the head to point to the new node (head_ref) = new_node; return head_ref;} // function to make all node is oddstatic Node makeOddNode(Node head_ref, int A[], int n){ Node ptr = head_ref; Node next; int i = 0; // traves list till last node while (ptr != null) { next = ptr.next; // check if node is even then // replace it and increment in i if (ptr.data % 2 == 0) { ptr.data = A[i]; i++; } ptr = next; } // return sum of nodes which is divided by K return head_ref;} // function to print nodes in a// given doubly linked liststatic void printList(Node head){ while (head != null) { System.out.print( head.data + " "); head = head.next; }} // Driver codepublic static void main(String args[]){ // start with the empty list Node head = null; // create the doubly linked list // 6 <=> 9 <=> 8 <=> 7 <=> 4 int Arr[] = { 3, 5, 23, 17, 1 }; head = push(head, 4); head = push(head, 7); head = push(head, 8); head = push(head, 9); head = push(head, 6); int n = Arr.length; System.out.print( "Original List: "); printList(head); System.out.println(); head = makeOddNode(head, Arr, n); System.out.print("New odd List: "); printList(head);}} // This code is contributed by Arnab Kundu # Python3 implementation to# create odd doubly linked list # Node of the doubly linked listclass Node: def __init__(self, data): self.data = data self.prev = None self.next = None # Function to insert a node at the# beginning of the Doubly Linked Listdef push(head_ref, new_data): # allocate node new_node = Node(new_data) # link the old list off the new node new_node.next = head_ref # change prev of head node to new node if head_ref != None: head_ref.prev = new_node # move the head to point to the new node head_ref = new_node return head_ref # Function to make all node is odddef makeOddNode(head_ref, A, n): ptr = head_ref i = 0 # traves list till last node while ptr != None: next = ptr.next # check if node is even then # replace it and increment in i if ptr.data % 2 == 0: ptr.data = A[i] i += 1 ptr = next # return sum of nodes which is divided by K # Function to print nodes in a# given doubly linked listdef printList(head): while head != None: print(head.data, end = " ") head = head.next # Driver Codeif __name__ == "__main__": # start with the empty list head = None # create the doubly linked list # 6 <=> 9 <=> 8 <=> 7 <=> 4 Arr = [3, 5, 23, 17, 1] head = push(head, 4) head = push(head, 7) head = push(head, 8) head = push(head, 9) head = push(head, 6) n = len(Arr) print("Original List:", end = " ") printList(head) print() makeOddNode(head, Arr, n) print("New odd List:", end = " ") printList(head) # This code is contributed by Rituraj Jain // C# implementation to create// odd doubly linked listusing System; class GFG{ // Node of the doubly linked listpublic class Node{ public int data; public Node prev, next;}; // function to insert a node at the beginning// of the Doubly Linked Liststatic Node push(Node head_ref, int new_data){ // allocate node Node new_node = new Node(); // put in the data new_node.data = new_data; // since we are adding at the beginning, // prev is always null new_node.prev = null; // link the old list off the new node new_node.next = (head_ref); // change prev of head node to new node if ((head_ref) != null) (head_ref).prev = new_node; // move the head to point to the new node (head_ref) = new_node; return head_ref;} // function to make all node is oddstatic Node makeOddNode(Node head_ref, int []A, int n){ Node ptr = head_ref; Node next; int i = 0; // traves list till last node while (ptr != null) { next = ptr.next; // check if node is even then // replace it and increment in i if (ptr.data % 2 == 0) { ptr.data = A[i]; i++; } ptr = next; } // return sum of nodes which is divided by K return head_ref;} // function to print nodes in a// given doubly linked liststatic void printList(Node head){ while (head != null) { Console.Write( head.data + " "); head = head.next; }} // Driver codepublic static void Main(String []args){ // start with the empty list Node head = null; // create the doubly linked list // 6 <=> 9 <=> 8 <=> 7 <=> 4 int []Arr = { 3, 5, 23, 17, 1 }; head = push(head, 4); head = push(head, 7); head = push(head, 8); head = push(head, 9); head = push(head, 6); int n = Arr.Length; Console.WriteLine( "Original List: "); printList(head); Console.WriteLine(); head = makeOddNode(head, Arr, n); Console.WriteLine("New odd List: "); printList(head);}} // This code contributed by Rajput-Ji <script> // JavaScript implementation to create// odd doubly linked list// Node of the doubly linked listclass Node { constructor(val) { this.data = val; this.prev = null; this.next = null; }} // function to insert a node at the beginning // of the Doubly Linked List function push(head_ref , new_data) { // allocate node var new_node = new Node(); // put in the data new_node.data = new_data; // since we are adding at the beginning, // prev is always null new_node.prev = null; // link the old list off the new node new_node.next = (head_ref); // change prev of head node to new node if ((head_ref) != null) (head_ref).prev = new_node; // move the head to point to the new node (head_ref) = new_node; return head_ref; } // function to make all node is odd function makeOddNode(head_ref , A , n) { var ptr = head_ref; var next; var i = 0; // traves list till last node while (ptr != null) { next = ptr.next; // check if node is even then // replace it and increment in i if (ptr.data % 2 == 0) { ptr.data = A[i]; i++; } ptr = next; } // return sum of nodes which is divided by K return head_ref; } // function to print nodes in a // given doubly linked list function printList(head) { while (head != null) { document.write(head.data + " "); head = head.next; } } // Driver code // start with the empty list var head = null; // create the doubly linked list // 6 <=> 9 <=> 8 <=> 7 <=> 4 var Arr = [ 3, 5, 23, 17, 1 ]; head = push(head, 4); head = push(head, 7); head = push(head, 8); head = push(head, 9); head = push(head, 6); var n = Arr.length; document.write("Original List: "); printList(head); document.write("<br/>"); head = makeOddNode(head, Arr, n); document.write("New odd List: "); printList(head); // This code contributed by umadevi9616 </script> Original List: 6 9 8 7 4 New odd List: 3 9 5 7 23 Time Complexity: O(N), where N is the total number of nodes. rituraj_jain andrew1234 Rajput-Ji nidhi_biet umadevi9616 sooda367 ankita_saini doubly linked list Technical Scripter 2018 Arrays Linked List Technical Scripter Linked List Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Window Sliding Technique Program to find sum of elements in a given array Reversal algorithm for array rotation Trapping Rain Water Find duplicates in O(n) time and O(1) extra space | Set 1 Linked List | Set 1 (Introduction) Linked List | Set 2 (Inserting a node) Reverse a linked list Linked List | Set 3 (Deleting a node) LinkedList in Java
[ { "code": null, "e": 24740, "s": 24712, "text": "\n03 Nov, 2021" }, { "code": null, "e": 24924, "s": 24740, "text": "Given a doubly linked list and an array with only odd values. Both are of equal size N. The task is replace all node which have even value with the Array elements from left to right. " }, { "code": null, "e": 24935, "s": 24924, "text": "Examples: " }, { "code": null, "e": 25102, "s": 24935, "text": "Input : List = 6 9 8 7 4 Arr[] = {3, 5, 23, 17, 1} Output : List = 3 9 5 7 23Input : List = 9 14 7 12 8 13 Arr[] = {5, 1, 17, 21, 11, 7} Output : List = 9 5 7 1 17 13" }, { "code": null, "e": 25404, "s": 25104, "text": "Approach: The idea is to traverse the nodes of the doubly linked list one by one and get the pointer of the nodes having even data then replace by the value of the array and increment the index of the array and move to the next node in the linked list.Below is the implementation of above approach: " }, { "code": null, "e": 25408, "s": 25404, "text": "C++" }, { "code": null, "e": 25413, "s": 25408, "text": "Java" }, { "code": null, "e": 25421, "s": 25413, "text": "Python3" }, { "code": null, "e": 25424, "s": 25421, "text": "C#" }, { "code": null, "e": 25435, "s": 25424, "text": "Javascript" }, { "code": "// C++ implementation to create// odd doubly linked list#include <bits/stdc++.h>using namespace std; // Node of the doubly linked liststruct Node { int data; Node *prev, *next;}; // function to insert a node at the beginning// of the Doubly Linked Listvoid push(Node** head_ref, int new_data){ // allocate node Node* new_node = (Node*)malloc(sizeof(struct Node)); // put in the data new_node->data = new_data; // since we are adding at the beginning, // prev is always NULL new_node->prev = NULL; // link the old list off the new node new_node->next = (*head_ref); // change prev of head node to new node if ((*head_ref) != NULL) (*head_ref)->prev = new_node; // move the head to point to the new node (*head_ref) = new_node;} // function to make all node is oddvoid makeOddNode(Node** head_ref, int A[], int n){ Node* ptr = *head_ref; Node* next; int i = 0; // traves list till last node while (ptr != NULL) { next = ptr->next; // check if node is even then // replace it and increment in i if (ptr->data % 2 == 0) { ptr->data = A[i]; i++; } ptr = next; } // return sum of nodes which is divided by K}// function to print nodes in a// given doubly linked listvoid printList(Node* head){ while (head != NULL) { cout << head->data << \" \"; head = head->next; }} // Driver program to test aboveint main(){ // start with the empty list Node* head = NULL; // create the doubly linked list // 6 <=> 9 <=> 8 <=> 7 <=> 4 int Arr[] = { 3, 5, 23, 17, 1 }; push(&head, 4); push(&head, 7); push(&head, 8); push(&head, 9); push(&head, 6); int n = sizeof(Arr) / sizeof(Arr[0]); cout << \"Original List: \"; printList(head); cout << endl; makeOddNode(&head, Arr, n); cout << \"New odd List: \"; printList(head);}", "e": 27343, "s": 25435, "text": null }, { "code": "// Java implementation to create// odd doubly linked listclass GFG{ // Node of the doubly linked liststatic class Node{ int data; Node prev, next;}; // function to insert a node at the beginning// of the Doubly Linked Liststatic Node push(Node head_ref, int new_data){ // allocate node Node new_node = new Node(); // put in the data new_node.data = new_data; // since we are adding at the beginning, // prev is always null new_node.prev = null; // link the old list off the new node new_node.next = (head_ref); // change prev of head node to new node if ((head_ref) != null) (head_ref).prev = new_node; // move the head to point to the new node (head_ref) = new_node; return head_ref;} // function to make all node is oddstatic Node makeOddNode(Node head_ref, int A[], int n){ Node ptr = head_ref; Node next; int i = 0; // traves list till last node while (ptr != null) { next = ptr.next; // check if node is even then // replace it and increment in i if (ptr.data % 2 == 0) { ptr.data = A[i]; i++; } ptr = next; } // return sum of nodes which is divided by K return head_ref;} // function to print nodes in a// given doubly linked liststatic void printList(Node head){ while (head != null) { System.out.print( head.data + \" \"); head = head.next; }} // Driver codepublic static void main(String args[]){ // start with the empty list Node head = null; // create the doubly linked list // 6 <=> 9 <=> 8 <=> 7 <=> 4 int Arr[] = { 3, 5, 23, 17, 1 }; head = push(head, 4); head = push(head, 7); head = push(head, 8); head = push(head, 9); head = push(head, 6); int n = Arr.length; System.out.print( \"Original List: \"); printList(head); System.out.println(); head = makeOddNode(head, Arr, n); System.out.print(\"New odd List: \"); printList(head);}} // This code is contributed by Arnab Kundu", "e": 29376, "s": 27343, "text": null }, { "code": "# Python3 implementation to# create odd doubly linked list # Node of the doubly linked listclass Node: def __init__(self, data): self.data = data self.prev = None self.next = None # Function to insert a node at the# beginning of the Doubly Linked Listdef push(head_ref, new_data): # allocate node new_node = Node(new_data) # link the old list off the new node new_node.next = head_ref # change prev of head node to new node if head_ref != None: head_ref.prev = new_node # move the head to point to the new node head_ref = new_node return head_ref # Function to make all node is odddef makeOddNode(head_ref, A, n): ptr = head_ref i = 0 # traves list till last node while ptr != None: next = ptr.next # check if node is even then # replace it and increment in i if ptr.data % 2 == 0: ptr.data = A[i] i += 1 ptr = next # return sum of nodes which is divided by K # Function to print nodes in a# given doubly linked listdef printList(head): while head != None: print(head.data, end = \" \") head = head.next # Driver Codeif __name__ == \"__main__\": # start with the empty list head = None # create the doubly linked list # 6 <=> 9 <=> 8 <=> 7 <=> 4 Arr = [3, 5, 23, 17, 1] head = push(head, 4) head = push(head, 7) head = push(head, 8) head = push(head, 9) head = push(head, 6) n = len(Arr) print(\"Original List:\", end = \" \") printList(head) print() makeOddNode(head, Arr, n) print(\"New odd List:\", end = \" \") printList(head) # This code is contributed by Rituraj Jain", "e": 31096, "s": 29376, "text": null }, { "code": "// C# implementation to create// odd doubly linked listusing System; class GFG{ // Node of the doubly linked listpublic class Node{ public int data; public Node prev, next;}; // function to insert a node at the beginning// of the Doubly Linked Liststatic Node push(Node head_ref, int new_data){ // allocate node Node new_node = new Node(); // put in the data new_node.data = new_data; // since we are adding at the beginning, // prev is always null new_node.prev = null; // link the old list off the new node new_node.next = (head_ref); // change prev of head node to new node if ((head_ref) != null) (head_ref).prev = new_node; // move the head to point to the new node (head_ref) = new_node; return head_ref;} // function to make all node is oddstatic Node makeOddNode(Node head_ref, int []A, int n){ Node ptr = head_ref; Node next; int i = 0; // traves list till last node while (ptr != null) { next = ptr.next; // check if node is even then // replace it and increment in i if (ptr.data % 2 == 0) { ptr.data = A[i]; i++; } ptr = next; } // return sum of nodes which is divided by K return head_ref;} // function to print nodes in a// given doubly linked liststatic void printList(Node head){ while (head != null) { Console.Write( head.data + \" \"); head = head.next; }} // Driver codepublic static void Main(String []args){ // start with the empty list Node head = null; // create the doubly linked list // 6 <=> 9 <=> 8 <=> 7 <=> 4 int []Arr = { 3, 5, 23, 17, 1 }; head = push(head, 4); head = push(head, 7); head = push(head, 8); head = push(head, 9); head = push(head, 6); int n = Arr.Length; Console.WriteLine( \"Original List: \"); printList(head); Console.WriteLine(); head = makeOddNode(head, Arr, n); Console.WriteLine(\"New odd List: \"); printList(head);}} // This code contributed by Rajput-Ji", "e": 33157, "s": 31096, "text": null }, { "code": "<script> // JavaScript implementation to create// odd doubly linked list// Node of the doubly linked listclass Node { constructor(val) { this.data = val; this.prev = null; this.next = null; }} // function to insert a node at the beginning // of the Doubly Linked List function push(head_ref , new_data) { // allocate node var new_node = new Node(); // put in the data new_node.data = new_data; // since we are adding at the beginning, // prev is always null new_node.prev = null; // link the old list off the new node new_node.next = (head_ref); // change prev of head node to new node if ((head_ref) != null) (head_ref).prev = new_node; // move the head to point to the new node (head_ref) = new_node; return head_ref; } // function to make all node is odd function makeOddNode(head_ref , A , n) { var ptr = head_ref; var next; var i = 0; // traves list till last node while (ptr != null) { next = ptr.next; // check if node is even then // replace it and increment in i if (ptr.data % 2 == 0) { ptr.data = A[i]; i++; } ptr = next; } // return sum of nodes which is divided by K return head_ref; } // function to print nodes in a // given doubly linked list function printList(head) { while (head != null) { document.write(head.data + \" \"); head = head.next; } } // Driver code // start with the empty list var head = null; // create the doubly linked list // 6 <=> 9 <=> 8 <=> 7 <=> 4 var Arr = [ 3, 5, 23, 17, 1 ]; head = push(head, 4); head = push(head, 7); head = push(head, 8); head = push(head, 9); head = push(head, 6); var n = Arr.length; document.write(\"Original List: \"); printList(head); document.write(\"<br/>\"); head = makeOddNode(head, Arr, n); document.write(\"New odd List: \"); printList(head); // This code contributed by umadevi9616 </script>", "e": 35413, "s": 33157, "text": null }, { "code": null, "e": 35464, "s": 35413, "text": "Original List: 6 9 8 7 4 \nNew odd List: 3 9 5 7 23" }, { "code": null, "e": 35528, "s": 35466, "text": "Time Complexity: O(N), where N is the total number of nodes. " }, { "code": null, "e": 35541, "s": 35528, "text": "rituraj_jain" }, { "code": null, "e": 35552, "s": 35541, "text": "andrew1234" }, { "code": null, "e": 35562, "s": 35552, "text": "Rajput-Ji" }, { "code": null, "e": 35573, "s": 35562, "text": "nidhi_biet" }, { "code": null, "e": 35585, "s": 35573, "text": "umadevi9616" }, { "code": null, "e": 35594, "s": 35585, "text": "sooda367" }, { "code": null, "e": 35607, "s": 35594, "text": "ankita_saini" }, { "code": null, "e": 35626, "s": 35607, "text": "doubly linked list" }, { "code": null, "e": 35650, "s": 35626, "text": "Technical Scripter 2018" }, { "code": null, "e": 35657, "s": 35650, "text": "Arrays" }, { "code": null, "e": 35669, "s": 35657, "text": "Linked List" }, { "code": null, "e": 35688, "s": 35669, "text": "Technical Scripter" }, { "code": null, "e": 35700, "s": 35688, "text": "Linked List" }, { "code": null, "e": 35707, "s": 35700, "text": "Arrays" }, { "code": null, "e": 35805, "s": 35707, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35814, "s": 35805, "text": "Comments" }, { "code": null, "e": 35827, "s": 35814, "text": "Old Comments" }, { "code": null, "e": 35852, "s": 35827, "text": "Window Sliding Technique" }, { "code": null, "e": 35901, "s": 35852, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 35939, "s": 35901, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 35959, "s": 35939, "text": "Trapping Rain Water" }, { "code": null, "e": 36017, "s": 35959, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 36052, "s": 36017, "text": "Linked List | Set 1 (Introduction)" }, { "code": null, "e": 36091, "s": 36052, "text": "Linked List | Set 2 (Inserting a node)" }, { "code": null, "e": 36113, "s": 36091, "text": "Reverse a linked list" }, { "code": null, "e": 36151, "s": 36113, "text": "Linked List | Set 3 (Deleting a node)" } ]
How to fetch data from a local JSON file in React Native ? - GeeksforGeeks
01 Sep, 2021 Fetching JSON (JavaScript Object Notation) data in React Native from Local (E.g. IOS/Android storage) is different from fetching JSON data from a server (using Fetch or Axios). It requires Storage permission for APP and a Library to provide Native filesystem access. Implementation: Now let’s start with the implementation: Step 1: Open your terminal and install expo-cli by the following command.npm install -g expo-cli Step 1: Open your terminal and install expo-cli by the following command. npm install -g expo-cli Step 2: Now create a project by the following command.expo init jsonDemo Step 2: Now create a project by the following command. expo init jsonDemo Step 3: Now go into your project folder i.e. jsonDemocd jsonDemo Step 3: Now go into your project folder i.e. jsonDemo cd jsonDemo Project Structure: It will look like the following. Directory Structure Example: Fetching data from a local JSON file in React Native. Step 1: Install react-native-fs using the following command: npm install react-native-fs Note: If you are getting errors like Attempt to get length of null array EUNSPECIFIED then in the android manifest file add the following code. XML <manifest ...> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <application android:requestLegacyExternalStorage="true" ...> ... </application></manifest> Step 2: Create a JSON file named data.json and place it in android’s “/storage/emulated/0/” directory which is default ExternalStorageDirectoryPath of android. You can also change the location of the JSON file but make sure to store its path which will be required when reading the file. All possible Directories that can be accessed are mentioned in react-native-fs documentation. { "type":"Fruits", "example":[ {"name":"banana"}, {"name":"apple"}, {"name":"orange"}, {"name":"mango"}, {"name":"grape"} ] } Step 3: In the App.js file, we will import react-native-fs and call a function named readFile which accepts file path and encoding as parameters and returns the file content. Inside “/storage/emulated/0/” I have created a folder named DATA and inside is the JSON file. Example: App.js import { mapValuesSeries } from 'async';import React, { Component } from 'react';import { Text, View, Button } from 'react-native';import * as RNFS from 'react-native-fs'; export class App extends Component { constructor(props) { super(props); this.state = { content: null, fruitType: null, }; } readFile = () => { RNFS.readFile('/storage/emulated/0/DATA/data.json', 'ascii') .then((res) => { console.log(res); const d = JSON.parse(res); this.setState({ content: res, fruitType: d.type }); }) .catch((err) => { console.log(err.message, err.code); }); }; render() { return ( <View style={{ alignItems: 'center' }}> <View style={{ marginVertical: '15%' }}> <Button title="READ" onPress={() => this.readFile()} /> </View> <Text> {this.state.content} </Text> <Text style={{ marginVertical: '5%', fontSize: 20, color: 'green', fontWeight: 'bold', }}> TYPE ={' '} {this.state.fruitType === null ? 'Press READ to get the type' : this.state.fruitType} </Text> </View> ); }} export default App; Start the server by using the following command. npx react-native run-android Output: To get the Directory (e.g. ExternalStorageDirectory) files paths we will use the function readDir which accepts directory (for all available directory types refer to the documentation of react-native-fs) type as a parameter and returns an array of objects containing file paths and information. App.js import { mapValuesSeries } from 'async';import React, { Component } from 'react';import { Text, View, Button } from 'react-native';import * as RNFS from 'react-native-fs'; export class App extends Component { constructor(props) { super(props); this.state = { content: null, fruitType: null, }; } readFile = () => { // On Android, use "RNFS.DocumentDirectoryPath" // (MainBundlePath is not defined) RNFS.readDir(RNFS.ExternalStorageDirectoryPath) .then((result) => { for (let i = 0; i < result.length; i++) { // Print the result console.log('GOT RESULT', result[i]); } // Stat the first file return Promise.all([RNFS.stat(result[0].path), result[0].path]); }) .then((statResult) => { if (statResult[0].isFile()) { // If we have a file, read it return RNFS.readFile(statResult[1], 'utf8'); } return 'no file'; }) .then((contents) => { // Print the file contents console.log(contents); }) .catch((err) => { console.log(err.message, err.code); }); }; render() { return ( <View style={{ alignItems: 'center' }}> <Text>Text</Text> </View> ); }} export default App; Reference: https://github.com/itinance/react-native-fs JSON Picked React-Native JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request Angular File Upload How to get selected value in dropdown list using JavaScript ? How to remove duplicate elements from JavaScript Array ? Express.js express.Router() Function Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 24909, "s": 24881, "text": "\n01 Sep, 2021" }, { "code": null, "e": 25176, "s": 24909, "text": "Fetching JSON (JavaScript Object Notation) data in React Native from Local (E.g. IOS/Android storage) is different from fetching JSON data from a server (using Fetch or Axios). It requires Storage permission for APP and a Library to provide Native filesystem access." }, { "code": null, "e": 25233, "s": 25176, "text": "Implementation: Now let’s start with the implementation:" }, { "code": null, "e": 25330, "s": 25233, "text": "Step 1: Open your terminal and install expo-cli by the following command.npm install -g expo-cli" }, { "code": null, "e": 25404, "s": 25330, "text": "Step 1: Open your terminal and install expo-cli by the following command." }, { "code": null, "e": 25428, "s": 25404, "text": "npm install -g expo-cli" }, { "code": null, "e": 25502, "s": 25428, "text": "Step 2: Now create a project by the following command.expo init jsonDemo " }, { "code": null, "e": 25557, "s": 25502, "text": "Step 2: Now create a project by the following command." }, { "code": null, "e": 25576, "s": 25557, "text": "expo init jsonDemo" }, { "code": null, "e": 25643, "s": 25578, "text": "Step 3: Now go into your project folder i.e. jsonDemocd jsonDemo" }, { "code": null, "e": 25697, "s": 25643, "text": "Step 3: Now go into your project folder i.e. jsonDemo" }, { "code": null, "e": 25709, "s": 25697, "text": "cd jsonDemo" }, { "code": null, "e": 25761, "s": 25709, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 25781, "s": 25761, "text": "Directory Structure" }, { "code": null, "e": 25844, "s": 25781, "text": "Example: Fetching data from a local JSON file in React Native." }, { "code": null, "e": 25905, "s": 25844, "text": "Step 1: Install react-native-fs using the following command:" }, { "code": null, "e": 25933, "s": 25905, "text": "npm install react-native-fs" }, { "code": null, "e": 26077, "s": 25933, "text": "Note: If you are getting errors like Attempt to get length of null array EUNSPECIFIED then in the android manifest file add the following code." }, { "code": null, "e": 26081, "s": 26077, "text": "XML" }, { "code": "<manifest ...> <uses-permission android:name=\"android.permission.READ_EXTERNAL_STORAGE\" /> <uses-permission android:name=\"android.permission.WRITE_EXTERNAL_STORAGE\" /> <application android:requestLegacyExternalStorage=\"true\" ...> ... </application></manifest>", "e": 26368, "s": 26081, "text": null }, { "code": null, "e": 26656, "s": 26368, "text": "Step 2: Create a JSON file named data.json and place it in android’s “/storage/emulated/0/” directory which is default ExternalStorageDirectoryPath of android. You can also change the location of the JSON file but make sure to store its path which will be required when reading the file." }, { "code": null, "e": 26750, "s": 26656, "text": "All possible Directories that can be accessed are mentioned in react-native-fs documentation." }, { "code": null, "e": 26920, "s": 26750, "text": "{\n \"type\":\"Fruits\",\n \"example\":[\n {\"name\":\"banana\"},\n {\"name\":\"apple\"},\n {\"name\":\"orange\"},\n {\"name\":\"mango\"},\n {\"name\":\"grape\"}\n ]\n}" }, { "code": null, "e": 27189, "s": 26920, "text": "Step 3: In the App.js file, we will import react-native-fs and call a function named readFile which accepts file path and encoding as parameters and returns the file content. Inside “/storage/emulated/0/” I have created a folder named DATA and inside is the JSON file." }, { "code": null, "e": 27198, "s": 27189, "text": "Example:" }, { "code": null, "e": 27205, "s": 27198, "text": "App.js" }, { "code": "import { mapValuesSeries } from 'async';import React, { Component } from 'react';import { Text, View, Button } from 'react-native';import * as RNFS from 'react-native-fs'; export class App extends Component { constructor(props) { super(props); this.state = { content: null, fruitType: null, }; } readFile = () => { RNFS.readFile('/storage/emulated/0/DATA/data.json', 'ascii') .then((res) => { console.log(res); const d = JSON.parse(res); this.setState({ content: res, fruitType: d.type }); }) .catch((err) => { console.log(err.message, err.code); }); }; render() { return ( <View style={{ alignItems: 'center' }}> <View style={{ marginVertical: '15%' }}> <Button title=\"READ\" onPress={() => this.readFile()} /> </View> <Text> {this.state.content} </Text> <Text style={{ marginVertical: '5%', fontSize: 20, color: 'green', fontWeight: 'bold', }}> TYPE ={' '} {this.state.fruitType === null ? 'Press READ to get the type' : this.state.fruitType} </Text> </View> ); }} export default App;", "e": 28423, "s": 27205, "text": null }, { "code": null, "e": 28472, "s": 28423, "text": "Start the server by using the following command." }, { "code": null, "e": 28501, "s": 28472, "text": "npx react-native run-android" }, { "code": null, "e": 28509, "s": 28501, "text": "Output:" }, { "code": null, "e": 28804, "s": 28509, "text": "To get the Directory (e.g. ExternalStorageDirectory) files paths we will use the function readDir which accepts directory (for all available directory types refer to the documentation of react-native-fs) type as a parameter and returns an array of objects containing file paths and information." }, { "code": null, "e": 28811, "s": 28804, "text": "App.js" }, { "code": "import { mapValuesSeries } from 'async';import React, { Component } from 'react';import { Text, View, Button } from 'react-native';import * as RNFS from 'react-native-fs'; export class App extends Component { constructor(props) { super(props); this.state = { content: null, fruitType: null, }; } readFile = () => { // On Android, use \"RNFS.DocumentDirectoryPath\" // (MainBundlePath is not defined) RNFS.readDir(RNFS.ExternalStorageDirectoryPath) .then((result) => { for (let i = 0; i < result.length; i++) { // Print the result console.log('GOT RESULT', result[i]); } // Stat the first file return Promise.all([RNFS.stat(result[0].path), result[0].path]); }) .then((statResult) => { if (statResult[0].isFile()) { // If we have a file, read it return RNFS.readFile(statResult[1], 'utf8'); } return 'no file'; }) .then((contents) => { // Print the file contents console.log(contents); }) .catch((err) => { console.log(err.message, err.code); }); }; render() { return ( <View style={{ alignItems: 'center' }}> <Text>Text</Text> </View> ); }} export default App;", "e": 30089, "s": 28811, "text": null }, { "code": null, "e": 30145, "s": 30089, "text": "Reference: https://github.com/itinance/react-native-fs " }, { "code": null, "e": 30150, "s": 30145, "text": "JSON" }, { "code": null, "e": 30157, "s": 30150, "text": "Picked" }, { "code": null, "e": 30170, "s": 30157, "text": "React-Native" }, { "code": null, "e": 30181, "s": 30170, "text": "JavaScript" }, { "code": null, "e": 30198, "s": 30181, "text": "Web Technologies" }, { "code": null, "e": 30296, "s": 30198, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30305, "s": 30296, "text": "Comments" }, { "code": null, "e": 30318, "s": 30305, "text": "Old Comments" }, { "code": null, "e": 30379, "s": 30318, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 30420, "s": 30379, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 30440, "s": 30420, "text": "Angular File Upload" }, { "code": null, "e": 30502, "s": 30440, "text": "How to get selected value in dropdown list using JavaScript ?" }, { "code": null, "e": 30559, "s": 30502, "text": "How to remove duplicate elements from JavaScript Array ?" }, { "code": null, "e": 30596, "s": 30559, "text": "Express.js express.Router() Function" }, { "code": null, "e": 30629, "s": 30596, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30691, "s": 30629, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 30734, "s": 30691, "text": "How to fetch data from an API in ReactJS ?" } ]
Sort list elements in descending order in C#
The following is our list with elements − IList<Employee> emp = new List<Employee>() { new Employee() { EmployeeRank = 4, EmpName = "Amit", EmpMarks = 90 } , new Employee() { EmployeeRank = 05, EmpName = "Raman", EmpMarks = 95 } }; Now use orderby and descending to sort elements in descending order. var res = from str in emp orderby str.EmpName descending select str; Live Demo using System; using System.Linq; using System.Collections.Generic; public class Demo { public static void Main() { IList<Employee> emp = new List<Employee>() { new Employee() { EmployeeRank = 4, EmpName = "Amit", EmpMarks = 90 } , new Employee() { EmployeeRank = 05, EmpName = "Raman", EmpMarks = 95 } }; var res = from str in emp orderby str.EmpName descending select str; Console.WriteLine("Student List (Descending Order):"); foreach (var list in res) Console.WriteLine(list.EmpName); } } public class Employee { public int EmployeeRank { get; set; } public string EmpName { get; set; } public int EmpMarks { get; set; } } Student List (Descending Order): Raman Amit
[ { "code": null, "e": 1104, "s": 1062, "text": "The following is our list with elements −" }, { "code": null, "e": 1300, "s": 1104, "text": "IList<Employee> emp = new List<Employee>() {\n new Employee() { EmployeeRank = 4, EmpName = \"Amit\", EmpMarks = 90 } ,\n new Employee() { EmployeeRank = 05, EmpName = \"Raman\", EmpMarks = 95 }\n};" }, { "code": null, "e": 1369, "s": 1300, "text": "Now use orderby and descending to sort elements in descending order." }, { "code": null, "e": 1438, "s": 1369, "text": "var res = from str in emp orderby str.EmpName descending select str;" }, { "code": null, "e": 1449, "s": 1438, "text": " Live Demo" }, { "code": null, "e": 2145, "s": 1449, "text": "using System;\nusing System.Linq;\nusing System.Collections.Generic;\npublic class Demo {\n public static void Main() {\n IList<Employee> emp = new List<Employee>() {\n new Employee() { EmployeeRank = 4, EmpName = \"Amit\", EmpMarks = 90 } ,\n new Employee() { EmployeeRank = 05, EmpName = \"Raman\", EmpMarks = 95 }\n };\n var res = from str in emp orderby str.EmpName descending select str;\n Console.WriteLine(\"Student List (Descending Order):\");\n foreach (var list in res)\n Console.WriteLine(list.EmpName);\n }\n}\n\npublic class Employee {\n public int EmployeeRank { get; set; }\n public string EmpName { get; set; }\n public int EmpMarks { get; set; }\n}" }, { "code": null, "e": 2189, "s": 2145, "text": "Student List (Descending Order):\nRaman\nAmit" } ]
Create a Pie Chart using Recharts in ReactJS - GeeksforGeeks
27 Jul, 2021 Introduction: Rechart JS is a library that is used for creating charts for React JS. This library is used for building Line charts, Bar charts, Pie charts, etc, with the help of React and D3 (Data-Driven Documents). To create Pie Chart using Recharts, we create a dataset which contains actual data. Then we define the slices using pie element with data property which will have the data of the dataset created and with datakey property which is the property name with a value for the slices. Creating React Application And Installing Module: Step 1: Create a React application using the following command.npx create-react-app foldername Step 1: Create a React application using the following command. npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command.cd foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command. cd foldername Step 3: After creating the ReactJS application, Install the required modules using the following command.npm install --save recharts Step 3: After creating the ReactJS application, Install the required modules using the following command. npm install --save recharts Project Structure: It will look like the following. Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. App.js import React from 'react';import { PieChart, Pie} from 'recharts'; const App = () => { // Sample dataconst data = [ {name: 'Geeksforgeeks', students: 400}, {name: 'Technical scripter', students: 700}, {name: 'Geek-i-knack', students: 200}, {name: 'Geek-o-mania', students: 1000}]; return ( <PieChart width={700} height={700}> <Pie data={data} dataKey="students" outerRadius={250} fill="green" /> </PieChart>);} export default App; Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Output React-Questions Recharts JavaScript ReactJS 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 Difference Between PUT and PATCH Request Remove elements from a JavaScript Array How to get character array from string in JavaScript? How to filter object array based on attributes? How to fetch data from an API in ReactJS ? How to redirect to another page in ReactJS ? How to pass data from child component to its parent in ReactJS ? How to pass data from one component to other component in ReactJS ? ReactJS Functional Components
[ { "code": null, "e": 25312, "s": 25284, "text": "\n27 Jul, 2021" }, { "code": null, "e": 25530, "s": 25312, "text": "Introduction: Rechart JS is a library that is used for creating charts for React JS. This library is used for building Line charts, Bar charts, Pie charts, etc, with the help of React and D3 (Data-Driven Documents). " }, { "code": null, "e": 25807, "s": 25530, "text": "To create Pie Chart using Recharts, we create a dataset which contains actual data. Then we define the slices using pie element with data property which will have the data of the dataset created and with datakey property which is the property name with a value for the slices." }, { "code": null, "e": 25857, "s": 25807, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 25952, "s": 25857, "text": "Step 1: Create a React application using the following command.npx create-react-app foldername" }, { "code": null, "e": 26016, "s": 25952, "text": "Step 1: Create a React application using the following command." }, { "code": null, "e": 26048, "s": 26016, "text": "npx create-react-app foldername" }, { "code": null, "e": 26161, "s": 26048, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command.cd foldername" }, { "code": null, "e": 26261, "s": 26161, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command." }, { "code": null, "e": 26275, "s": 26261, "text": "cd foldername" }, { "code": null, "e": 26408, "s": 26275, "text": "Step 3: After creating the ReactJS application, Install the required modules using the following command.npm install --save recharts" }, { "code": null, "e": 26514, "s": 26408, "text": "Step 3: After creating the ReactJS application, Install the required modules using the following command." }, { "code": null, "e": 26542, "s": 26514, "text": "npm install --save recharts" }, { "code": null, "e": 26594, "s": 26542, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 26724, "s": 26594, "text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 26731, "s": 26724, "text": "App.js" }, { "code": "import React from 'react';import { PieChart, Pie} from 'recharts'; const App = () => { // Sample dataconst data = [ {name: 'Geeksforgeeks', students: 400}, {name: 'Technical scripter', students: 700}, {name: 'Geek-i-knack', students: 200}, {name: 'Geek-o-mania', students: 1000}]; return ( <PieChart width={700} height={700}> <Pie data={data} dataKey=\"students\" outerRadius={250} fill=\"green\" /> </PieChart>);} export default App;", "e": 27197, "s": 26731, "text": null }, { "code": null, "e": 27310, "s": 27197, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 27320, "s": 27310, "text": "npm start" }, { "code": null, "e": 27419, "s": 27320, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 27426, "s": 27419, "text": "Output" }, { "code": null, "e": 27442, "s": 27426, "text": "React-Questions" }, { "code": null, "e": 27451, "s": 27442, "text": "Recharts" }, { "code": null, "e": 27462, "s": 27451, "text": "JavaScript" }, { "code": null, "e": 27470, "s": 27462, "text": "ReactJS" }, { "code": null, "e": 27487, "s": 27470, "text": "Web Technologies" }, { "code": null, "e": 27585, "s": 27487, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27646, "s": 27585, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27687, "s": 27646, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 27727, "s": 27687, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27781, "s": 27727, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 27829, "s": 27781, "text": "How to filter object array based on attributes?" }, { "code": null, "e": 27872, "s": 27829, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27917, "s": 27872, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 27982, "s": 27917, "text": "How to pass data from child component to its parent in ReactJS ?" }, { "code": null, "e": 28050, "s": 27982, "text": "How to pass data from one component to other component in ReactJS ?" } ]
VB.Net - Nested Loops
VB.Net allows using one loop inside another loop. Following section shows few examples to illustrate the concept. The syntax for a nested For loop statement in VB.Net is as follows − For counter1 [ As datatype1 ] = start1 To end1 [ Step step1 ] For counter2 [ As datatype2 ] = start2 To end2 [ Step step2 ] ... Next [ counter2 ] Next [ counter 1] The syntax for a nested While loop statement in VB.Net is as follows − While condition1 While condition2 ... End While End While The syntax for a nested Do...While loop statement in VB.Net is as follows − Do { While | Until } condition1 Do { While | Until } condition2 ... Loop Loop A final note on loop nesting is that you can put any type of loop inside of any other type of loop. For example, a for loop can be inside a while loop or vice versa. The following program uses a nested for loop to find the prime numbers from 2 to 100 − Module loops Sub Main() ' local variable definition Dim i, j As Integer For i = 2 To 100 For j = 2 To i ' if factor found, not prime If ((i Mod j) = 0) Then Exit For End If Next j If (j > (i \ j)) Then Console.WriteLine("{0} is prime", i) End If Next i Console.ReadLine() End Sub End Module When the above code is compiled and executed, it produces the following result − 2 is prime 3 is prime 5 is prime 7 is prime 11 is prime 13 is prime 17 is prime 19 is prime 23 is prime 29 is prime 31 is prime 37 is prime 41 is prime 43 is prime 47 is prime 53 is prime 59 is prime 61 is prime 67 is prime 71 is prime 73 is prime 79 is prime 83 is prime 89 is prime 97 is prime 63 Lectures 4 hours Frahaan Hussain 103 Lectures 12 hours Arnold Higuit 60 Lectures 9.5 hours Arnold Higuit 97 Lectures 9 hours Arnold Higuit Print Add Notes Bookmark this page
[ { "code": null, "e": 2414, "s": 2300, "text": "VB.Net allows using one loop inside another loop. Following section shows few examples to illustrate the concept." }, { "code": null, "e": 2484, "s": 2414, "text": "The syntax for a nested For loop statement in VB.Net is as follows −" }, { "code": null, "e": 2661, "s": 2484, "text": "For counter1 [ As datatype1 ] = start1 To end1 [ Step step1 ]\n For counter2 [ As datatype2 ] = start2 To end2 [ Step step2 ]\n ...\n Next [ counter2 ]\nNext [ counter 1]\n" }, { "code": null, "e": 2732, "s": 2661, "text": "The syntax for a nested While loop statement in VB.Net is as follows −" }, { "code": null, "e": 2803, "s": 2732, "text": "While condition1\n While condition2\n ...\n End While\nEnd While\n" }, { "code": null, "e": 2879, "s": 2803, "text": "The syntax for a nested Do...While loop statement in VB.Net is as follows −" }, { "code": null, "e": 2970, "s": 2879, "text": "Do { While | Until } condition1\n Do { While | Until } condition2\n ...\n Loop\nLoop\n" }, { "code": null, "e": 3136, "s": 2970, "text": "A final note on loop nesting is that you can put any type of loop inside of any other type of loop. For example, a for loop can be inside a while loop or vice versa." }, { "code": null, "e": 3223, "s": 3136, "text": "The following program uses a nested for loop to find the prime numbers from 2 to 100 −" }, { "code": null, "e": 3662, "s": 3223, "text": "Module loops\n Sub Main()\n ' local variable definition \n Dim i, j As Integer\n For i = 2 To 100\n For j = 2 To i\n ' if factor found, not prime\n If ((i Mod j) = 0) Then\n Exit For\n End If\n Next j\n If (j > (i \\ j)) Then\n Console.WriteLine(\"{0} is prime\", i)\n End If\n Next i\n Console.ReadLine()\n End Sub\nEnd Module" }, { "code": null, "e": 3743, "s": 3662, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 4040, "s": 3743, "text": "2 is prime\n3 is prime\n5 is prime\n7 is prime\n11 is prime\n13 is prime\n17 is prime\n19 is prime\n23 is prime\n29 is prime\n31 is prime\n37 is prime\n41 is prime\n43 is prime\n47 is prime\n53 is prime\n59 is prime\n61 is prime\n67 is prime\n71 is prime\n73 is prime\n79 is prime\n83 is prime\n89 is prime\n97 is prime\n" }, { "code": null, "e": 4073, "s": 4040, "text": "\n 63 Lectures \n 4 hours \n" }, { "code": null, "e": 4090, "s": 4073, "text": " Frahaan Hussain" }, { "code": null, "e": 4125, "s": 4090, "text": "\n 103 Lectures \n 12 hours \n" }, { "code": null, "e": 4140, "s": 4125, "text": " Arnold Higuit" }, { "code": null, "e": 4175, "s": 4140, "text": "\n 60 Lectures \n 9.5 hours \n" }, { "code": null, "e": 4190, "s": 4175, "text": " Arnold Higuit" }, { "code": null, "e": 4223, "s": 4190, "text": "\n 97 Lectures \n 9 hours \n" }, { "code": null, "e": 4238, "s": 4223, "text": " Arnold Higuit" }, { "code": null, "e": 4245, "s": 4238, "text": " Print" }, { "code": null, "e": 4256, "s": 4245, "text": " Add Notes" } ]
Software Design Complexity
The term complexity stands for state of events or things, which have multiple interconnected links and highly complicated structures. In software programming, as the design of software is realized, the number of elements and their interconnections gradually emerge to be huge, which becomes too difficult to understand at once. Software design complexity is difficult to assess without using complexity metrics and measures. Let us see three important software complexity measures. In 1977, Mr. Maurice Howard Halstead introduced metrics to measure software complexity. Halstead’s metrics depends upon the actual implementation of program and its measures, which are computed directly from the operators and operands from source code, in static manner. It allows to evaluate testing time, vocabulary, size, difficulty, errors, and efforts for C/C++/Java source code. According to Halstead, “A computer program is an implementation of an algorithm considered to be a collection of tokens which can be classified as either operators or operands”. Halstead metrics think a program as sequence of operators and their associated operands. He defines various indicators to check complexity of module. When we select source file to view its complexity details in Metric Viewer, the following result is seen in Metric Report: Every program encompasses statements to execute in order to perform some task and other decision-making statements that decide, what statements need to be executed. These decision-making constructs change the flow of the program. If we compare two programs of same size, the one with more decision-making statements will be more complex as the control of program jumps frequently. McCabe, in 1976, proposed Cyclomatic Complexity Measure to quantify complexity of a given software. It is graph driven model that is based on decision-making constructs of program such as if-else, do-while, repeat-until, switch-case and goto statements. Process to make flow control graph: Break program in smaller blocks, delimited by decision-making constructs. Create nodes representing each of these nodes. Connect nodes as follows: If control can branch from block i to block j Draw an arc If control can branch from block i to block j Draw an arc From exit node to entry node Draw an arc. From exit node to entry node Draw an arc. To calculate Cyclomatic complexity of a program module, we use the formula - V(G) = e – n + 2 Where e is total number of edges n is total number of nodes The Cyclomatic complexity of the above module is e = 10 n = 8 Cyclomatic Complexity = 10 - 8 + 2 = 4 According to P. Jorgensen, Cyclomatic Complexity of a module should not exceed 10. It is widely used to measure the size of software. Function Point concentrates on functionality provided by the system. Features and functionality of the system are used to measure the software complexity. Function point counts on five parameters, named as External Input, External Output, Logical Internal Files, External Interface Files, and External Inquiry. To consider the complexity of software each parameter is further categorized as simple, average or complex. Let us see parameters of function point: Every unique input to the system, from outside, is considered as external input. Uniqueness of input is measured, as no two inputs should have same formats. These inputs can either be data or control parameters. Simple - if input count is low and affects less internal files Simple - if input count is low and affects less internal files Complex - if input count is high and affects more internal files Complex - if input count is high and affects more internal files Average - in-between simple and complex. Average - in-between simple and complex. All output types provided by the system are counted in this category. Output is considered unique if their output format and/or processing are unique. Simple - if output count is low Simple - if output count is low Complex - if output count is high Complex - if output count is high Average - in between simple and complex. Average - in between simple and complex. Every software system maintains internal files in order to maintain its functional information and to function properly. These files hold logical data of the system. This logical data may contain both functional data and control data. Simple - if number of record types are low Simple - if number of record types are low Complex - if number of record types are high Complex - if number of record types are high Average - in between simple and complex. Average - in between simple and complex. Software system may need to share its files with some external software or it may need to pass the file for processing or as parameter to some function. All these files are counted as external interface files. Simple - if number of record types in shared file are low Simple - if number of record types in shared file are low Complex - if number of record types in shared file are high Complex - if number of record types in shared file are high Average - in between simple and complex. Average - in between simple and complex. An inquiry is a combination of input and output, where user sends some data to inquire about as input and the system responds to the user with the output of inquiry processed. The complexity of a query is more than External Input and External Output. Query is said to be unique if its input and output are unique in terms of format and data. Simple - if query needs low processing and yields small amount of output data Simple - if query needs low processing and yields small amount of output data Complex - if query needs high process and yields large amount of output data Complex - if query needs high process and yields large amount of output data Average - in between simple and complex. Average - in between simple and complex. Each of these parameters in the system is given weightage according to their class and complexity. The table below mentions the weightage given to each parameter: The table above yields raw Function Points. These function points are adjusted according to the environment complexity. System is described using fourteen different characteristics: Data communications Distributed processing Performance objectives Operation configuration load Transaction rate Online data entry, End user efficiency Online update Complex processing logic Re-usability Installation ease Operational ease Multiple sites Desire to facilitate changes These characteristics factors are then rated from 0 to 5, as mentioned below: No influence Incidental Moderate Average Significant Essential All ratings are then summed up as N. The value of N ranges from 0 to 70 (14 types of characteristics x 5 types of ratings). It is used to calculate Complexity Adjustment Factors (CAF), using the following formulae: CAF = 0.65 + 0.01N Then, Delivered Function Points (FP)= CAF x Raw FP This FP can then be used in various metrics, such as: Cost = $ / FP Quality = Errors / FP Productivity = FP / person-month 80 Lectures 7.5 hours Arnab Chakraborty 10 Lectures 1 hours Zach Miller 17 Lectures 1.5 hours Zach Miller 60 Lectures 5 hours John Shea 99 Lectures 10 hours Daniel IT 62 Lectures 5 hours GlobalETraining Print Add Notes Bookmark this page
[ { "code": null, "e": 2366, "s": 2037, "text": "The term complexity stands for state of events or things, which have multiple interconnected links and highly complicated structures. In software programming, as the design of software is realized, the number of elements and their interconnections gradually emerge to be huge, which becomes too difficult to understand at once." }, { "code": null, "e": 2521, "s": 2366, "text": "Software design complexity is difficult to assess without using complexity metrics and measures. Let us see three important software complexity measures." }, { "code": null, "e": 2907, "s": 2521, "text": "In 1977, Mr. Maurice Howard Halstead introduced metrics to measure software complexity. Halstead’s metrics depends upon the actual implementation of program and its measures, which are computed directly from the operators and operands from source code, in static manner. It allows to evaluate testing time, vocabulary, size, difficulty, errors, and efforts for C/C++/Java source code." }, { "code": null, "e": 3175, "s": 2907, "text": "According to Halstead, “A computer program is an implementation of an algorithm considered to be a collection of tokens which can be classified as either operators or operands”. Halstead metrics think a program as sequence of operators and their associated operands." }, { "code": null, "e": 3236, "s": 3175, "text": "He defines various indicators to check complexity of module." }, { "code": null, "e": 3359, "s": 3236, "text": "When we select source file to view its complexity details in Metric Viewer, the following result is seen in Metric Report:" }, { "code": null, "e": 3590, "s": 3359, "text": "Every program encompasses statements to execute in order to perform some task and other decision-making statements that decide, what statements need to be executed. These decision-making constructs change the flow of the program. " }, { "code": null, "e": 3741, "s": 3590, "text": "If we compare two programs of same size, the one with more decision-making statements will be more complex as the control of program jumps frequently." }, { "code": null, "e": 3996, "s": 3741, "text": "McCabe, in 1976, proposed Cyclomatic Complexity Measure to quantify complexity of a given software. It is graph driven model that is based on decision-making constructs of program such as if-else, do-while, repeat-until, switch-case and goto statements." }, { "code": null, "e": 4032, "s": 3996, "text": "Process to make flow control graph:" }, { "code": null, "e": 4106, "s": 4032, "text": "Break program in smaller blocks, delimited by decision-making constructs." }, { "code": null, "e": 4153, "s": 4106, "text": "Create nodes representing each of these nodes." }, { "code": null, "e": 4180, "s": 4153, "text": "Connect nodes as follows: " }, { "code": null, "e": 4238, "s": 4180, "text": "If control can branch from block i to block j\nDraw an arc" }, { "code": null, "e": 4284, "s": 4238, "text": "If control can branch from block i to block j" }, { "code": null, "e": 4296, "s": 4284, "text": "Draw an arc" }, { "code": null, "e": 4338, "s": 4296, "text": "From exit node to entry node\nDraw an arc." }, { "code": null, "e": 4367, "s": 4338, "text": "From exit node to entry node" }, { "code": null, "e": 4380, "s": 4367, "text": "Draw an arc." }, { "code": null, "e": 4457, "s": 4380, "text": "To calculate Cyclomatic complexity of a program module, we use the formula -" }, { "code": null, "e": 4535, "s": 4457, "text": "V(G) = e – n + 2\n\nWhere\ne is total number of edges\nn is total number of nodes" }, { "code": null, "e": 4584, "s": 4535, "text": "The Cyclomatic complexity of the above module is" }, { "code": null, "e": 4658, "s": 4584, "text": "e = 10\nn = 8\nCyclomatic Complexity = 10 - 8 + 2\n = 4" }, { "code": null, "e": 4741, "s": 4658, "text": "According to P. Jorgensen, Cyclomatic Complexity of a module should not exceed 10." }, { "code": null, "e": 4949, "s": 4741, "text": "It is widely used to measure the size of software. Function Point concentrates on functionality provided by the system. Features and functionality of the system are used to measure the software complexity." }, { "code": null, "e": 5216, "s": 4949, "text": "Function point counts on five parameters, named as External Input, External Output, Logical Internal Files, External Interface Files, and External Inquiry. To consider the complexity of software each parameter is further categorized as simple, average or complex. " }, { "code": null, "e": 5257, "s": 5216, "text": "Let us see parameters of function point:" }, { "code": null, "e": 5471, "s": 5257, "text": "Every unique input to the system, from outside, is considered as external input. Uniqueness of input is measured, as no two inputs should have same formats. These inputs can either be data or control parameters." }, { "code": null, "e": 5534, "s": 5471, "text": "Simple - if input count is low and affects less internal files" }, { "code": null, "e": 5597, "s": 5534, "text": "Simple - if input count is low and affects less internal files" }, { "code": null, "e": 5662, "s": 5597, "text": "Complex - if input count is high and affects more internal files" }, { "code": null, "e": 5727, "s": 5662, "text": "Complex - if input count is high and affects more internal files" }, { "code": null, "e": 5768, "s": 5727, "text": "Average - in-between simple and complex." }, { "code": null, "e": 5809, "s": 5768, "text": "Average - in-between simple and complex." }, { "code": null, "e": 5961, "s": 5809, "text": " All output types provided by the system are counted in this category. Output is considered unique if their output format and/or processing are unique." }, { "code": null, "e": 5993, "s": 5961, "text": "Simple - if output count is low" }, { "code": null, "e": 6025, "s": 5993, "text": "Simple - if output count is low" }, { "code": null, "e": 6059, "s": 6025, "text": "Complex - if output count is high" }, { "code": null, "e": 6093, "s": 6059, "text": "Complex - if output count is high" }, { "code": null, "e": 6134, "s": 6093, "text": "Average - in between simple and complex." }, { "code": null, "e": 6175, "s": 6134, "text": "Average - in between simple and complex." }, { "code": null, "e": 6412, "s": 6175, "text": " Every software system maintains internal files in order to maintain its functional information and to function properly. These files hold logical data of the system. This logical data may contain both functional data and control data." }, { "code": null, "e": 6455, "s": 6412, "text": "Simple - if number of record types are low" }, { "code": null, "e": 6498, "s": 6455, "text": "Simple - if number of record types are low" }, { "code": null, "e": 6543, "s": 6498, "text": "Complex - if number of record types are high" }, { "code": null, "e": 6588, "s": 6543, "text": "Complex - if number of record types are high" }, { "code": null, "e": 6629, "s": 6588, "text": "Average - in between simple and complex." }, { "code": null, "e": 6670, "s": 6629, "text": "Average - in between simple and complex." }, { "code": null, "e": 6881, "s": 6670, "text": " Software system may need to share its files with some external software or it may need to pass the file for processing or as parameter to some function. All these files are counted as external interface files." }, { "code": null, "e": 6939, "s": 6881, "text": "Simple - if number of record types in shared file are low" }, { "code": null, "e": 6997, "s": 6939, "text": "Simple - if number of record types in shared file are low" }, { "code": null, "e": 7057, "s": 6997, "text": "Complex - if number of record types in shared file are high" }, { "code": null, "e": 7117, "s": 7057, "text": "Complex - if number of record types in shared file are high" }, { "code": null, "e": 7158, "s": 7117, "text": "Average - in between simple and complex." }, { "code": null, "e": 7199, "s": 7158, "text": "Average - in between simple and complex." }, { "code": null, "e": 7544, "s": 7199, "text": " An inquiry is a combination of input and output, where user sends some data to inquire about as input and the system responds to the user with the output of inquiry processed. The complexity of a query is more than External Input and External Output. Query is said to be unique if its input and output are unique in terms of format and data." }, { "code": null, "e": 7622, "s": 7544, "text": "Simple - if query needs low processing and yields small amount of output data" }, { "code": null, "e": 7700, "s": 7622, "text": "Simple - if query needs low processing and yields small amount of output data" }, { "code": null, "e": 7777, "s": 7700, "text": "Complex - if query needs high process and yields large amount of output data" }, { "code": null, "e": 7854, "s": 7777, "text": "Complex - if query needs high process and yields large amount of output data" }, { "code": null, "e": 7895, "s": 7854, "text": "Average - in between simple and complex." }, { "code": null, "e": 7936, "s": 7895, "text": "Average - in between simple and complex." }, { "code": null, "e": 8100, "s": 7936, "text": "Each of these parameters in the system is given weightage according to their class and complexity. The table below mentions the weightage given to each parameter:" }, { "code": null, "e": 8284, "s": 8100, "text": "The table above yields raw Function Points. These function points are adjusted according to the environment complexity. System is described using fourteen different characteristics:" }, { "code": null, "e": 8304, "s": 8284, "text": "Data communications" }, { "code": null, "e": 8327, "s": 8304, "text": "Distributed processing" }, { "code": null, "e": 8350, "s": 8327, "text": "Performance objectives" }, { "code": null, "e": 8379, "s": 8350, "text": "Operation configuration load" }, { "code": null, "e": 8396, "s": 8379, "text": "Transaction rate" }, { "code": null, "e": 8415, "s": 8396, "text": "Online data entry," }, { "code": null, "e": 8435, "s": 8415, "text": "End user efficiency" }, { "code": null, "e": 8449, "s": 8435, "text": "Online update" }, { "code": null, "e": 8474, "s": 8449, "text": "Complex processing logic" }, { "code": null, "e": 8487, "s": 8474, "text": "Re-usability" }, { "code": null, "e": 8505, "s": 8487, "text": "Installation ease" }, { "code": null, "e": 8522, "s": 8505, "text": "Operational ease" }, { "code": null, "e": 8537, "s": 8522, "text": "Multiple sites" }, { "code": null, "e": 8566, "s": 8537, "text": "Desire to facilitate changes" }, { "code": null, "e": 8644, "s": 8566, "text": "These characteristics factors are then rated from 0 to 5, as mentioned below:" }, { "code": null, "e": 8657, "s": 8644, "text": "No influence" }, { "code": null, "e": 8668, "s": 8657, "text": "Incidental" }, { "code": null, "e": 8677, "s": 8668, "text": "Moderate" }, { "code": null, "e": 8685, "s": 8677, "text": "Average" }, { "code": null, "e": 8697, "s": 8685, "text": "Significant" }, { "code": null, "e": 8707, "s": 8697, "text": "Essential" }, { "code": null, "e": 8923, "s": 8707, "text": "All ratings are then summed up as N. The value of N ranges from 0 to 70 (14 types of characteristics x 5 types of ratings). It is used to calculate Complexity Adjustment Factors (CAF), using the following formulae:" }, { "code": null, "e": 8942, "s": 8923, "text": "CAF = 0.65 + 0.01N" }, { "code": null, "e": 8948, "s": 8942, "text": "Then," }, { "code": null, "e": 8993, "s": 8948, "text": "Delivered Function Points (FP)= CAF x Raw FP" }, { "code": null, "e": 9047, "s": 8993, "text": "This FP can then be used in various metrics, such as:" }, { "code": null, "e": 9061, "s": 9047, "text": "Cost = $ / FP" }, { "code": null, "e": 9083, "s": 9061, "text": "Quality = Errors / FP" }, { "code": null, "e": 9116, "s": 9083, "text": "Productivity = FP / person-month" }, { "code": null, "e": 9151, "s": 9116, "text": "\n 80 Lectures \n 7.5 hours \n" }, { "code": null, "e": 9170, "s": 9151, "text": " Arnab Chakraborty" }, { "code": null, "e": 9203, "s": 9170, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 9216, "s": 9203, "text": " Zach Miller" }, { "code": null, "e": 9251, "s": 9216, "text": "\n 17 Lectures \n 1.5 hours \n" }, { "code": null, "e": 9264, "s": 9251, "text": " Zach Miller" }, { "code": null, "e": 9297, "s": 9264, "text": "\n 60 Lectures \n 5 hours \n" }, { "code": null, "e": 9308, "s": 9297, "text": " John Shea" }, { "code": null, "e": 9342, "s": 9308, "text": "\n 99 Lectures \n 10 hours \n" }, { "code": null, "e": 9353, "s": 9342, "text": " Daniel IT" }, { "code": null, "e": 9386, "s": 9353, "text": "\n 62 Lectures \n 5 hours \n" }, { "code": null, "e": 9403, "s": 9386, "text": " GlobalETraining" }, { "code": null, "e": 9410, "s": 9403, "text": " Print" }, { "code": null, "e": 9421, "s": 9410, "text": " Add Notes" } ]
Get greatest repetitive item in array JavaScript
We have an array of Number / String literals that contains some values (some are repetitive as well). Our job is to write a function that returns the element from the array which appears for the greatest number of times in the array. For example − if the input array is − const input = ['a', 'v', 'k', 'f', 'a', 'f', 's', 'd', 'd', 'f', 'a', 'j', 'a']; Then the output should be − 'a' because 'a' gets repeated for the maximum number of times Therefore, let’s write the code for this. We will use a Map() to keep track of all the elements we encounter and their count, and at last return the element with maximum count like this − const input = ['m', 'a', 'v', 'k', 'f', 'a', 'f', 's', 'd', 'd', 'f', 'a', 'j', 'a']; const findMaximum = arr => { const map = arr.reduce((acc, val) => { let count = acc.get(val); if(count){ acc.set(val, ++count); } else { acc.set(val, 1); }; return acc; }, new Map()); return Array.from(map).reduce((acc, val) => { if(val[1] > acc[1]){ return val; }; return acc; }, [0, 0])[0]; }; console.log(findMaximum(input)); The output in the console will be − a
[ { "code": null, "e": 1296, "s": 1062, "text": "We have an array of Number / String literals that contains some values (some are repetitive as\nwell). Our job is to write a function that returns the element from the array which appears for the\ngreatest number of times in the array." }, { "code": null, "e": 1334, "s": 1296, "text": "For example − if the input array is −" }, { "code": null, "e": 1415, "s": 1334, "text": "const input = ['a', 'v', 'k', 'f', 'a', 'f', 's', 'd', 'd', 'f', 'a', 'j',\n'a'];" }, { "code": null, "e": 1443, "s": 1415, "text": "Then the output should be −" }, { "code": null, "e": 1447, "s": 1443, "text": "'a'" }, { "code": null, "e": 1505, "s": 1447, "text": "because 'a' gets repeated for the maximum number of times" }, { "code": null, "e": 1693, "s": 1505, "text": "Therefore, let’s write the code for this. We will use a Map() to keep track of all the elements we\nencounter and their count, and at last return the element with maximum count like this −" }, { "code": null, "e": 2195, "s": 1693, "text": "const input = ['m', 'a', 'v', 'k', 'f', 'a', 'f', 's', 'd', 'd', 'f', 'a',\n'j', 'a'];\nconst findMaximum = arr => {\n const map = arr.reduce((acc, val) => {\n let count = acc.get(val);\n if(count){\n acc.set(val, ++count);\n } else {\n acc.set(val, 1);\n };\n return acc;\n }, new Map());\n return Array.from(map).reduce((acc, val) => {\n if(val[1] > acc[1]){\n return val;\n };\n return acc;\n }, [0, 0])[0];\n};\nconsole.log(findMaximum(input));" }, { "code": null, "e": 2231, "s": 2195, "text": "The output in the console will be −" }, { "code": null, "e": 2233, "s": 2231, "text": "a" } ]
What are final classes in Java?
The final modifier for finalizing the implementations of classes, methods, and variables. The main purpose of using a class being declared as final is to prevent the class from being subclassed. If a class is marked as final then no class can inherit any feature from the final class. You cannot extend a final class. If you try it gives you a compile time error. final class Super { private int data = 30; } public class Sub extends Super{ public static void main(String args[]){ } } Exception in thread "main" java.lang.Error: Unresolved compilation problem: at newJavaExamples.Sub.main(Sub.java:9)
[ { "code": null, "e": 1152, "s": 1062, "text": "The final modifier for finalizing the implementations of classes, methods, and variables." }, { "code": null, "e": 1347, "s": 1152, "text": "The main purpose of using a class being declared as final is to prevent the class from being subclassed. If a class is marked as final then no class can inherit any feature from the final class." }, { "code": null, "e": 1426, "s": 1347, "text": "You cannot extend a final class. If you try it gives you a compile time error." }, { "code": null, "e": 1556, "s": 1426, "text": "final class Super {\n private int data = 30;\n}\npublic class Sub extends Super{\n public static void main(String args[]){\n }\n}" }, { "code": null, "e": 1676, "s": 1556, "text": "Exception in thread \"main\" java.lang.Error: Unresolved compilation problem:\n at newJavaExamples.Sub.main(Sub.java:9)\n" } ]
What is Stateful/Class based Component in ReactJS ? - GeeksforGeeks
08 Dec, 2021 React class-based components: These are the bread and butter of most modern web apps built in ReactJS. These components are simple classes (made up of multiple functions that add functionality to the application). All class-based components are child classes for the Component class of ReactJS. Once a component is declared, it can be used in other components. Create React app: Step 1: execute Create react app using the following command. npx create-react-app foldername Step 2: Change directory to that folder by executing the command : cd foldername Project Structure: It will look like the following. Example 1: Program to demonstrate the creation of a class-based component. App.js import React from "react"; class App extends React.Component { render() { return <h1> Welcome to GeeksForGeeks</h1>; }} export default App; Step to run the application: Open the terminal and type the following command. npm start Output: State in class components: The main feature of class-based components that distinguishes them from functional components is that they have access to a state which dictates the current behavior and appearance of the component. The state is an instance of React Component Class can be defined as an object of a set of observable properties that control the behavior of the component. In other words, the State of a component is an object that holds some information that may change over the lifetime of the component. For example, let us think of the clock that we created in this article, we were calling the render() method every second explicitly, but React provides a better way to achieve the same result and that is by using State, storing the value of time as a member of the component’s state. We will look into this more elaborately later in the article. This state can be modified by calling the setState() function. One or more variables, arrays, or objects defined as part of the state can be modified at a time with the setState() function. Example 2: Program to demonstrate the use of state and props in class-based components. Open the App.js file and replace the code with the below code. App.js import React from "react"; class App extends React.Component {constructor(props) { super(props); this.state = { change: true };}render() { return ( <div> <button onClick={() => { this.setState({ change: !this.state.change }); }} > Click Here! </button> {this.state.change ? ( <h1>Welcome to GeeksforGeeks</h1> ) : ( <h1>A Computer Science Portal for Geeks</h1> )} </div> );}} export default App; Output: Props in class components: Data is passed to other components with the help of props. Props work similarly for all components in ReactJS be they class-based or functional. Props are always passed down from the parent component to the child component. ReactJS does not allow a component to modify its own props as a rule. The only way to modify the props is to change the props being passed from the parent component to the child component. This is generally done by passing a reference to a function in the parent component, which changes the props being passed to the child component. We can access any prop from inside a component’s class using the above syntax. The ‘this.props’ is a kind of global object which stores all of the components props. The propName, that is the names of props are keys of this object. Example 3: Program to demonstrate the use of props in class-based components. Open the App.js file and replace the code with the below code. App.js import React from "react";class Name extends React.Component{ render() { return( <div> <h1>{this.props.data}</h1> </div> ) } } class PropsExample extends React.Component { constructor(props) { super(props); this.state = { change: true }; }render() { return ( <div> <button onClick={() => { this.setState({ change: !this.state.change }); }} > Click Here! </button> {this.state.change ? ( <Name data="Welcome to GeeksforGeeks" /> ) : ( <Name data="A Computer Science Portal for Geeks" /> )} </div> );}} export default PropsExample; Output: Picked React-Questions ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ReactJS useNavigate() Hook How to set background images in ReactJS ? Axios in React: A Guide for Beginners How to create a table in ReactJS ? How to navigate on path by button click in react router ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26071, "s": 26043, "text": "\n08 Dec, 2021" }, { "code": null, "e": 26432, "s": 26071, "text": "React class-based components: These are the bread and butter of most modern web apps built in ReactJS. These components are simple classes (made up of multiple functions that add functionality to the application). All class-based components are child classes for the Component class of ReactJS. Once a component is declared, it can be used in other components." }, { "code": null, "e": 26450, "s": 26432, "text": "Create React app:" }, { "code": null, "e": 26512, "s": 26450, "text": "Step 1: execute Create react app using the following command." }, { "code": null, "e": 26544, "s": 26512, "text": "npx create-react-app foldername" }, { "code": null, "e": 26611, "s": 26544, "text": "Step 2: Change directory to that folder by executing the command :" }, { "code": null, "e": 26625, "s": 26611, "text": "cd foldername" }, { "code": null, "e": 26679, "s": 26627, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 26754, "s": 26679, "text": "Example 1: Program to demonstrate the creation of a class-based component." }, { "code": null, "e": 26761, "s": 26754, "text": "App.js" }, { "code": "import React from \"react\"; class App extends React.Component { render() { return <h1> Welcome to GeeksForGeeks</h1>; }} export default App;", "e": 26908, "s": 26761, "text": null }, { "code": null, "e": 26987, "s": 26908, "text": "Step to run the application: Open the terminal and type the following command." }, { "code": null, "e": 26997, "s": 26987, "text": "npm start" }, { "code": null, "e": 27005, "s": 26997, "text": "Output:" }, { "code": null, "e": 28058, "s": 27005, "text": "State in class components: The main feature of class-based components that distinguishes them from functional components is that they have access to a state which dictates the current behavior and appearance of the component. The state is an instance of React Component Class can be defined as an object of a set of observable properties that control the behavior of the component. In other words, the State of a component is an object that holds some information that may change over the lifetime of the component. For example, let us think of the clock that we created in this article, we were calling the render() method every second explicitly, but React provides a better way to achieve the same result and that is by using State, storing the value of time as a member of the component’s state. We will look into this more elaborately later in the article. This state can be modified by calling the setState() function. One or more variables, arrays, or objects defined as part of the state can be modified at a time with the setState() function. " }, { "code": null, "e": 28209, "s": 28058, "text": "Example 2: Program to demonstrate the use of state and props in class-based components. Open the App.js file and replace the code with the below code." }, { "code": null, "e": 28216, "s": 28209, "text": "App.js" }, { "code": "import React from \"react\"; class App extends React.Component {constructor(props) { super(props); this.state = { change: true };}render() { return ( <div> <button onClick={() => { this.setState({ change: !this.state.change }); }} > Click Here! </button> {this.state.change ? ( <h1>Welcome to GeeksforGeeks</h1> ) : ( <h1>A Computer Science Portal for Geeks</h1> )} </div> );}} export default App;", "e": 28720, "s": 28216, "text": null }, { "code": null, "e": 28728, "s": 28720, "text": "Output:" }, { "code": null, "e": 29545, "s": 28728, "text": "Props in class components: Data is passed to other components with the help of props. Props work similarly for all components in ReactJS be they class-based or functional. Props are always passed down from the parent component to the child component. ReactJS does not allow a component to modify its own props as a rule. The only way to modify the props is to change the props being passed from the parent component to the child component. This is generally done by passing a reference to a function in the parent component, which changes the props being passed to the child component. We can access any prop from inside a component’s class using the above syntax. The ‘this.props’ is a kind of global object which stores all of the components props. The propName, that is the names of props are keys of this object." }, { "code": null, "e": 29686, "s": 29545, "text": "Example 3: Program to demonstrate the use of props in class-based components. Open the App.js file and replace the code with the below code." }, { "code": null, "e": 29693, "s": 29686, "text": "App.js" }, { "code": "import React from \"react\";class Name extends React.Component{ render() { return( <div> <h1>{this.props.data}</h1> </div> ) } } class PropsExample extends React.Component { constructor(props) { super(props); this.state = { change: true }; }render() { return ( <div> <button onClick={() => { this.setState({ change: !this.state.change }); }} > Click Here! </button> {this.state.change ? ( <Name data=\"Welcome to GeeksforGeeks\" /> ) : ( <Name data=\"A Computer Science Portal for Geeks\" /> )} </div> );}} export default PropsExample;", "e": 30400, "s": 29693, "text": null }, { "code": null, "e": 30408, "s": 30400, "text": "Output:" }, { "code": null, "e": 30415, "s": 30408, "text": "Picked" }, { "code": null, "e": 30431, "s": 30415, "text": "React-Questions" }, { "code": null, "e": 30439, "s": 30431, "text": "ReactJS" }, { "code": null, "e": 30456, "s": 30439, "text": "Web Technologies" }, { "code": null, "e": 30554, "s": 30456, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30581, "s": 30554, "text": "ReactJS useNavigate() Hook" }, { "code": null, "e": 30623, "s": 30581, "text": "How to set background images in ReactJS ?" }, { "code": null, "e": 30661, "s": 30623, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 30696, "s": 30661, "text": "How to create a table in ReactJS ?" }, { "code": null, "e": 30754, "s": 30696, "text": "How to navigate on path by button click in react router ?" }, { "code": null, "e": 30794, "s": 30754, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30827, "s": 30794, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30872, "s": 30827, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 30922, "s": 30872, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Evaluate and Quote an Expression in R Programming - bquote() Function - GeeksforGeeks
16 Jun, 2020 bquote() function in R Language is used to quote the arguments passed to it, except the values which are wrapped in ‘.()‘. It evaluates the wrapped values and quotes the result. Syntax: bquote(expr) Parameters:expr: language object Example 1: # R program to quote an expression # Assigning value to variablex <- 10 # Calling bquote() Functionbquote(x == x)bquote(x == 10)bquote(x == .(x))bquote(x == .(x * 2)) Output: x == x x == 10 x == 10 x == 20 Example 2: # R program to quote an expression # Assigning value to variablez <- 10 # Calling bquote() Functionbquote(function(x, y = .(z)) x + y) # Plotting a graph with the default valueplot(1:10, z+(1:10), main = bquote(z == .(z))) Output: function(x, y = 10) x + y R String-Functions R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to filter R DataFrame by values in a column? R - if statement How to import an Excel File into R ? Plot mean and standard deviation using ggplot2 in R How to filter R dataframe by multiple conditions?
[ { "code": null, "e": 26487, "s": 26459, "text": "\n16 Jun, 2020" }, { "code": null, "e": 26665, "s": 26487, "text": "bquote() function in R Language is used to quote the arguments passed to it, except the values which are wrapped in ‘.()‘. It evaluates the wrapped values and quotes the result." }, { "code": null, "e": 26686, "s": 26665, "text": "Syntax: bquote(expr)" }, { "code": null, "e": 26719, "s": 26686, "text": "Parameters:expr: language object" }, { "code": null, "e": 26730, "s": 26719, "text": "Example 1:" }, { "code": "# R program to quote an expression # Assigning value to variablex <- 10 # Calling bquote() Functionbquote(x == x)bquote(x == 10)bquote(x == .(x))bquote(x == .(x * 2))", "e": 26899, "s": 26730, "text": null }, { "code": null, "e": 26907, "s": 26899, "text": "Output:" }, { "code": null, "e": 26939, "s": 26907, "text": "x == x\nx == 10\nx == 10\nx == 20\n" }, { "code": null, "e": 26950, "s": 26939, "text": "Example 2:" }, { "code": "# R program to quote an expression # Assigning value to variablez <- 10 # Calling bquote() Functionbquote(function(x, y = .(z)) x + y) # Plotting a graph with the default valueplot(1:10, z+(1:10), main = bquote(z == .(z)))", "e": 27176, "s": 26950, "text": null }, { "code": null, "e": 27184, "s": 27176, "text": "Output:" }, { "code": null, "e": 27211, "s": 27184, "text": "function(x, y = 10) x + y\n" }, { "code": null, "e": 27230, "s": 27211, "text": "R String-Functions" }, { "code": null, "e": 27241, "s": 27230, "text": "R Language" }, { "code": null, "e": 27339, "s": 27241, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27391, "s": 27339, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 27426, "s": 27391, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 27464, "s": 27426, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 27522, "s": 27464, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 27565, "s": 27522, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 27614, "s": 27565, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 27631, "s": 27614, "text": "R - if statement" }, { "code": null, "e": 27668, "s": 27631, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 27720, "s": 27668, "text": "Plot mean and standard deviation using ggplot2 in R" } ]
Check if characters of a given string can be rearranged to form a palindrome - GeeksforGeeks
25 Feb, 2022 Given a string, Check if characters of the given string can be rearranged to form a palindrome. For example characters of “geeksogeeks” can be rearranged to form a palindrome “geeksoskeeg”, but characters of “geeksforgeeks” cannot be rearranged to form a palindrome. A set of characters can form a palindrome if at most one character occurs odd number of times and all characters occur even number of times.A simple solution is to run two loops, the outer loop picks all characters one by one, the inner loop counts the number of occurrences of the picked character. We keep track of odd counts. Time complexity of this solution is O(n2). We can do it in O(n) time using a count array. Following are detailed steps. Create a count array of alphabet size which is typically 256. Initialize all values of count array as 0.Traverse the given string and increment count of every character.Traverse the count array and if the count array has more than one odd values, return false. Otherwise, return true. Create a count array of alphabet size which is typically 256. Initialize all values of count array as 0. Traverse the given string and increment count of every character. Traverse the count array and if the count array has more than one odd values, return false. Otherwise, return true. Below is the implementation of the above approach. C++ Java Python3 C# Javascript // C++ implementation to check if// characters of a given string can// be rearranged to form a palindrome#include <bits/stdc++.h>using namespace std;#define NO_OF_CHARS 256 /* function to check whether characters of a string can form a palindrome */bool canFormPalindrome(string str){ // Create a count array and initialize all // values as 0 int count[NO_OF_CHARS] = { 0 }; // For each character in input strings, // increment count in the corresponding // count array for (int i = 0; str[i]; i++) count[str[i]]++; // Count odd occurring characters int odd = 0; for (int i = 0; i < NO_OF_CHARS; i++) { if (count[i] & 1) odd++; if (odd > 1) return false; } // Return true if odd count is 0 or 1, return true;} /* Driver code*/int main(){ canFormPalindrome("geeksforgeeks") ? cout << "Yes\n" : cout << "No\n"; canFormPalindrome("geeksogeeks") ? cout << "Yes\n" : cout << "No\n"; return 0;} // Java implementation to check if// characters of a given string can// be rearranged to form a palindromeimport java.io.*;import java.math.*;import java.util.*; class GFG { static int NO_OF_CHARS = 256; /* function to check whether characters of a string can form a palindrome */ static boolean canFormPalindrome(String str) { // Create a count array and initialize all // values as 0 int count[] = new int[NO_OF_CHARS]; Arrays.fill(count, 0); // For each character in input strings, // increment count in the corresponding // count array for (int i = 0; i < str.length(); i++) count[(int)(str.charAt(i))]++; // Count odd occurring characters int odd = 0; for (int i = 0; i < NO_OF_CHARS; i++) { if ((count[i] & 1) == 1) odd++; if (odd > 1) return false; } // Return true if odd count is 0 or 1, return true; } // Driver code public static void main(String args[]) { if (canFormPalindrome("geeksforgeeks")) System.out.println("Yes"); else System.out.println("No"); if (canFormPalindrome("geeksogeeks")) System.out.println("Yes"); else System.out.println("No"); }} // This code is contributed by Nikita Tiwari. # Python3 implementation to check if# characters of a given string can# be rearranged to form a palindrome NO_OF_CHARS = 256 # function to check whether characters# of a string can form a palindrome def canFormPalindrome(st): # Create a count array and initialize # all values as 0 count = [0] * (NO_OF_CHARS) # For each character in input strings, # increment count in the corresponding # count array for i in range(0, len(st)): count[ord(st[i])] = count[ord(st[i])] + 1 # Count odd occurring characters odd = 0 for i in range(0, NO_OF_CHARS): if (count[i] & 1): odd = odd + 1 if (odd > 1): return False # Return true if odd count is 0 or 1, return True # Driver codeif(canFormPalindrome("geeksforgeeks")): print("Yes")else: print("No") if(canFormPalindrome("geeksogeeks")): print("Yes")else: print("No") # This code is contributed by Nikita Tiwari. // C# implementation to check if// characters of a given string can// be rearranged to form a palindrome using System; class GFG { static int NO_OF_CHARS = 256; /* function to check whether characters of a string can form a palindrome */ static bool canFormPalindrome(string str) { // Create a count array and initialize all // values as 0 int[] count = new int[NO_OF_CHARS]; Array.Fill(count, 0); // For each character in input strings, // increment count in the corresponding // count array for (int i = 0; i < str.Length; i++) count[(int)(str[i])]++; // Count odd occurring characters int odd = 0; for (int i = 0; i < NO_OF_CHARS; i++) { if ((count[i] & 1) == 1) odd++; if (odd > 1) return false; } // Return true if odd count is 0 or 1, return true; } // Driver code public static void Main() { if (canFormPalindrome("geeksforgeeks")) Console.WriteLine("Yes"); else Console.WriteLine("No"); if (canFormPalindrome("geeksogeeks")) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} <script> // Javascript implementation to check if// characters of a given string can// be rearranged to form a palindrome let NO_OF_CHARS = 256; /* function to check whether characters of a string can form a palindrome */ function canFormPalindrome(str) { // Create a count array and initialize all // values as 0 let count = Array(NO_OF_CHARS).fill(0); // For each character in input strings, // increment count in the corresponding // count array for (let i = 0; i < str.length; i++) count[str[i].charCodeAt()]++; // Count odd occurring characters let odd = 0; for (let i = 0; i < NO_OF_CHARS; i++) { if ((count[i] & 1) == 1) odd++; if (odd > 1) return false; } // Return true if odd count is 0 or 1, return true; } // Driver program if (canFormPalindrome("geeksforgeeks")) document.write("Yes"); else document.write("No"); if (canFormPalindrome("geeksogeeks")) document.write("Yes"); else document.write("No"); </script> No Yes This article is contributed by Abhishek. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Another approach:We can do it in O(n) time using a list. Following are detailed steps. Create a character list.Traverse the given string.For every character in the string, remove the character if the list already contains else add to the list.If the string length is even the list is expected to be empty.Or if the string length is odd the list size is expected to be 1On the above two conditions (3) or (4) return true else return false. Create a character list. Traverse the given string. For every character in the string, remove the character if the list already contains else add to the list. If the string length is even the list is expected to be empty. Or if the string length is odd the list size is expected to be 1 On the above two conditions (3) or (4) return true else return false. C++ Java Python3 C# Javascript #include <bits/stdc++.h>using namespace std; /** function to check whether characters ofa string can form a palindrome*/bool canFormPalindrome(string str){ // Create a list vector<char> list; // For each character in input strings, // remove character if list contains // else add character to list for (int i = 0; i < str.length(); i++) { auto pos = find(list.begin(), list.end(), str[i]); if (pos != list.end()) { auto posi = find(list.begin(), list.end(), str[i]); list.erase(posi); } else list.push_back(str[i]); } // if character length is even list is // expected to be empty or if character // length is odd list size is expected to be 1 // if string length is even if (str.length() % 2 == 0 && list.empty() || (str.length() % 2 == 1 && list.size() == 1)) return true; // if string length is odd else return false;} // Driver codeint main(){ if (canFormPalindrome("geeksforgeeks")) cout << ("Yes") << endl; else cout << ("No") << endl; if (canFormPalindrome("geeksogeeks")) cout << ("Yes") << endl; else cout << ("No") << endl;} // This code is contributed by Rajput-Ji import java.util.ArrayList;import java.util.List; class GFG { /* * function to check whether * characters of a string can form a palindrome */ static boolean canFormPalindrome(String str) { // Create a list List<Character> list = new ArrayList<Character>(); // For each character in input strings, // remove character if list contains // else add character to list for (int i = 0; i < str.length(); i++) { if (list.contains(str.charAt(i))) list.remove((Character)str.charAt(i)); else list.add(str.charAt(i)); } // if character length is even // list is expected to be empty or // if character length is odd list size // is expected to be 1 // if string length is even if (str.length() % 2 == 0 && list.isEmpty() || (str.length() % 2 == 1 && list.size() == 1)) return true; // if string length is odd else return false; } // Driver code public static void main(String args[]) { if (canFormPalindrome("geeksforgeeks")) System.out.println("Yes"); else System.out.println("No"); if (canFormPalindrome("geeksogeeks")) System.out.println("Yes"); else System.out.println("No"); }} // This code is contributed by Sugunakumar P ''' * function to check whether characters of a string can form a palindrome ''' def canFormPalindrome(strr): # Create a list listt = [] # For each character in input strings, # remove character if list contains # else add character to list for i in range(len(strr)): if (strr[i] in listt): listt.remove(strr[i]) else: listt.append(strr[i]) # if character length is even # list is expected to be empty # or if character length is odd # list size is expected to be 1 if (len(strr) % 2 == 0 and len(listt) == 0 or (len(strr) % 2 == 1 and len(listt) == 1)): return True else: return False # Driver codeif (canFormPalindrome("geeksforgeeks")): print("Yes")else: print("No") if (canFormPalindrome("geeksogeeks")): print("Yes")else: print("No") # This code is contributed by SHUBHAMSINGH10 // C# Implementation of the above approachusing System;using System.Collections.Generic;class GFG { /* * function to check whether characters of a string can form a palindrome */ static Boolean canFormPalindrome(String str) { // Create a list List<char> list = new List<char>(); // For each character in input strings, // remove character if list contains // else add character to list for (int i = 0; i < str.Length; i++) { if (list.Contains(str[i])) list.Remove((char)str[i]); else list.Add(str[i]); } // if character length is even // list is expected to be empty // or if character length is odd // list size is expected to be 1 // if string length is even if (str.Length % 2 == 0 && list.Count == 0 || (str.Length % 2 == 1 && list.Count == 1)) return true; // if string length is odd else return false; } // Driver Code public static void Main(String[] args) { if (canFormPalindrome("geeksforgeeks")) Console.WriteLine("Yes"); else Console.WriteLine("No"); if (canFormPalindrome("geeksogeeks")) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code is contributed by Rajput-Ji <script> /* * function to check whether * characters of a string can form a palindrome */function canFormPalindrome(str){ // Create a list let list = []; // For each character in input strings, // remove character if list contains // else add character to list for(let i = 0; i < str.length; i++) { if (list.includes(str[i])) list.splice(list.indexOf(str[i]), 1); else list.push(str[i]); } // If character length is even // list is expected to be empty or // if character length is odd list size // is expected to be 1 // If string length is even if (str.length % 2 == 0 && list.length == 0 || (str.length % 2 == 1 && list.length == 1)) return true; // If string length is odd else return false;} // Driver codeif (canFormPalindrome("geeksforgeeks")) document.write("Yes<br>");else document.write("No<br>"); if (canFormPalindrome("geeksogeeks")) document.write("Yes<br>");else document.write("No<br>"); // This code is contributed by ab2127 </script> No Yes Another Approach: (Using Bits) This problem can be solved in O(n) time where n is the number of characters in the string and O(1) space. The string to be palindrome all the characters should occur an even number of times if the string is of even length and at most one character can occur an odd number of times if the string length is odd. Track of the count of the characters is not required instead, it is sufficient to keep track if the counts are odd or even. This can be achieved by using a variable as bit vector. For every character in the string: if the bit corresponding to character is not set: //if it is the character’s odd occurrence set the bit else if the bit corresponding to character is set: //if it is the character’s even occurrence toggle the bit This is similar to performing an XOR operation between bit vector and mask. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ Implementation of the above approach# include <bits/stdc++.h>using namespace std; bool canFormPalindrome(string a){ // bitvector to store // the record of which character appear // odd and even number of times int bitvector = 0, mask = 0; for (int i=0; a[i] != '\0'; i++) { int x = a[i] - 'a'; mask = 1 << x; bitvector = bitvector ^ mask; } return (bitvector & (bitvector - 1)) == 0;} // Driver Codeint main(){ if (canFormPalindrome("geeksforgeeks")) cout << ("Yes") << endl; else cout << ("No") << endl; return 0;} // Java Implementation of the above approachimport java.io.*;class GFG { static boolean canFormPalindrome(String a) { // bitvector to store // the record of which character appear // odd and even number of times int bitvector = 0, mask = 0; for (int i = 0; i < a.length(); i++) { int x = a.charAt(i) - 'a'; mask = 1 << x; bitvector = bitvector ^ mask; } return (bitvector & (bitvector - 1)) == 0; } // Driver Code public static void main (String[] args) { if (canFormPalindrome("geeksforgeeks")) System.out.println("Yes"); else System.out.println("No"); }} // This code is contributed by rag2127 # Python3 implementation of above approach.def canFormPalindrome(s): bitvector = 0 for str in s: bitvector ^= 1 << ord(str) return bitvector == 0 or bitvector & (bitvector - 1) == 0 #s = input() if canFormPalindrome("geeksforgeeks"): print('Yes')else: print('No') # This code is contributed by sahilmahale0 // C# Implementation of the above approachusing System;public class GFG{ static bool canFormPalindrome(string a) { // bitvector to store // the record of which character appear // odd and even number of times int bitvector = 0, mask = 0; for (int i = 0; i < a.Length; i++) { int x = a[i] - 'a'; mask = 1 << x; bitvector = bitvector ^ mask; } return (bitvector & (bitvector - 1)) == 0; } // Driver Code static public void Main (){ if (canFormPalindrome("geeksforgeeks")) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code is contributed by avanitrachhadiya2155 <script> // JavaScript implementation of the above approach function canFormPalindrome(a){ // Bitvector to store the record // of which character appear // odd and even number of times var bitvector = 0, mask = 0; for(var i = 0; i < a.length; i++) { var x = a.charCodeAt(i) - 97; mask = 1 << x; bitvector = bitvector ^ mask; } return ((bitvector & (bitvector - 1)) == 0);} // Driver Codeif (canFormPalindrome("geeksforgeeks")) document.write("Yes" + "<br>");else document.write("No" + "<br>"); // This code is contributed by akshitsaxenaa09 </script> No ukasp psugunakumar Rajput-Ji SHUBHAMSINGH10 phoenix_rk sahilmahale0 rag2127 avanitrachhadiya2155 akshitsaxenaa09 chinmoy1997pal ab2127 ruhelaa48 akshaysingh98088 CoderSaty amartyaghoshgfg surinderdawra388 Morgan Stanley palindrome Hash Strings Morgan Stanley Hash Strings palindrome Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Hashing | Set 2 (Separate Chaining) Sort string of characters Counting frequencies of array elements Most frequent element in an array Sorting a Map by value in C++ STL Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Longest Common Subsequence | DP-4
[ { "code": null, "e": 26387, "s": 26359, "text": "\n25 Feb, 2022" }, { "code": null, "e": 26655, "s": 26387, "text": "Given a string, Check if characters of the given string can be rearranged to form a palindrome. For example characters of “geeksogeeks” can be rearranged to form a palindrome “geeksoskeeg”, but characters of “geeksforgeeks” cannot be rearranged to form a palindrome. " }, { "code": null, "e": 27027, "s": 26655, "text": "A set of characters can form a palindrome if at most one character occurs odd number of times and all characters occur even number of times.A simple solution is to run two loops, the outer loop picks all characters one by one, the inner loop counts the number of occurrences of the picked character. We keep track of odd counts. Time complexity of this solution is O(n2)." }, { "code": null, "e": 27105, "s": 27027, "text": "We can do it in O(n) time using a count array. Following are detailed steps. " }, { "code": null, "e": 27390, "s": 27105, "text": "Create a count array of alphabet size which is typically 256. Initialize all values of count array as 0.Traverse the given string and increment count of every character.Traverse the count array and if the count array has more than one odd values, return false. Otherwise, return true." }, { "code": null, "e": 27495, "s": 27390, "text": "Create a count array of alphabet size which is typically 256. Initialize all values of count array as 0." }, { "code": null, "e": 27561, "s": 27495, "text": "Traverse the given string and increment count of every character." }, { "code": null, "e": 27677, "s": 27561, "text": "Traverse the count array and if the count array has more than one odd values, return false. Otherwise, return true." }, { "code": null, "e": 27728, "s": 27677, "text": "Below is the implementation of the above approach." }, { "code": null, "e": 27732, "s": 27728, "text": "C++" }, { "code": null, "e": 27737, "s": 27732, "text": "Java" }, { "code": null, "e": 27745, "s": 27737, "text": "Python3" }, { "code": null, "e": 27748, "s": 27745, "text": "C#" }, { "code": null, "e": 27759, "s": 27748, "text": "Javascript" }, { "code": "// C++ implementation to check if// characters of a given string can// be rearranged to form a palindrome#include <bits/stdc++.h>using namespace std;#define NO_OF_CHARS 256 /* function to check whether characters of a string can form a palindrome */bool canFormPalindrome(string str){ // Create a count array and initialize all // values as 0 int count[NO_OF_CHARS] = { 0 }; // For each character in input strings, // increment count in the corresponding // count array for (int i = 0; str[i]; i++) count[str[i]]++; // Count odd occurring characters int odd = 0; for (int i = 0; i < NO_OF_CHARS; i++) { if (count[i] & 1) odd++; if (odd > 1) return false; } // Return true if odd count is 0 or 1, return true;} /* Driver code*/int main(){ canFormPalindrome(\"geeksforgeeks\") ? cout << \"Yes\\n\" : cout << \"No\\n\"; canFormPalindrome(\"geeksogeeks\") ? cout << \"Yes\\n\" : cout << \"No\\n\"; return 0;}", "e": 28771, "s": 27759, "text": null }, { "code": "// Java implementation to check if// characters of a given string can// be rearranged to form a palindromeimport java.io.*;import java.math.*;import java.util.*; class GFG { static int NO_OF_CHARS = 256; /* function to check whether characters of a string can form a palindrome */ static boolean canFormPalindrome(String str) { // Create a count array and initialize all // values as 0 int count[] = new int[NO_OF_CHARS]; Arrays.fill(count, 0); // For each character in input strings, // increment count in the corresponding // count array for (int i = 0; i < str.length(); i++) count[(int)(str.charAt(i))]++; // Count odd occurring characters int odd = 0; for (int i = 0; i < NO_OF_CHARS; i++) { if ((count[i] & 1) == 1) odd++; if (odd > 1) return false; } // Return true if odd count is 0 or 1, return true; } // Driver code public static void main(String args[]) { if (canFormPalindrome(\"geeksforgeeks\")) System.out.println(\"Yes\"); else System.out.println(\"No\"); if (canFormPalindrome(\"geeksogeeks\")) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} // This code is contributed by Nikita Tiwari.", "e": 30165, "s": 28771, "text": null }, { "code": "# Python3 implementation to check if# characters of a given string can# be rearranged to form a palindrome NO_OF_CHARS = 256 # function to check whether characters# of a string can form a palindrome def canFormPalindrome(st): # Create a count array and initialize # all values as 0 count = [0] * (NO_OF_CHARS) # For each character in input strings, # increment count in the corresponding # count array for i in range(0, len(st)): count[ord(st[i])] = count[ord(st[i])] + 1 # Count odd occurring characters odd = 0 for i in range(0, NO_OF_CHARS): if (count[i] & 1): odd = odd + 1 if (odd > 1): return False # Return true if odd count is 0 or 1, return True # Driver codeif(canFormPalindrome(\"geeksforgeeks\")): print(\"Yes\")else: print(\"No\") if(canFormPalindrome(\"geeksogeeks\")): print(\"Yes\")else: print(\"No\") # This code is contributed by Nikita Tiwari.", "e": 31129, "s": 30165, "text": null }, { "code": "// C# implementation to check if// characters of a given string can// be rearranged to form a palindrome using System; class GFG { static int NO_OF_CHARS = 256; /* function to check whether characters of a string can form a palindrome */ static bool canFormPalindrome(string str) { // Create a count array and initialize all // values as 0 int[] count = new int[NO_OF_CHARS]; Array.Fill(count, 0); // For each character in input strings, // increment count in the corresponding // count array for (int i = 0; i < str.Length; i++) count[(int)(str[i])]++; // Count odd occurring characters int odd = 0; for (int i = 0; i < NO_OF_CHARS; i++) { if ((count[i] & 1) == 1) odd++; if (odd > 1) return false; } // Return true if odd count is 0 or 1, return true; } // Driver code public static void Main() { if (canFormPalindrome(\"geeksforgeeks\")) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); if (canFormPalindrome(\"geeksogeeks\")) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }}", "e": 32404, "s": 31129, "text": null }, { "code": "<script> // Javascript implementation to check if// characters of a given string can// be rearranged to form a palindrome let NO_OF_CHARS = 256; /* function to check whether characters of a string can form a palindrome */ function canFormPalindrome(str) { // Create a count array and initialize all // values as 0 let count = Array(NO_OF_CHARS).fill(0); // For each character in input strings, // increment count in the corresponding // count array for (let i = 0; i < str.length; i++) count[str[i].charCodeAt()]++; // Count odd occurring characters let odd = 0; for (let i = 0; i < NO_OF_CHARS; i++) { if ((count[i] & 1) == 1) odd++; if (odd > 1) return false; } // Return true if odd count is 0 or 1, return true; } // Driver program if (canFormPalindrome(\"geeksforgeeks\")) document.write(\"Yes\"); else document.write(\"No\"); if (canFormPalindrome(\"geeksogeeks\")) document.write(\"Yes\"); else document.write(\"No\"); </script>", "e": 33605, "s": 32404, "text": null }, { "code": null, "e": 33615, "s": 33608, "text": "No\nYes" }, { "code": null, "e": 33782, "s": 33617, "text": "This article is contributed by Abhishek. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 33872, "s": 33784, "text": "Another approach:We can do it in O(n) time using a list. Following are detailed steps. " }, { "code": null, "e": 34226, "s": 33874, "text": "Create a character list.Traverse the given string.For every character in the string, remove the character if the list already contains else add to the list.If the string length is even the list is expected to be empty.Or if the string length is odd the list size is expected to be 1On the above two conditions (3) or (4) return true else return false." }, { "code": null, "e": 34251, "s": 34226, "text": "Create a character list." }, { "code": null, "e": 34278, "s": 34251, "text": "Traverse the given string." }, { "code": null, "e": 34385, "s": 34278, "text": "For every character in the string, remove the character if the list already contains else add to the list." }, { "code": null, "e": 34448, "s": 34385, "text": "If the string length is even the list is expected to be empty." }, { "code": null, "e": 34513, "s": 34448, "text": "Or if the string length is odd the list size is expected to be 1" }, { "code": null, "e": 34583, "s": 34513, "text": "On the above two conditions (3) or (4) return true else return false." }, { "code": null, "e": 34589, "s": 34585, "text": "C++" }, { "code": null, "e": 34594, "s": 34589, "text": "Java" }, { "code": null, "e": 34602, "s": 34594, "text": "Python3" }, { "code": null, "e": 34605, "s": 34602, "text": "C#" }, { "code": null, "e": 34616, "s": 34605, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; /** function to check whether characters ofa string can form a palindrome*/bool canFormPalindrome(string str){ // Create a list vector<char> list; // For each character in input strings, // remove character if list contains // else add character to list for (int i = 0; i < str.length(); i++) { auto pos = find(list.begin(), list.end(), str[i]); if (pos != list.end()) { auto posi = find(list.begin(), list.end(), str[i]); list.erase(posi); } else list.push_back(str[i]); } // if character length is even list is // expected to be empty or if character // length is odd list size is expected to be 1 // if string length is even if (str.length() % 2 == 0 && list.empty() || (str.length() % 2 == 1 && list.size() == 1)) return true; // if string length is odd else return false;} // Driver codeint main(){ if (canFormPalindrome(\"geeksforgeeks\")) cout << (\"Yes\") << endl; else cout << (\"No\") << endl; if (canFormPalindrome(\"geeksogeeks\")) cout << (\"Yes\") << endl; else cout << (\"No\") << endl;} // This code is contributed by Rajput-Ji", "e": 35972, "s": 34616, "text": null }, { "code": "import java.util.ArrayList;import java.util.List; class GFG { /* * function to check whether * characters of a string can form a palindrome */ static boolean canFormPalindrome(String str) { // Create a list List<Character> list = new ArrayList<Character>(); // For each character in input strings, // remove character if list contains // else add character to list for (int i = 0; i < str.length(); i++) { if (list.contains(str.charAt(i))) list.remove((Character)str.charAt(i)); else list.add(str.charAt(i)); } // if character length is even // list is expected to be empty or // if character length is odd list size // is expected to be 1 // if string length is even if (str.length() % 2 == 0 && list.isEmpty() || (str.length() % 2 == 1 && list.size() == 1)) return true; // if string length is odd else return false; } // Driver code public static void main(String args[]) { if (canFormPalindrome(\"geeksforgeeks\")) System.out.println(\"Yes\"); else System.out.println(\"No\"); if (canFormPalindrome(\"geeksogeeks\")) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} // This code is contributed by Sugunakumar P", "e": 37493, "s": 35972, "text": null }, { "code": "''' * function to check whether characters of a string can form a palindrome ''' def canFormPalindrome(strr): # Create a list listt = [] # For each character in input strings, # remove character if list contains # else add character to list for i in range(len(strr)): if (strr[i] in listt): listt.remove(strr[i]) else: listt.append(strr[i]) # if character length is even # list is expected to be empty # or if character length is odd # list size is expected to be 1 if (len(strr) % 2 == 0 and len(listt) == 0 or (len(strr) % 2 == 1 and len(listt) == 1)): return True else: return False # Driver codeif (canFormPalindrome(\"geeksforgeeks\")): print(\"Yes\")else: print(\"No\") if (canFormPalindrome(\"geeksogeeks\")): print(\"Yes\")else: print(\"No\") # This code is contributed by SHUBHAMSINGH10", "e": 38402, "s": 37493, "text": null }, { "code": "// C# Implementation of the above approachusing System;using System.Collections.Generic;class GFG { /* * function to check whether characters of a string can form a palindrome */ static Boolean canFormPalindrome(String str) { // Create a list List<char> list = new List<char>(); // For each character in input strings, // remove character if list contains // else add character to list for (int i = 0; i < str.Length; i++) { if (list.Contains(str[i])) list.Remove((char)str[i]); else list.Add(str[i]); } // if character length is even // list is expected to be empty // or if character length is odd // list size is expected to be 1 // if string length is even if (str.Length % 2 == 0 && list.Count == 0 || (str.Length % 2 == 1 && list.Count == 1)) return true; // if string length is odd else return false; } // Driver Code public static void Main(String[] args) { if (canFormPalindrome(\"geeksforgeeks\")) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); if (canFormPalindrome(\"geeksogeeks\")) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // This code is contributed by Rajput-Ji", "e": 39867, "s": 38402, "text": null }, { "code": "<script> /* * function to check whether * characters of a string can form a palindrome */function canFormPalindrome(str){ // Create a list let list = []; // For each character in input strings, // remove character if list contains // else add character to list for(let i = 0; i < str.length; i++) { if (list.includes(str[i])) list.splice(list.indexOf(str[i]), 1); else list.push(str[i]); } // If character length is even // list is expected to be empty or // if character length is odd list size // is expected to be 1 // If string length is even if (str.length % 2 == 0 && list.length == 0 || (str.length % 2 == 1 && list.length == 1)) return true; // If string length is odd else return false;} // Driver codeif (canFormPalindrome(\"geeksforgeeks\")) document.write(\"Yes<br>\");else document.write(\"No<br>\"); if (canFormPalindrome(\"geeksogeeks\")) document.write(\"Yes<br>\");else document.write(\"No<br>\"); // This code is contributed by ab2127 </script>", "e": 40977, "s": 39867, "text": null }, { "code": null, "e": 40984, "s": 40977, "text": "No\nYes" }, { "code": null, "e": 41016, "s": 40984, "text": " Another Approach: (Using Bits)" }, { "code": null, "e": 41122, "s": 41016, "text": "This problem can be solved in O(n) time where n is the number of characters in the string and O(1) space." }, { "code": null, "e": 41450, "s": 41122, "text": "The string to be palindrome all the characters should occur an even number of times if the string is of even length and at most one character can occur an odd number of times if the string length is odd. Track of the count of the characters is not required instead, it is sufficient to keep track if the counts are odd or even." }, { "code": null, "e": 41506, "s": 41450, "text": "This can be achieved by using a variable as bit vector." }, { "code": null, "e": 41541, "s": 41506, "text": "For every character in the string:" }, { "code": null, "e": 41647, "s": 41541, "text": "if the bit corresponding to character is not set: //if it is the character’s odd occurrence set the bit " }, { "code": null, "e": 41756, "s": 41647, "text": "else if the bit corresponding to character is set: //if it is the character’s even occurrence toggle the bit" }, { "code": null, "e": 41832, "s": 41756, "text": "This is similar to performing an XOR operation between bit vector and mask." }, { "code": null, "e": 41884, "s": 41832, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 41888, "s": 41884, "text": "C++" }, { "code": null, "e": 41893, "s": 41888, "text": "Java" }, { "code": null, "e": 41901, "s": 41893, "text": "Python3" }, { "code": null, "e": 41904, "s": 41901, "text": "C#" }, { "code": null, "e": 41915, "s": 41904, "text": "Javascript" }, { "code": "// C++ Implementation of the above approach# include <bits/stdc++.h>using namespace std; bool canFormPalindrome(string a){ // bitvector to store // the record of which character appear // odd and even number of times int bitvector = 0, mask = 0; for (int i=0; a[i] != '\\0'; i++) { int x = a[i] - 'a'; mask = 1 << x; bitvector = bitvector ^ mask; } return (bitvector & (bitvector - 1)) == 0;} // Driver Codeint main(){ if (canFormPalindrome(\"geeksforgeeks\")) cout << (\"Yes\") << endl; else cout << (\"No\") << endl; return 0;}", "e": 42508, "s": 41915, "text": null }, { "code": "// Java Implementation of the above approachimport java.io.*;class GFG { static boolean canFormPalindrome(String a) { // bitvector to store // the record of which character appear // odd and even number of times int bitvector = 0, mask = 0; for (int i = 0; i < a.length(); i++) { int x = a.charAt(i) - 'a'; mask = 1 << x; bitvector = bitvector ^ mask; } return (bitvector & (bitvector - 1)) == 0; } // Driver Code public static void main (String[] args) { if (canFormPalindrome(\"geeksforgeeks\")) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} // This code is contributed by rag2127", "e": 43178, "s": 42508, "text": null }, { "code": "# Python3 implementation of above approach.def canFormPalindrome(s): bitvector = 0 for str in s: bitvector ^= 1 << ord(str) return bitvector == 0 or bitvector & (bitvector - 1) == 0 #s = input() if canFormPalindrome(\"geeksforgeeks\"): print('Yes')else: print('No') # This code is contributed by sahilmahale0", "e": 43516, "s": 43178, "text": null }, { "code": "// C# Implementation of the above approachusing System;public class GFG{ static bool canFormPalindrome(string a) { // bitvector to store // the record of which character appear // odd and even number of times int bitvector = 0, mask = 0; for (int i = 0; i < a.Length; i++) { int x = a[i] - 'a'; mask = 1 << x; bitvector = bitvector ^ mask; } return (bitvector & (bitvector - 1)) == 0; } // Driver Code static public void Main (){ if (canFormPalindrome(\"geeksforgeeks\")) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // This code is contributed by avanitrachhadiya2155", "e": 44169, "s": 43516, "text": null }, { "code": "<script> // JavaScript implementation of the above approach function canFormPalindrome(a){ // Bitvector to store the record // of which character appear // odd and even number of times var bitvector = 0, mask = 0; for(var i = 0; i < a.length; i++) { var x = a.charCodeAt(i) - 97; mask = 1 << x; bitvector = bitvector ^ mask; } return ((bitvector & (bitvector - 1)) == 0);} // Driver Codeif (canFormPalindrome(\"geeksforgeeks\")) document.write(\"Yes\" + \"<br>\");else document.write(\"No\" + \"<br>\"); // This code is contributed by akshitsaxenaa09 </script>", "e": 44790, "s": 44169, "text": null }, { "code": null, "e": 44796, "s": 44793, "text": "No" }, { "code": null, "e": 44804, "s": 44798, "text": "ukasp" }, { "code": null, "e": 44817, "s": 44804, "text": "psugunakumar" }, { "code": null, "e": 44827, "s": 44817, "text": "Rajput-Ji" }, { "code": null, "e": 44842, "s": 44827, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 44853, "s": 44842, "text": "phoenix_rk" }, { "code": null, "e": 44866, "s": 44853, "text": "sahilmahale0" }, { "code": null, "e": 44874, "s": 44866, "text": "rag2127" }, { "code": null, "e": 44895, "s": 44874, "text": "avanitrachhadiya2155" }, { "code": null, "e": 44911, "s": 44895, "text": "akshitsaxenaa09" }, { "code": null, "e": 44926, "s": 44911, "text": "chinmoy1997pal" }, { "code": null, "e": 44933, "s": 44926, "text": "ab2127" }, { "code": null, "e": 44943, "s": 44933, "text": "ruhelaa48" }, { "code": null, "e": 44960, "s": 44943, "text": "akshaysingh98088" }, { "code": null, "e": 44970, "s": 44960, "text": "CoderSaty" }, { "code": null, "e": 44986, "s": 44970, "text": "amartyaghoshgfg" }, { "code": null, "e": 45003, "s": 44986, "text": "surinderdawra388" }, { "code": null, "e": 45018, "s": 45003, "text": "Morgan Stanley" }, { "code": null, "e": 45029, "s": 45018, "text": "palindrome" }, { "code": null, "e": 45034, "s": 45029, "text": "Hash" }, { "code": null, "e": 45042, "s": 45034, "text": "Strings" }, { "code": null, "e": 45057, "s": 45042, "text": "Morgan Stanley" }, { "code": null, "e": 45062, "s": 45057, "text": "Hash" }, { "code": null, "e": 45070, "s": 45062, "text": "Strings" }, { "code": null, "e": 45081, "s": 45070, "text": "palindrome" }, { "code": null, "e": 45179, "s": 45081, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 45215, "s": 45179, "text": "Hashing | Set 2 (Separate Chaining)" }, { "code": null, "e": 45241, "s": 45215, "text": "Sort string of characters" }, { "code": null, "e": 45280, "s": 45241, "text": "Counting frequencies of array elements" }, { "code": null, "e": 45314, "s": 45280, "text": "Most frequent element in an array" }, { "code": null, "e": 45348, "s": 45314, "text": "Sorting a Map by value in C++ STL" }, { "code": null, "e": 45394, "s": 45348, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 45419, "s": 45394, "text": "Reverse a string in Java" }, { "code": null, "e": 45479, "s": 45419, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 45494, "s": 45479, "text": "C++ Data Types" } ]
Introduction of Botnet in Computer Networks - GeeksforGeeks
13 Aug, 2019 Network of compromised computers are called botnet. Compromised computers are also called as Zombies or bots. Programming Language:These software are mostly written in C++ & C. Motivation:It all starts with the dark side of the internet which introduced new kind of Crime called Cybercrime Among the malware (malicious software) botnet is a most widespread and serious threat.Several large institutions, government organizations, almost every social networking websites Facebook, Twitter, Instagram etc, e-commerce website Amazon, Flipkart etc, in short, every firm associated with internet became the victim of this malware. The funniest part about this kind of malicious software is that it is freely available in the market for the lease. It can be used in DDoS attacks (Smurf attack), Phishing, Extortion etc. How it Works:Either you write code to build software or use it from the available (Leaked) botnet like ZEUS Botnet(king of all botnet), Mirai botnet, BASHLITE etc. then find the vulnerable system where you can install this software through some means like social engineering (e.g Phishing) soon that system becomes a part of bot army. Those who control it called as the botmaster which communicates its bot army using command and control channel. Botnet Communication:At first, those who want to be botmaster finds the target system (here target system means finding the vulnerable system), then use popular social engineering techniques like phishing, click fraud etc to install small (Kbs) executable file into it. A small patch has been included in the code which made it not visible even with all the running background process. A naive user won’t even come to know that his/her system became the part of a bot army. After infection, bot looks for the channel through which it can communicate with its master. Mostly Channel (command and Control channel) uses the existing protocol to request for the command and receive updates from the master, so that if anyone tries to look at the traffic behavior then it will be quite difficult to figure it out. Botmaster used to write scripts to run an executable file on different OS. For Windows: Batch Program For Linux: BASH Program Following are the major things can be performed on bots: Web-Injection:Botmaster can inject snippet of code to any secured website which bot used to visit.Web-filters:Here on using a special symbol like:”!” for bypass specific domain,”@” for the screenshot are used.Web-fakes:Redirection of the webpage can be done here.DnsMAP:Assign any IP to any domain which master wants to route of the bot family. Web-Injection:Botmaster can inject snippet of code to any secured website which bot used to visit. Web-filters:Here on using a special symbol like:”!” for bypass specific domain,”@” for the screenshot are used. Web-fakes:Redirection of the webpage can be done here. DnsMAP:Assign any IP to any domain which master wants to route of the bot family. Types of Botnet: Based on Channel: Internet Relay Chat (IRC) Botnet:Internet Relay Chat (IRC) acts as the C&C Channel.Bots receive commands from a centralized IRC server. A command is in the form of a normal chat message.Limitation: Entire botnet can be collapsed by simply shutting down the IRC Server.Peer-to-Peer (P2P) Botnet:Formed using the P2P protocols and decentralized network of nodes.Very difficult to shut down due to its decentralized structure. Each P2P bot can act both as the client and the server. The bots frequently communicate with each other and send “keep alive” messages.Limitation:Has a higher latency for data transmission.Hyper Text Transfer Protocol (HTTP) Botnet:Centralized structure, using HTTP protocol to hide their activities.Bots use specific URL or IP address to connect to the C&C Server, at regular intervals. Unlike IRC bots, HTTP bots periodically visit C&C server to get updates or new commands. Internet Relay Chat (IRC) Botnet:Internet Relay Chat (IRC) acts as the C&C Channel.Bots receive commands from a centralized IRC server. A command is in the form of a normal chat message.Limitation: Entire botnet can be collapsed by simply shutting down the IRC Server. Peer-to-Peer (P2P) Botnet:Formed using the P2P protocols and decentralized network of nodes.Very difficult to shut down due to its decentralized structure. Each P2P bot can act both as the client and the server. The bots frequently communicate with each other and send “keep alive” messages.Limitation:Has a higher latency for data transmission. Hyper Text Transfer Protocol (HTTP) Botnet:Centralized structure, using HTTP protocol to hide their activities.Bots use specific URL or IP address to connect to the C&C Server, at regular intervals. Unlike IRC bots, HTTP bots periodically visit C&C server to get updates or new commands. Botnet Lifecycle can be understood using the following stages: Stage-1: Stage-2: Stage-3: Stage-4: This is a brief introduction of the botnet. Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Advanced Encryption Standard (AES) Intrusion Detection System (IDS) Introduction and IPv4 Datagram Header Secure Socket Layer (SSL) Cryptography and its Types Multiple Access Protocols in Computer Network Routing Information Protocol (RIP) Congestion Control in Computer Networks Wireless Sensor Network (WSN) Architecture of Internet of Things (IoT)
[ { "code": null, "e": 25755, "s": 25727, "text": "\n13 Aug, 2019" }, { "code": null, "e": 25865, "s": 25755, "text": "Network of compromised computers are called botnet. Compromised computers are also called as Zombies or bots." }, { "code": null, "e": 25932, "s": 25865, "text": "Programming Language:These software are mostly written in C++ & C." }, { "code": null, "e": 26569, "s": 25932, "text": "Motivation:It all starts with the dark side of the internet which introduced new kind of Crime called Cybercrime Among the malware (malicious software) botnet is a most widespread and serious threat.Several large institutions, government organizations, almost every social networking websites Facebook, Twitter, Instagram etc, e-commerce website Amazon, Flipkart etc, in short, every firm associated with internet became the victim of this malware. The funniest part about this kind of malicious software is that it is freely available in the market for the lease. It can be used in DDoS attacks (Smurf attack), Phishing, Extortion etc." }, { "code": null, "e": 27016, "s": 26569, "text": "How it Works:Either you write code to build software or use it from the available (Leaked) botnet like ZEUS Botnet(king of all botnet), Mirai botnet, BASHLITE etc. then find the vulnerable system where you can install this software through some means like social engineering (e.g Phishing) soon that system becomes a part of bot army. Those who control it called as the botmaster which communicates its bot army using command and control channel." }, { "code": null, "e": 27825, "s": 27016, "text": "Botnet Communication:At first, those who want to be botmaster finds the target system (here target system means finding the vulnerable system), then use popular social engineering techniques like phishing, click fraud etc to install small (Kbs) executable file into it. A small patch has been included in the code which made it not visible even with all the running background process. A naive user won’t even come to know that his/her system became the part of a bot army. After infection, bot looks for the channel through which it can communicate with its master. Mostly Channel (command and Control channel) uses the existing protocol to request for the command and receive updates from the master, so that if anyone tries to look at the traffic behavior then it will be quite difficult to figure it out." }, { "code": null, "e": 27900, "s": 27825, "text": "Botmaster used to write scripts to run an executable file on different OS." }, { "code": null, "e": 27953, "s": 27900, "text": "For Windows: Batch Program \nFor Linux: BASH Program " }, { "code": null, "e": 28010, "s": 27953, "text": "Following are the major things can be performed on bots:" }, { "code": null, "e": 28355, "s": 28010, "text": "Web-Injection:Botmaster can inject snippet of code to any secured website which bot used to visit.Web-filters:Here on using a special symbol like:”!” for bypass specific domain,”@” for the screenshot are used.Web-fakes:Redirection of the webpage can be done here.DnsMAP:Assign any IP to any domain which master wants to route of the bot family." }, { "code": null, "e": 28454, "s": 28355, "text": "Web-Injection:Botmaster can inject snippet of code to any secured website which bot used to visit." }, { "code": null, "e": 28566, "s": 28454, "text": "Web-filters:Here on using a special symbol like:”!” for bypass specific domain,”@” for the screenshot are used." }, { "code": null, "e": 28621, "s": 28566, "text": "Web-fakes:Redirection of the webpage can be done here." }, { "code": null, "e": 28703, "s": 28621, "text": "DnsMAP:Assign any IP to any domain which master wants to route of the bot family." }, { "code": null, "e": 28738, "s": 28703, "text": "Types of Botnet: Based on Channel:" }, { "code": null, "e": 29639, "s": 28738, "text": "Internet Relay Chat (IRC) Botnet:Internet Relay Chat (IRC) acts as the C&C Channel.Bots receive commands from a centralized IRC server. A command is in the form of a normal chat message.Limitation: Entire botnet can be collapsed by simply shutting down the IRC Server.Peer-to-Peer (P2P) Botnet:Formed using the P2P protocols and decentralized network of nodes.Very difficult to shut down due to its decentralized structure. Each P2P bot can act both as the client and the server. The bots frequently communicate with each other and send “keep alive” messages.Limitation:Has a higher latency for data transmission.Hyper Text Transfer Protocol (HTTP) Botnet:Centralized structure, using HTTP protocol to hide their activities.Bots use specific URL or IP address to connect to the C&C Server, at regular intervals. Unlike IRC bots, HTTP bots periodically visit C&C server to get updates or new commands." }, { "code": null, "e": 29908, "s": 29639, "text": "Internet Relay Chat (IRC) Botnet:Internet Relay Chat (IRC) acts as the C&C Channel.Bots receive commands from a centralized IRC server. A command is in the form of a normal chat message.Limitation: Entire botnet can be collapsed by simply shutting down the IRC Server." }, { "code": null, "e": 30254, "s": 29908, "text": "Peer-to-Peer (P2P) Botnet:Formed using the P2P protocols and decentralized network of nodes.Very difficult to shut down due to its decentralized structure. Each P2P bot can act both as the client and the server. The bots frequently communicate with each other and send “keep alive” messages.Limitation:Has a higher latency for data transmission." }, { "code": null, "e": 30542, "s": 30254, "text": "Hyper Text Transfer Protocol (HTTP) Botnet:Centralized structure, using HTTP protocol to hide their activities.Bots use specific URL or IP address to connect to the C&C Server, at regular intervals. Unlike IRC bots, HTTP bots periodically visit C&C server to get updates or new commands." }, { "code": null, "e": 30605, "s": 30542, "text": "Botnet Lifecycle can be understood using the following stages:" }, { "code": null, "e": 30614, "s": 30605, "text": "Stage-1:" }, { "code": null, "e": 30623, "s": 30614, "text": "Stage-2:" }, { "code": null, "e": 30632, "s": 30623, "text": "Stage-3:" }, { "code": null, "e": 30641, "s": 30632, "text": "Stage-4:" }, { "code": null, "e": 30685, "s": 30641, "text": "This is a brief introduction of the botnet." }, { "code": null, "e": 30703, "s": 30685, "text": "Computer Networks" }, { "code": null, "e": 30721, "s": 30703, "text": "Computer Networks" }, { "code": null, "e": 30819, "s": 30721, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30854, "s": 30819, "text": "Advanced Encryption Standard (AES)" }, { "code": null, "e": 30887, "s": 30854, "text": "Intrusion Detection System (IDS)" }, { "code": null, "e": 30925, "s": 30887, "text": "Introduction and IPv4 Datagram Header" }, { "code": null, "e": 30951, "s": 30925, "text": "Secure Socket Layer (SSL)" }, { "code": null, "e": 30978, "s": 30951, "text": "Cryptography and its Types" }, { "code": null, "e": 31024, "s": 30978, "text": "Multiple Access Protocols in Computer Network" }, { "code": null, "e": 31059, "s": 31024, "text": "Routing Information Protocol (RIP)" }, { "code": null, "e": 31099, "s": 31059, "text": "Congestion Control in Computer Networks" }, { "code": null, "e": 31129, "s": 31099, "text": "Wireless Sensor Network (WSN)" } ]
Find mirror of a given node in Binary tree - GeeksforGeeks
29 Jun, 2021 Given a Binary tree, the problem is to find the mirror of a given node. The mirror of a node is a node which exists at the mirror position of the node in opposite subtree at the root. Examples: In above tree- Node 2 and 3 are mirror nodes Node 4 and 6 are mirror nodes. We can have a recursive solution for finding mirror nodes. The algorithm is following – 1) Start from the root of the tree and recur nodes from both subtree simultaneously using two pointers for left and right nodes. 2) First recur all the external nodes and store returned value in mirror variable. 3) If current node value is equal to target node, return the value of opposite pointer else repeat step 2. 4) If no external node is left and mirror is none, recur internal nodes. C++ C Java Python3 C# Javascript // C++ program to find the mirror Node// in Binary tree#include <bits/stdc++.h> using namespace std; /* A binary tree Node has data,pointer to left child anda pointer to right child */struct Node{ int key; struct Node* left, *right;}; // create new Node and initialize itstruct Node* newNode(int key){ struct Node* n = (struct Node*) malloc(sizeof(struct Node*)); if (n != NULL) { n->key = key; n->left = NULL; n->right = NULL; return n; } else { cout << "Memory allocation failed!" << endl; exit(1); }} // recursive function to find mirror of Nodeint findMirrorRec(int target, struct Node* left, struct Node* right){ /* if any of the Node is none then Node itself and decendent have no mirror, so return none, no need to further explore! */ if (left == NULL || right == NULL) return 0; /* if left Node is target Node, then return right's key (that is mirror) and vice versa */ if (left->key == target) return right->key; if (right->key == target) return left->key; // first recur external Nodes int mirror_val = findMirrorRec(target, left->left, right->right); if (mirror_val) return mirror_val; // if no mirror found, recur internal Nodes findMirrorRec(target, left->right, right->left);} // interface for mirror searchint findMirror(struct Node* root, int target){ if (root == NULL) return 0; if (root->key == target) return target; return findMirrorRec(target, root->left, root->right);} // Driver Codeint main(){ struct Node* root = newNode(1); root-> left = newNode(2); root->left->left = newNode(4); root->left->left->right = newNode(7); root->right = newNode(3); root->right->left = newNode(5); root->right->right = newNode(6); root->right->left->left = newNode(8); root->right->left->right = newNode(9); // target Node whose mirror have to be searched int target = root->left->left->key; int mirror = findMirror(root, target); if (mirror) cout << "Mirror of Node " << target << " is Node " << mirror << endl; else cout << "Mirror of Node " << target << " is NULL! " << endl;} // This code is contributed by SHUBHAMSINGH10 // C program to find the mirror Node in Binary tree#include <stdio.h>#include <stdlib.h> /* A binary tree Node has data, pointer to left child and a pointer to right child */struct Node{ int key; struct Node* left, *right;}; // create new Node and initialize itstruct Node* newNode(int key){ struct Node* n = (struct Node*) malloc(sizeof(struct Node*)); if (n != NULL) { n->key = key; n->left = NULL; n->right = NULL; return n; } else { printf("Memory allocation failed!"); exit(1); }} // recursive function to find mirror of Nodeint findMirrorRec(int target, struct Node* left, struct Node* right){ /* if any of the Node is none then Node itself and decendent have no mirror, so return none, no need to further explore! */ if (left==NULL || right==NULL) return 0; /* if left Node is target Node, then return right's key (that is mirror) and vice versa */ if (left->key == target) return right->key; if (right->key == target) return left->key; // first recur external Nodes int mirror_val = findMirrorRec(target, left->left, right->right); if (mirror_val) return mirror_val; // if no mirror found, recur internal Nodes findMirrorRec(target, left->right, right->left);} // interface for mirror searchint findMirror(struct Node* root, int target){ if (root == NULL) return 0; if (root->key == target) return target; return findMirrorRec(target, root->left, root->right);} // Driverint main(){ struct Node* root = newNode(1); root-> left = newNode(2); root->left->left = newNode(4); root->left->left->right = newNode(7); root->right = newNode(3); root->right->left = newNode(5); root->right->right = newNode(6); root->right->left->left = newNode(8); root->right->left->right = newNode(9); // target Node whose mirror have to be searched int target = root->left->left->key; int mirror = findMirror(root, target); if (mirror) printf("Mirror of Node %d is Node %d\n", target, mirror); else printf("Mirror of Node %d is NULL!\n", target);} // Java program to find the mirror Node in Binary treeclass GfG { /* A binary tree Node has data, pointer to left childand a pointer to right child */static class Node{ int key; Node left, right;} // create new Node and initialize itstatic Node newNode(int key){ Node n = new Node(); n.key = key; n.left = null; n.right = null; return n;} // recursive function to find mirror of Nodestatic int findMirrorRec(int target, Node left, Node right){ /* if any of the Node is none then Node itself and decendent have no mirror, so return none, no need to further explore! */ if (left==null || right==null) return 0; /* if left Node is target Node, then return right's key (that is mirror) and vice versa */ if (left.key == target) return right.key; if (right.key == target) return left.key; // first recur external Nodes int mirror_val = findMirrorRec(target, left.left, right.right); if (mirror_val != 0) return mirror_val; // if no mirror found, recur internal Nodes return findMirrorRec(target, left.right, right.left);} // interface for mirror searchstatic int findMirror(Node root, int target){ if (root == null) return 0; if (root.key == target) return target; return findMirrorRec(target, root.left, root.right);} // Driverpublic static void main(String[] args){ Node root = newNode(1); root.left = newNode(2); root.left.left = newNode(4); root.left.left.right = newNode(7); root.right = newNode(3); root.right.left = newNode(5); root.right.right = newNode(6); root.right.left.left = newNode(8); root.right.left.right = newNode(9); // target Node whose mirror have to be searched int target = root.left.left.key; int mirror = findMirror(root, target); if (mirror != 0) System.out.println("Mirror of Node " + target + " is Node " + mirror); else System.out.println("Mirror of Node " + target + " is null ");}} # Python3 program to find the mirror node in# Binary tree class Node: '''A binary tree node has data, reference to left child and a reference to right child ''' def __init__(self, key, lchild=None, rchild=None): self.key = key self.lchild = None self.rchild = None # recursive function to find mirrordef findMirrorRec(target, left, right): # If any of the node is none then node itself # and decendent have no mirror, so return # none, no need to further explore! if left == None or right == None: return None # if left node is target node, then return # right's key (that is mirror) and vice versa if left.key == target: return right.key if right.key == target: return left.key # first recur external nodes mirror_val = findMirrorRec(target, left.lchild, right.rchild) if mirror_val != None: return mirror_val # if no mirror found, recur internal nodes findMirrorRec(target, left.rchild, right.lchild) # interface for mirror searchdef findMirror(root, target): if root == None: return None if root.key == target: return target return findMirrorRec(target, root.lchild, root.rchild) # Driverdef main(): root = Node(1) n1 = Node(2) n2 = Node(3) root.lchild = n1 root.rchild = n2 n3 = Node(4) n4 = Node(5) n5 = Node(6) n1.lchild = n3 n2.lchild = n4 n2.rchild = n5 n6 = Node(7) n7 = Node(8) n8 = Node(9) n3.rchild = n6 n4.lchild = n7 n4.rchild = n8 # target node whose mirror have to be searched target = n3.key mirror = findMirror(root, target) print("Mirror of node {} is node {}".format(target, mirror)) if __name__ == '__main__': main() // C# program to find the// mirror Node in Binary treeusing System; class GfG{ /* A binary tree Node has data, pointer to left child and a pointer to right child */ class Node { public int key; public Node left, right; } // create new Node and initialize it static Node newNode(int key) { Node n = new Node(); n.key = key; n.left = null; n.right = null; return n; } // recursive function to find mirror of Node static int findMirrorRec(int target, Node left, Node right) { /* if any of the Node is none then Node itself and decendent have no mirror, so return none, no need to further explore! */ if (left==null || right==null) return 0; /* if left Node is target Node, then return right's key (that is mirror) and vice versa */ if (left.key == target) return right.key; if (right.key == target) return left.key; // first recur external Nodes int mirror_val = findMirrorRec(target, left.left, right.right); if (mirror_val != 0) return mirror_val; // if no mirror found, recur internal Nodes return findMirrorRec(target, left.right, right.left); } // interface for mirror search static int findMirror(Node root, int target) { if (root == null) return 0; if (root.key == target) return target; return findMirrorRec(target, root.left, root.right); } // Driver code public static void Main(String[] args) { Node root = newNode(1); root.left = newNode(2); root.left.left = newNode(4); root.left.left.right = newNode(7); root.right = newNode(3); root.right.left = newNode(5); root.right.right = newNode(6); root.right.left.left = newNode(8); root.right.left.right = newNode(9); // target Node whose mirror have to be searched int target = root.left.left.key; int mirror = findMirror(root, target); if (mirror != 0) Console.WriteLine("Mirror of Node " + target + " is Node " + mirror); else Console.WriteLine("Mirror of Node " + target + " is null "); }} // This code is contributed by 29AjayKumar <script> // Javascript program to find the mirror// Node in Binary tree /* A binary tree Node has data, pointerto left child and a pointer to right child */class Node{ // Create new Node and initialize it constructor(key) { this.key = key; this.left = this.right = null; }} // Recursive function to find mirror of Nodefunction findMirrorRec(target, left, right){ /* If any of the Node is none then Node itself and decendent have no mirror, so return none, no need to further explore! */ if (left == null || right == null) return 0; /* If left Node is target Node, then return right's key (that is mirror) and vice versa */ if (left.key == target) return right.key; if (right.key == target) return left.key; // First recur external Nodes let mirror_val = findMirrorRec( target, left.left, right.right); if (mirror_val != 0) return mirror_val; // If no mirror found, recur internal Nodes return findMirrorRec(target, left.right, right.left);} // Interface for mirror searchfunction findMirror(root, target){ if (root == null) return 0; if (root.key == target) return target; return findMirrorRec(target, root.left, root.right);} // Driver codelet root = new Node(1);root.left = new Node(2);root.left.left = new Node(4);root.left.left.right = new Node(7);root.right = new Node(3);root.right.left = new Node(5);root.right.right = new Node(6);root.right.left.left = new Node(8);root.right.left.right = new Node(9); // Target Node whose mirror have to be searchedlet target = root.left.left.key; let mirror = findMirror(root, target); if (mirror != 0) document.write("Mirror of Node " + target + " is Node " + mirror + "<br>");else document.write("Mirror of Node " + target + " is null " + "<br>"); // This code is contributed by rag2127 </script> Output: Mirror of node 4 is node 6 Time Complexity: YouTube<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=lN848OkmMY4" 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 Atul 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 review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. prerna saini 29AjayKumar SHUBHAMSINGH10 rag2127 Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Tree Data Structure DFS traversal of a tree using recursion Top 50 Tree Coding Problems for Interviews Find the node with minimum value in a Binary Search Tree Real-time application of Data Structures Print Binary Tree in 2-Dimensions Iterative Postorder Traversal | Set 2 (Using One Stack) Find maximum (or minimum) in Binary Tree Difference between Min Heap and Max Heap Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)
[ { "code": null, "e": 26183, "s": 26155, "text": "\n29 Jun, 2021" }, { "code": null, "e": 26367, "s": 26183, "text": "Given a Binary tree, the problem is to find the mirror of a given node. The mirror of a node is a node which exists at the mirror position of the node in opposite subtree at the root." }, { "code": null, "e": 26379, "s": 26367, "text": "Examples: " }, { "code": null, "e": 26456, "s": 26379, "text": "In above tree-\nNode 2 and 3 are mirror nodes\nNode 4 and 6 are mirror nodes. " }, { "code": null, "e": 26546, "s": 26456, "text": "We can have a recursive solution for finding mirror nodes. The algorithm is following – " }, { "code": null, "e": 26962, "s": 26546, "text": "1) Start from the root of the tree and recur \n nodes from both subtree simultaneously \n using two pointers for left and right nodes.\n2) First recur all the external nodes and \n store returned value in mirror variable.\n3) If current node value is equal to target node, \n return the value of opposite pointer else \n repeat step 2.\n4) If no external node is left and mirror is \n none, recur internal nodes." }, { "code": null, "e": 26966, "s": 26962, "text": "C++" }, { "code": null, "e": 26968, "s": 26966, "text": "C" }, { "code": null, "e": 26973, "s": 26968, "text": "Java" }, { "code": null, "e": 26981, "s": 26973, "text": "Python3" }, { "code": null, "e": 26984, "s": 26981, "text": "C#" }, { "code": null, "e": 26995, "s": 26984, "text": "Javascript" }, { "code": "// C++ program to find the mirror Node// in Binary tree#include <bits/stdc++.h> using namespace std; /* A binary tree Node has data,pointer to left child anda pointer to right child */struct Node{ int key; struct Node* left, *right;}; // create new Node and initialize itstruct Node* newNode(int key){ struct Node* n = (struct Node*) malloc(sizeof(struct Node*)); if (n != NULL) { n->key = key; n->left = NULL; n->right = NULL; return n; } else { cout << \"Memory allocation failed!\" << endl; exit(1); }} // recursive function to find mirror of Nodeint findMirrorRec(int target, struct Node* left, struct Node* right){ /* if any of the Node is none then Node itself and decendent have no mirror, so return none, no need to further explore! */ if (left == NULL || right == NULL) return 0; /* if left Node is target Node, then return right's key (that is mirror) and vice versa */ if (left->key == target) return right->key; if (right->key == target) return left->key; // first recur external Nodes int mirror_val = findMirrorRec(target, left->left, right->right); if (mirror_val) return mirror_val; // if no mirror found, recur internal Nodes findMirrorRec(target, left->right, right->left);} // interface for mirror searchint findMirror(struct Node* root, int target){ if (root == NULL) return 0; if (root->key == target) return target; return findMirrorRec(target, root->left, root->right);} // Driver Codeint main(){ struct Node* root = newNode(1); root-> left = newNode(2); root->left->left = newNode(4); root->left->left->right = newNode(7); root->right = newNode(3); root->right->left = newNode(5); root->right->right = newNode(6); root->right->left->left = newNode(8); root->right->left->right = newNode(9); // target Node whose mirror have to be searched int target = root->left->left->key; int mirror = findMirror(root, target); if (mirror) cout << \"Mirror of Node \" << target << \" is Node \" << mirror << endl; else cout << \"Mirror of Node \" << target << \" is NULL! \" << endl;} // This code is contributed by SHUBHAMSINGH10", "e": 29446, "s": 26995, "text": null }, { "code": "// C program to find the mirror Node in Binary tree#include <stdio.h>#include <stdlib.h> /* A binary tree Node has data, pointer to left child and a pointer to right child */struct Node{ int key; struct Node* left, *right;}; // create new Node and initialize itstruct Node* newNode(int key){ struct Node* n = (struct Node*) malloc(sizeof(struct Node*)); if (n != NULL) { n->key = key; n->left = NULL; n->right = NULL; return n; } else { printf(\"Memory allocation failed!\"); exit(1); }} // recursive function to find mirror of Nodeint findMirrorRec(int target, struct Node* left, struct Node* right){ /* if any of the Node is none then Node itself and decendent have no mirror, so return none, no need to further explore! */ if (left==NULL || right==NULL) return 0; /* if left Node is target Node, then return right's key (that is mirror) and vice versa */ if (left->key == target) return right->key; if (right->key == target) return left->key; // first recur external Nodes int mirror_val = findMirrorRec(target, left->left, right->right); if (mirror_val) return mirror_val; // if no mirror found, recur internal Nodes findMirrorRec(target, left->right, right->left);} // interface for mirror searchint findMirror(struct Node* root, int target){ if (root == NULL) return 0; if (root->key == target) return target; return findMirrorRec(target, root->left, root->right);} // Driverint main(){ struct Node* root = newNode(1); root-> left = newNode(2); root->left->left = newNode(4); root->left->left->right = newNode(7); root->right = newNode(3); root->right->left = newNode(5); root->right->right = newNode(6); root->right->left->left = newNode(8); root->right->left->right = newNode(9); // target Node whose mirror have to be searched int target = root->left->left->key; int mirror = findMirror(root, target); if (mirror) printf(\"Mirror of Node %d is Node %d\\n\", target, mirror); else printf(\"Mirror of Node %d is NULL!\\n\", target);}", "e": 31856, "s": 29446, "text": null }, { "code": "// Java program to find the mirror Node in Binary treeclass GfG { /* A binary tree Node has data, pointer to left childand a pointer to right child */static class Node{ int key; Node left, right;} // create new Node and initialize itstatic Node newNode(int key){ Node n = new Node(); n.key = key; n.left = null; n.right = null; return n;} // recursive function to find mirror of Nodestatic int findMirrorRec(int target, Node left, Node right){ /* if any of the Node is none then Node itself and decendent have no mirror, so return none, no need to further explore! */ if (left==null || right==null) return 0; /* if left Node is target Node, then return right's key (that is mirror) and vice versa */ if (left.key == target) return right.key; if (right.key == target) return left.key; // first recur external Nodes int mirror_val = findMirrorRec(target, left.left, right.right); if (mirror_val != 0) return mirror_val; // if no mirror found, recur internal Nodes return findMirrorRec(target, left.right, right.left);} // interface for mirror searchstatic int findMirror(Node root, int target){ if (root == null) return 0; if (root.key == target) return target; return findMirrorRec(target, root.left, root.right);} // Driverpublic static void main(String[] args){ Node root = newNode(1); root.left = newNode(2); root.left.left = newNode(4); root.left.left.right = newNode(7); root.right = newNode(3); root.right.left = newNode(5); root.right.right = newNode(6); root.right.left.left = newNode(8); root.right.left.right = newNode(9); // target Node whose mirror have to be searched int target = root.left.left.key; int mirror = findMirror(root, target); if (mirror != 0) System.out.println(\"Mirror of Node \" + target + \" is Node \" + mirror); else System.out.println(\"Mirror of Node \" + target + \" is null \");}}", "e": 33936, "s": 31856, "text": null }, { "code": "# Python3 program to find the mirror node in# Binary tree class Node: '''A binary tree node has data, reference to left child and a reference to right child ''' def __init__(self, key, lchild=None, rchild=None): self.key = key self.lchild = None self.rchild = None # recursive function to find mirrordef findMirrorRec(target, left, right): # If any of the node is none then node itself # and decendent have no mirror, so return # none, no need to further explore! if left == None or right == None: return None # if left node is target node, then return # right's key (that is mirror) and vice versa if left.key == target: return right.key if right.key == target: return left.key # first recur external nodes mirror_val = findMirrorRec(target, left.lchild, right.rchild) if mirror_val != None: return mirror_val # if no mirror found, recur internal nodes findMirrorRec(target, left.rchild, right.lchild) # interface for mirror searchdef findMirror(root, target): if root == None: return None if root.key == target: return target return findMirrorRec(target, root.lchild, root.rchild) # Driverdef main(): root = Node(1) n1 = Node(2) n2 = Node(3) root.lchild = n1 root.rchild = n2 n3 = Node(4) n4 = Node(5) n5 = Node(6) n1.lchild = n3 n2.lchild = n4 n2.rchild = n5 n6 = Node(7) n7 = Node(8) n8 = Node(9) n3.rchild = n6 n4.lchild = n7 n4.rchild = n8 # target node whose mirror have to be searched target = n3.key mirror = findMirror(root, target) print(\"Mirror of node {} is node {}\".format(target, mirror)) if __name__ == '__main__': main()", "e": 35675, "s": 33936, "text": null }, { "code": "// C# program to find the// mirror Node in Binary treeusing System; class GfG{ /* A binary tree Node has data, pointer to left child and a pointer to right child */ class Node { public int key; public Node left, right; } // create new Node and initialize it static Node newNode(int key) { Node n = new Node(); n.key = key; n.left = null; n.right = null; return n; } // recursive function to find mirror of Node static int findMirrorRec(int target, Node left, Node right) { /* if any of the Node is none then Node itself and decendent have no mirror, so return none, no need to further explore! */ if (left==null || right==null) return 0; /* if left Node is target Node, then return right's key (that is mirror) and vice versa */ if (left.key == target) return right.key; if (right.key == target) return left.key; // first recur external Nodes int mirror_val = findMirrorRec(target, left.left, right.right); if (mirror_val != 0) return mirror_val; // if no mirror found, recur internal Nodes return findMirrorRec(target, left.right, right.left); } // interface for mirror search static int findMirror(Node root, int target) { if (root == null) return 0; if (root.key == target) return target; return findMirrorRec(target, root.left, root.right); } // Driver code public static void Main(String[] args) { Node root = newNode(1); root.left = newNode(2); root.left.left = newNode(4); root.left.left.right = newNode(7); root.right = newNode(3); root.right.left = newNode(5); root.right.right = newNode(6); root.right.left.left = newNode(8); root.right.left.right = newNode(9); // target Node whose mirror have to be searched int target = root.left.left.key; int mirror = findMirror(root, target); if (mirror != 0) Console.WriteLine(\"Mirror of Node \" + target + \" is Node \" + mirror); else Console.WriteLine(\"Mirror of Node \" + target + \" is null \"); }} // This code is contributed by 29AjayKumar", "e": 38235, "s": 35675, "text": null }, { "code": "<script> // Javascript program to find the mirror// Node in Binary tree /* A binary tree Node has data, pointerto left child and a pointer to right child */class Node{ // Create new Node and initialize it constructor(key) { this.key = key; this.left = this.right = null; }} // Recursive function to find mirror of Nodefunction findMirrorRec(target, left, right){ /* If any of the Node is none then Node itself and decendent have no mirror, so return none, no need to further explore! */ if (left == null || right == null) return 0; /* If left Node is target Node, then return right's key (that is mirror) and vice versa */ if (left.key == target) return right.key; if (right.key == target) return left.key; // First recur external Nodes let mirror_val = findMirrorRec( target, left.left, right.right); if (mirror_val != 0) return mirror_val; // If no mirror found, recur internal Nodes return findMirrorRec(target, left.right, right.left);} // Interface for mirror searchfunction findMirror(root, target){ if (root == null) return 0; if (root.key == target) return target; return findMirrorRec(target, root.left, root.right);} // Driver codelet root = new Node(1);root.left = new Node(2);root.left.left = new Node(4);root.left.left.right = new Node(7);root.right = new Node(3);root.right.left = new Node(5);root.right.right = new Node(6);root.right.left.left = new Node(8);root.right.left.right = new Node(9); // Target Node whose mirror have to be searchedlet target = root.left.left.key; let mirror = findMirror(root, target); if (mirror != 0) document.write(\"Mirror of Node \" + target + \" is Node \" + mirror + \"<br>\");else document.write(\"Mirror of Node \" + target + \" is null \" + \"<br>\"); // This code is contributed by rag2127 </script>", "e": 40240, "s": 38235, "text": null }, { "code": null, "e": 40249, "s": 40240, "text": "Output: " }, { "code": null, "e": 40276, "s": 40249, "text": "Mirror of node 4 is node 6" }, { "code": null, "e": 40294, "s": 40276, "text": "Time Complexity: " }, { "code": null, "e": 40586, "s": 40294, "text": "YouTube<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=lN848OkmMY4\" 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": 41005, "s": 40586, "text": "This article is contributed by Atul 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 review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 41018, "s": 41005, "text": "prerna saini" }, { "code": null, "e": 41030, "s": 41018, "text": "29AjayKumar" }, { "code": null, "e": 41045, "s": 41030, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 41053, "s": 41045, "text": "rag2127" }, { "code": null, "e": 41058, "s": 41053, "text": "Tree" }, { "code": null, "e": 41063, "s": 41058, "text": "Tree" }, { "code": null, "e": 41161, "s": 41063, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41197, "s": 41161, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 41237, "s": 41197, "text": "DFS traversal of a tree using recursion" }, { "code": null, "e": 41280, "s": 41237, "text": "Top 50 Tree Coding Problems for Interviews" }, { "code": null, "e": 41337, "s": 41280, "text": "Find the node with minimum value in a Binary Search Tree" }, { "code": null, "e": 41378, "s": 41337, "text": "Real-time application of Data Structures" }, { "code": null, "e": 41412, "s": 41378, "text": "Print Binary Tree in 2-Dimensions" }, { "code": null, "e": 41468, "s": 41412, "text": "Iterative Postorder Traversal | Set 2 (Using One Stack)" }, { "code": null, "e": 41509, "s": 41468, "text": "Find maximum (or minimum) in Binary Tree" }, { "code": null, "e": 41550, "s": 41509, "text": "Difference between Min Heap and Max Heap" } ]
How to Create a Range From a Specified Start in C#? - GeeksforGeeks
28 Nov, 2019 The Range Structure is introduced in C# 8.0. It represents a range that has a start and end indexes. You are allowed to create a Range object starting from the specified starting index to the end of the given collection or sequence with the help of the StartAt() Method provided by the Range structure. Or in other words, StartAt() Method returns a range that starts from the specified start index to the end of the given collection or sequence. Syntax: public static Range StartAt(Index start); Here, the Index start represents the start index. Example 1: // C# program to illustrate // how to create a range using// StartAt() method of Range structusing System; namespace range_example { class GFG { // Main Method static void Main(string[] args) { // Creating range // using Range constructor var r1 = new Range(2, 4); // Creating range // using Range operator Range r2 = 1..10; // Creating a range // using StartAt() method var r3 = Range.StartAt(4); // Displaying all the ranges Console.WriteLine("Range_1: " + r1); Console.WriteLine("Range_2: " + r2); Console.WriteLine("Range_3: " + r3); }}} Output: Range_1: 2..4 Range_2: 1..10 Range_3: 4..^0 Example 2: // C# program to illustrate how // to create a range using// StartAt() method of Range structusing System; namespace range_example { class GFG { // Main Method static void Main(string[] args) { // Creating and initializing an array int[] arr = new int[8] {100, 200, 300, 400, 500, 600, 700, 800}; // Creating a range // using StartAt() method var r = Range.StartAt(2); var new_arr = arr[r]; // Displaying the range // and the elements Console.WriteLine("Range: " + r); Console.Write("Numbers: "); foreach(var i in new_arr) Console.Write($" [{i}]"); }}} Output: Range: 2..^0 Numbers: [300] [400] [500] [600] [700] [800] CSharp-8.0 C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Extension Method in C# HashSet in C# with Examples C# | Inheritance Partial Classes in C# C# | Generics - Introduction Top 50 C# Interview Questions & Answers Switch Statement in C# C# | How to insert an element in an Array? Convert String to Character Array in C# Linked List Implementation in C#
[ { "code": null, "e": 25547, "s": 25519, "text": "\n28 Nov, 2019" }, { "code": null, "e": 25993, "s": 25547, "text": "The Range Structure is introduced in C# 8.0. It represents a range that has a start and end indexes. You are allowed to create a Range object starting from the specified starting index to the end of the given collection or sequence with the help of the StartAt() Method provided by the Range structure. Or in other words, StartAt() Method returns a range that starts from the specified start index to the end of the given collection or sequence." }, { "code": null, "e": 26001, "s": 25993, "text": "Syntax:" }, { "code": null, "e": 26043, "s": 26001, "text": "public static Range StartAt(Index start);" }, { "code": null, "e": 26093, "s": 26043, "text": "Here, the Index start represents the start index." }, { "code": null, "e": 26104, "s": 26093, "text": "Example 1:" }, { "code": "// C# program to illustrate // how to create a range using// StartAt() method of Range structusing System; namespace range_example { class GFG { // Main Method static void Main(string[] args) { // Creating range // using Range constructor var r1 = new Range(2, 4); // Creating range // using Range operator Range r2 = 1..10; // Creating a range // using StartAt() method var r3 = Range.StartAt(4); // Displaying all the ranges Console.WriteLine(\"Range_1: \" + r1); Console.WriteLine(\"Range_2: \" + r2); Console.WriteLine(\"Range_3: \" + r3); }}}", "e": 26759, "s": 26104, "text": null }, { "code": null, "e": 26767, "s": 26759, "text": "Output:" }, { "code": null, "e": 26812, "s": 26767, "text": "Range_1: 2..4\nRange_2: 1..10\nRange_3: 4..^0\n" }, { "code": null, "e": 26823, "s": 26812, "text": "Example 2:" }, { "code": "// C# program to illustrate how // to create a range using// StartAt() method of Range structusing System; namespace range_example { class GFG { // Main Method static void Main(string[] args) { // Creating and initializing an array int[] arr = new int[8] {100, 200, 300, 400, 500, 600, 700, 800}; // Creating a range // using StartAt() method var r = Range.StartAt(2); var new_arr = arr[r]; // Displaying the range // and the elements Console.WriteLine(\"Range: \" + r); Console.Write(\"Numbers: \"); foreach(var i in new_arr) Console.Write($\" [{i}]\"); }}}", "e": 27512, "s": 26823, "text": null }, { "code": null, "e": 27520, "s": 27512, "text": "Output:" }, { "code": null, "e": 27580, "s": 27520, "text": "Range: 2..^0\nNumbers: [300] [400] [500] [600] [700] [800]\n" }, { "code": null, "e": 27591, "s": 27580, "text": "CSharp-8.0" }, { "code": null, "e": 27594, "s": 27591, "text": "C#" }, { "code": null, "e": 27692, "s": 27594, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27715, "s": 27692, "text": "Extension Method in C#" }, { "code": null, "e": 27743, "s": 27715, "text": "HashSet in C# with Examples" }, { "code": null, "e": 27760, "s": 27743, "text": "C# | Inheritance" }, { "code": null, "e": 27782, "s": 27760, "text": "Partial Classes in C#" }, { "code": null, "e": 27811, "s": 27782, "text": "C# | Generics - Introduction" }, { "code": null, "e": 27851, "s": 27811, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 27874, "s": 27851, "text": "Switch Statement in C#" }, { "code": null, "e": 27917, "s": 27874, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 27957, "s": 27917, "text": "Convert String to Character Array in C#" } ]
Project Euler - GeeksforGeeks
21 Apr, 2017 What is Project Euler?Project Euler is a series of challenging problems that require mathematical and programming skills. Somebody who enjoys learning new area of mathematics, project Euler is going to be a fun journey. Where are the problems ?The problems are right here in their official archive. Let’s solve a problem from the archive and understand its complexity. Randomly I have chosen Problem no 116.Problem 116 : Red, green or blue tilesProblem Statement Solution: [ IT IS ADVISED TO TRY YOURSELF FIRST]A red tile is of length 2, green is of length 3 and blue is of length 4. Since, we need to count total ways for 50 units of black colored square tiles, say k = 50. def E_116(i, k): ways = [1] * i + [0] * (k-i+1) for j in range(i, k+1): ways[j] += ways[j - 1] + ways[j - i] return ways[k] - 1 Here, we are initializing our function E_116() which holds the logic of the solution to the problem.The function E_116() has two parameters i = number of black coloured square tiles covered by the new coloured (red, green or blue) tiles and k = total number of black coloured square tiles.In the function, ways = [1] * i + [0] * (k-i+1) So, ways is a list which holds the total number of ways which the i length block can cover 50 black coloured square tiles.For e.g:In the above example x = [1, 1, 1, 0, 0, 0] , has 1 (x3) and 0 (x3) , where 1 represents possible solution case and 0 represents failure.As we can compare for i = 3 and k = 5 from the question, we get total 3 possible ways.Hence there are 1 (x3) in the list, ways. for j in range(i, k+1): ways[j] += ways[j - 1] + ways[j - i] Using the for loop we are iterating from i to 50, we have written k+1 since iterating in the loop through range() will exclude the last case.In ways[j] += ways[j – 1] + ways[j – i], we are updating the jth index of the list ways with the summation of (j-1) and (j+i)th index’s value and also the jth index value (Since +=).These are the possible values of j, for i=3 and k =5.Finally we return our list as return ways[k] – 1.So, for i=3 and k=5, this gives the solution(i.e, Ans = 3)Lastly in our code, print("Number of black tiles =", k, "units") print("Number of ways to fill:", E_116(2, k) + E_116(3, k) + E_116(4, k)) We print away our result using the print() function. The first statement prints Number of black tiles = 50 and the second statement prints Number of ways to fill: 20492570929 which is the desired answer to the problem. # Project Euler Problem 116 k = 50def E_116(i, k): ways = [1] * i + [0] * (k-i+1) for j in range(i, k+1): ways[j] += ways[j - 1] + ways[j - i] return ways[k] - 1 print("Number of black tiles =", k, "units")print("Number of ways to fill:", E_116(2, k) + E_116(3, k) + E_116(4, k)) Resources: projecteuler Java solution _ mathblog This article is contributed by Amartya Ranjan Saikia. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Competitive Programming Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Multistage Graph (Shortest Path) Breadth First Traversal ( BFS ) on a 2D array Check whether bitwise AND of a number with any subset of an array is zero or not Shortest path in a directed graph by Dijkstra’s algorithm 5 Best Books for Competitive Programming 5 Best Languages for Competitive Programming Most important type of Algorithms Difference between Backtracking and Branch-N-Bound technique String hashing using Polynomial rolling hash function Graph implementation using STL for competitive programming | Set 2 (Weighted graph)
[ { "code": null, "e": 26281, "s": 26253, "text": "\n21 Apr, 2017" }, { "code": null, "e": 26501, "s": 26281, "text": "What is Project Euler?Project Euler is a series of challenging problems that require mathematical and programming skills. Somebody who enjoys learning new area of mathematics, project Euler is going to be a fun journey." }, { "code": null, "e": 26580, "s": 26501, "text": "Where are the problems ?The problems are right here in their official archive." }, { "code": null, "e": 26744, "s": 26580, "text": "Let’s solve a problem from the archive and understand its complexity. Randomly I have chosen Problem no 116.Problem 116 : Red, green or blue tilesProblem Statement" }, { "code": null, "e": 26865, "s": 26744, "text": "Solution: [ IT IS ADVISED TO TRY YOURSELF FIRST]A red tile is of length 2, green is of length 3 and blue is of length 4." }, { "code": null, "e": 26956, "s": 26865, "text": "Since, we need to count total ways for 50 units of black colored square tiles, say k = 50." }, { "code": null, "e": 27105, "s": 26956, "text": "def E_116(i, k):\n ways = [1] * i + [0] * (k-i+1)\n for j in range(i, k+1):\n ways[j] += ways[j - 1] + ways[j - i]\n return ways[k] - 1\n" }, { "code": null, "e": 27411, "s": 27105, "text": "Here, we are initializing our function E_116() which holds the logic of the solution to the problem.The function E_116() has two parameters i = number of black coloured square tiles covered by the new coloured (red, green or blue) tiles and k = total number of black coloured square tiles.In the function," }, { "code": null, "e": 27442, "s": 27411, "text": "ways = [1] * i + [0] * (k-i+1)" }, { "code": null, "e": 27837, "s": 27442, "text": "So, ways is a list which holds the total number of ways which the i length block can cover 50 black coloured square tiles.For e.g:In the above example x = [1, 1, 1, 0, 0, 0] , has 1 (x3) and 0 (x3) , where 1 represents possible solution case and 0 represents failure.As we can compare for i = 3 and k = 5 from the question, we get total 3 possible ways.Hence there are 1 (x3) in the list, ways." }, { "code": null, "e": 27907, "s": 27837, "text": "for j in range(i, k+1):\n ways[j] += ways[j - 1] + ways[j - i]\n" }, { "code": null, "e": 28410, "s": 27907, "text": "Using the for loop we are iterating from i to 50, we have written k+1 since iterating in the loop through range() will exclude the last case.In ways[j] += ways[j – 1] + ways[j – i], we are updating the jth index of the list ways with the summation of (j-1) and (j+i)th index’s value and also the jth index value (Since +=).These are the possible values of j, for i=3 and k =5.Finally we return our list as return ways[k] – 1.So, for i=3 and k=5, this gives the solution(i.e, Ans = 3)Lastly in our code," }, { "code": null, "e": 28530, "s": 28410, "text": "print(\"Number of black tiles =\", k, \"units\")\nprint(\"Number of ways to fill:\", E_116(2, k) + E_116(3, k) + E_116(4, k))\n" }, { "code": null, "e": 28749, "s": 28530, "text": "We print away our result using the print() function. The first statement prints Number of black tiles = 50 and the second statement prints Number of ways to fill: 20492570929 which is the desired answer to the problem." }, { "code": "# Project Euler Problem 116 k = 50def E_116(i, k): ways = [1] * i + [0] * (k-i+1) for j in range(i, k+1): ways[j] += ways[j - 1] + ways[j - i] return ways[k] - 1 print(\"Number of black tiles =\", k, \"units\")print(\"Number of ways to fill:\", E_116(2, k) + E_116(3, k) + E_116(4, k))", "e": 29047, "s": 28749, "text": null }, { "code": null, "e": 29058, "s": 29047, "text": "Resources:" }, { "code": null, "e": 29071, "s": 29058, "text": "projecteuler" }, { "code": null, "e": 29096, "s": 29071, "text": "Java solution _ mathblog" }, { "code": null, "e": 29405, "s": 29096, "text": "This article is contributed by Amartya Ranjan Saikia. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 29530, "s": 29405, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 29554, "s": 29530, "text": "Competitive Programming" }, { "code": null, "e": 29573, "s": 29554, "text": "Technical Scripter" }, { "code": null, "e": 29671, "s": 29573, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29704, "s": 29671, "text": "Multistage Graph (Shortest Path)" }, { "code": null, "e": 29750, "s": 29704, "text": "Breadth First Traversal ( BFS ) on a 2D array" }, { "code": null, "e": 29831, "s": 29750, "text": "Check whether bitwise AND of a number with any subset of an array is zero or not" }, { "code": null, "e": 29889, "s": 29831, "text": "Shortest path in a directed graph by Dijkstra’s algorithm" }, { "code": null, "e": 29930, "s": 29889, "text": "5 Best Books for Competitive Programming" }, { "code": null, "e": 29975, "s": 29930, "text": "5 Best Languages for Competitive Programming" }, { "code": null, "e": 30009, "s": 29975, "text": "Most important type of Algorithms" }, { "code": null, "e": 30070, "s": 30009, "text": "Difference between Backtracking and Branch-N-Bound technique" }, { "code": null, "e": 30124, "s": 30070, "text": "String hashing using Polynomial rolling hash function" } ]
GRE Data Analysis | Distribution of Data, Random Variables, and Probability Distributions - GeeksforGeeks
19 Jun, 2019 The distribution of a statistical data set (or a population) is a listing or function showing all the possible values (or intervals) of the data and how often they occur, we can think of a distribution as a function that describes the relationship between observations in a sample space. Example:The lifetimes of 800 electric devices were measured. Because the lifetimes had many different values, the measurements were grouped into 50 intervals, or classes, of 10 hours each:601 to 610 hours, 611 to 620 hours, and so on, up to 1, 091 to 1, 100 hours. The resulting relative frequency distribution, as a histogram, has 50 thin bars and many different bar heights, as shown in Data Analysis Figure below. Relative frequency is how often something happens divided by all outcomes. As an example here, it can be considered as the number of electric devices having lifetime of (Ex 601 to 610) divided by the total devices.In the histogram, the median is represented by M, the mean is represented by m, and the standard deviation is represented by d. The median, represented by M, is between 730 and 740 The mean, represented by m, is between 750 and 760 The sum of areas of all 50 bars of relative frequency is 1 Histograms that represent very large data sets grouped into many classes have a relatively smooth appearance. Consequently, the distribution can be modeled by a smooth curve that is close to the tops of the bars. This curve is called a distribution curve. The purpose of the distribution curve is to give a good illustration of a large distribution of numerical data that does not depend on specific classes. Property of distribution curve is that the area under the curve in any vertical slice, just like a histogram bar, represents the proportion of the data that lies in the corresponding interval on the horizontal axis. A random variable can map each value from sample space to a real number and moreover sum of values from real number is always equal to 1 Example:In an experiment three fair coins are tossed, then sample space is S = { HHH, HHT, HTH, THH, HTT, TTH, THT, TTT} Let variable X count the number of times head turns up, hence we call it as Random variable. Moreover random variable is generally represented by X.Now, X can take values 3, 2, 1, 0 P(X = 1) is probability of occurring head one time, P(X = 1) = P(THT) + P(TTH) + P(HTT) = 3/8 Types of random variable: Discrete Random Variable:A variable that can take one value from a discrete set of values.Example:Let x denote the sum of dice, Now x is discrete random variable as it can take one value from the set { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }, since the sum of two dice can only be one of these values. Example:Let x denote the sum of dice, Now x is discrete random variable as it can take one value from the set { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }, since the sum of two dice can only be one of these values. Continuous Random Variable:A variable that can take one value from a continuous range of values.Example:x denotes the volume of water in a 500 ml cup. Now x may be a number from 0 to 500, any of which value, x may take. Example:x denotes the volume of water in a 500 ml cup. Now x may be a number from 0 to 500, any of which value, x may take. Probability distributions indicate the likelihood of an event or outcome.P(x) = the likelihood that random variable takes a specific value of x. Example:In an experiment three fair coins are tossed, then sample space is, S = {HHH, HHT, HTH, THH, HTT, TTH, THT, TTT} X is random variable having values 3, 2, 1, 0 then P(X = 0) = P(TTT) = 1/8 P(X = 1) = P(HTT) + P(TTH) + P(THT) = 3/8 P(X = 2) = P(HHT) + P(HTH) + P(THH) = 3/8 P(X = 3) = P(HHH) = 1/8 Therefore, This table is called the probability distribution of random variable X. Distribution can be divided into 2 types: Discrete distribution:Based on discrete random variable, examples are Binomial Distribution, Poisson Distribution.Continuous distribution:Based on continuous random variable, examples are Normal Distribution, Uniform Distribution, Exponential Distribution.Probability Mass Function:Let x be discrete random variable then its Probability Mass Function p(x) is defined such that1. p(x) 0 2. = 1 3. p(x) = P(X=x) Probability Density Function:Let x be continuous random variable then probability density function F(x) is defined such that1. F(x) 0 2. = 1 3. P(a < x < b) = Properties of Discrete Distribution:1. = 1 2. E(x) = 3. V(x) = Properties of Continuous Distribution:1. = 1 2. E(x) = 3. V(x) = 4. p(a < x < b) = Where,E(x) denotes expected value or average value of the random variable x,V(x) denotes the variance of the random variable x.Types of Distributions:Uniform DistributionExponential DistributionNormal DistributionBinomial DistributionPoisson DistributionMy Personal Notes arrow_drop_upSave Discrete distribution:Based on discrete random variable, examples are Binomial Distribution, Poisson Distribution. Continuous distribution:Based on continuous random variable, examples are Normal Distribution, Uniform Distribution, Exponential Distribution.Probability Mass Function:Let x be discrete random variable then its Probability Mass Function p(x) is defined such that1. p(x) 0 2. = 1 3. p(x) = P(X=x) Probability Density Function:Let x be continuous random variable then probability density function F(x) is defined such that1. F(x) 0 2. = 1 3. P(a < x < b) = Properties of Discrete Distribution:1. = 1 2. E(x) = 3. V(x) = Properties of Continuous Distribution:1. = 1 2. E(x) = 3. V(x) = 4. p(a < x < b) = Where,E(x) denotes expected value or average value of the random variable x,V(x) denotes the variance of the random variable x.Types of Distributions:Uniform DistributionExponential DistributionNormal DistributionBinomial DistributionPoisson DistributionMy Personal Notes arrow_drop_upSave Probability Mass Function:Let x be discrete random variable then its Probability Mass Function p(x) is defined such that 1. p(x) 0 2. = 1 3. p(x) = P(X=x) Probability Density Function:Let x be continuous random variable then probability density function F(x) is defined such that 1. F(x) 0 2. = 1 3. P(a < x < b) = Properties of Discrete Distribution: 1. = 1 2. E(x) = 3. V(x) = Properties of Continuous Distribution: 1. = 1 2. E(x) = 3. V(x) = 4. p(a < x < b) = Where,E(x) denotes expected value or average value of the random variable x,V(x) denotes the variance of the random variable x. Types of Distributions: Uniform Distribution Exponential Distribution Normal Distribution Binomial Distribution Poisson Distribution Aptitude Picked placement preparation GRE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Vocabulary for CAT and Aptitude Related Exams GRE Data Analysis | Counting Methods GRE Algebra | Rules of Exponent Vocabulary for CAT and Aptitude Related Exams | Set 2 GRE | List of words to enhance your vocabulary with alphabet ‘C’ GRE Data Analysis | Methods for Presenting Data GRE | List of words to enhance your vocabulary with alphabet 'M' GRE | List of words to enhance your vocabulary with root alphabet 'H' GRE | List of words to enhance your vocabulary with root alphabet ‘G’ Introduction of Graduate Record Examinations (GRE)
[ { "code": null, "e": 25561, "s": 25533, "text": "\n19 Jun, 2019" }, { "code": null, "e": 25849, "s": 25561, "text": "The distribution of a statistical data set (or a population) is a listing or function showing all the possible values (or intervals) of the data and how often they occur, we can think of a distribution as a function that describes the relationship between observations in a sample space." }, { "code": null, "e": 26266, "s": 25849, "text": "Example:The lifetimes of 800 electric devices were measured. Because the lifetimes had many different values, the measurements were grouped into 50 intervals, or classes, of 10 hours each:601 to 610 hours, 611 to 620 hours, and so on, up to 1, 091 to 1, 100 hours. The resulting relative frequency distribution, as a histogram, has 50 thin bars and many different bar heights, as shown in Data Analysis Figure below." }, { "code": null, "e": 26608, "s": 26266, "text": "Relative frequency is how often something happens divided by all outcomes. As an example here, it can be considered as the number of electric devices having lifetime of (Ex 601 to 610) divided by the total devices.In the histogram, the median is represented by M, the mean is represented by m, and the standard deviation is represented by d." }, { "code": null, "e": 26661, "s": 26608, "text": "The median, represented by M, is between 730 and 740" }, { "code": null, "e": 26712, "s": 26661, "text": "The mean, represented by m, is between 750 and 760" }, { "code": null, "e": 26771, "s": 26712, "text": "The sum of areas of all 50 bars of relative frequency is 1" }, { "code": null, "e": 27027, "s": 26771, "text": "Histograms that represent very large data sets grouped into many classes have a relatively smooth appearance. Consequently, the distribution can be modeled by a smooth curve that is close to the tops of the bars. This curve is called a distribution curve." }, { "code": null, "e": 27396, "s": 27027, "text": "The purpose of the distribution curve is to give a good illustration of a large distribution of numerical data that does not depend on specific classes. Property of distribution curve is that the area under the curve in any vertical slice, just like a histogram bar, represents the proportion of the data that lies in the corresponding interval on the horizontal axis." }, { "code": null, "e": 27533, "s": 27396, "text": "A random variable can map each value from sample space to a real number and moreover sum of values from real number is always equal to 1" }, { "code": null, "e": 27608, "s": 27533, "text": "Example:In an experiment three fair coins are tossed, then sample space is" }, { "code": null, "e": 27654, "s": 27608, "text": "S = { HHH, HHT, HTH, THH, HTT, TTH, THT, TTT}" }, { "code": null, "e": 27836, "s": 27654, "text": "Let variable X count the number of times head turns up, hence we call it as Random variable. Moreover random variable is generally represented by X.Now, X can take values 3, 2, 1, 0" }, { "code": null, "e": 27930, "s": 27836, "text": "P(X = 1) is probability of occurring head one time,\nP(X = 1) = P(THT) + P(TTH) + P(HTT) = 3/8" }, { "code": null, "e": 27956, "s": 27930, "text": "Types of random variable:" }, { "code": null, "e": 28255, "s": 27956, "text": "Discrete Random Variable:A variable that can take one value from a discrete set of values.Example:Let x denote the sum of dice, Now x is discrete random variable as it can take one value from the set { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }, since the sum of two dice can only be one of these values." }, { "code": null, "e": 28464, "s": 28255, "text": "Example:Let x denote the sum of dice, Now x is discrete random variable as it can take one value from the set { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }, since the sum of two dice can only be one of these values." }, { "code": null, "e": 28684, "s": 28464, "text": "Continuous Random Variable:A variable that can take one value from a continuous range of values.Example:x denotes the volume of water in a 500 ml cup. Now x may be a number from 0 to 500, any of which value, x may take." }, { "code": null, "e": 28808, "s": 28684, "text": "Example:x denotes the volume of water in a 500 ml cup. Now x may be a number from 0 to 500, any of which value, x may take." }, { "code": null, "e": 28953, "s": 28808, "text": "Probability distributions indicate the likelihood of an event or outcome.P(x) = the likelihood that random variable takes a specific value of x." }, { "code": null, "e": 29029, "s": 28953, "text": "Example:In an experiment three fair coins are tossed, then sample space is," }, { "code": null, "e": 29074, "s": 29029, "text": "S = {HHH, HHT, HTH, THH, HTT, TTH, THT, TTT}" }, { "code": null, "e": 29125, "s": 29074, "text": "X is random variable having values 3, 2, 1, 0 then" }, { "code": null, "e": 29258, "s": 29125, "text": "P(X = 0) = P(TTT) = 1/8\nP(X = 1) = P(HTT) + P(TTH) + P(THT) = 3/8\nP(X = 2) = P(HHT) + P(HTH) + P(THH) = 3/8\nP(X = 3) = P(HHH) = 1/8 " }, { "code": null, "e": 29269, "s": 29258, "text": "Therefore," }, { "code": null, "e": 29341, "s": 29269, "text": "This table is called the probability distribution of random variable X." }, { "code": null, "e": 29383, "s": 29341, "text": "Distribution can be divided into 2 types:" }, { "code": null, "e": 30399, "s": 29383, "text": "Discrete distribution:Based on discrete random variable, examples are Binomial Distribution, Poisson Distribution.Continuous distribution:Based on continuous random variable, examples are Normal Distribution, Uniform Distribution, Exponential Distribution.Probability Mass Function:Let x be discrete random variable then its Probability Mass Function p(x) is defined such that1. p(x) 0\n2. = 1\n3. p(x) = P(X=x) Probability Density Function:Let x be continuous random variable then probability density function F(x) is defined such that1. F(x) 0\n2. = 1\n3. P(a < x < b) = Properties of Discrete Distribution:1. = 1\n2. E(x) = \n3. V(x) = Properties of Continuous Distribution:1. = 1\n2. E(x) = \n3. V(x) = \n4. p(a < x < b) = Where,E(x) denotes expected value or average value of the random variable x,V(x) denotes the variance of the random variable x.Types of Distributions:Uniform DistributionExponential DistributionNormal DistributionBinomial DistributionPoisson DistributionMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 30514, "s": 30399, "text": "Discrete distribution:Based on discrete random variable, examples are Binomial Distribution, Poisson Distribution." }, { "code": null, "e": 31416, "s": 30514, "text": "Continuous distribution:Based on continuous random variable, examples are Normal Distribution, Uniform Distribution, Exponential Distribution.Probability Mass Function:Let x be discrete random variable then its Probability Mass Function p(x) is defined such that1. p(x) 0\n2. = 1\n3. p(x) = P(X=x) Probability Density Function:Let x be continuous random variable then probability density function F(x) is defined such that1. F(x) 0\n2. = 1\n3. P(a < x < b) = Properties of Discrete Distribution:1. = 1\n2. E(x) = \n3. V(x) = Properties of Continuous Distribution:1. = 1\n2. E(x) = \n3. V(x) = \n4. p(a < x < b) = Where,E(x) denotes expected value or average value of the random variable x,V(x) denotes the variance of the random variable x.Types of Distributions:Uniform DistributionExponential DistributionNormal DistributionBinomial DistributionPoisson DistributionMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 31537, "s": 31416, "text": "Probability Mass Function:Let x be discrete random variable then its Probability Mass Function p(x) is defined such that" }, { "code": null, "e": 31573, "s": 31537, "text": "1. p(x) 0\n2. = 1\n3. p(x) = P(X=x) " }, { "code": null, "e": 31698, "s": 31573, "text": "Probability Density Function:Let x be continuous random variable then probability density function F(x) is defined such that" }, { "code": null, "e": 31737, "s": 31698, "text": "1. F(x) 0\n2. = 1\n3. P(a < x < b) = " }, { "code": null, "e": 31774, "s": 31737, "text": "Properties of Discrete Distribution:" }, { "code": null, "e": 31805, "s": 31774, "text": "1. = 1\n2. E(x) = \n3. V(x) = " }, { "code": null, "e": 31844, "s": 31805, "text": "Properties of Continuous Distribution:" }, { "code": null, "e": 31894, "s": 31844, "text": "1. = 1\n2. E(x) = \n3. V(x) = \n4. p(a < x < b) = " }, { "code": null, "e": 32022, "s": 31894, "text": "Where,E(x) denotes expected value or average value of the random variable x,V(x) denotes the variance of the random variable x." }, { "code": null, "e": 32046, "s": 32022, "text": "Types of Distributions:" }, { "code": null, "e": 32067, "s": 32046, "text": "Uniform Distribution" }, { "code": null, "e": 32092, "s": 32067, "text": "Exponential Distribution" }, { "code": null, "e": 32112, "s": 32092, "text": "Normal Distribution" }, { "code": null, "e": 32134, "s": 32112, "text": "Binomial Distribution" }, { "code": null, "e": 32155, "s": 32134, "text": "Poisson Distribution" }, { "code": null, "e": 32164, "s": 32155, "text": "Aptitude" }, { "code": null, "e": 32171, "s": 32164, "text": "Picked" }, { "code": null, "e": 32193, "s": 32171, "text": "placement preparation" }, { "code": null, "e": 32197, "s": 32193, "text": "GRE" }, { "code": null, "e": 32295, "s": 32197, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32341, "s": 32295, "text": "Vocabulary for CAT and Aptitude Related Exams" }, { "code": null, "e": 32378, "s": 32341, "text": "GRE Data Analysis | Counting Methods" }, { "code": null, "e": 32410, "s": 32378, "text": "GRE Algebra | Rules of Exponent" }, { "code": null, "e": 32464, "s": 32410, "text": "Vocabulary for CAT and Aptitude Related Exams | Set 2" }, { "code": null, "e": 32529, "s": 32464, "text": "GRE | List of words to enhance your vocabulary with alphabet ‘C’" }, { "code": null, "e": 32577, "s": 32529, "text": "GRE Data Analysis | Methods for Presenting Data" }, { "code": null, "e": 32642, "s": 32577, "text": "GRE | List of words to enhance your vocabulary with alphabet 'M'" }, { "code": null, "e": 32712, "s": 32642, "text": "GRE | List of words to enhance your vocabulary with root alphabet 'H'" }, { "code": null, "e": 32782, "s": 32712, "text": "GRE | List of words to enhance your vocabulary with root alphabet ‘G’" } ]
Replace the column contains the values 'yes' and 'no' with True and False In Python-Pandas - GeeksforGeeks
28 Jul, 2020 Let’s discuss a program To change the values from a column that contains the values ‘YES’ and ‘NO’ with TRUE and FALSE. First, Let’s see a dataset. Code: Python3 # import pandas libraryimport pandas as pd # load csv filedf = pd.read_csv("supermarkets.csv") # show the dataframedf Output : For downloading the used csv file Click Here. Now, Let’s see the multiple ways to do this task: Method 1: Using Series.map(). This method is used to map values from two series having one column the same. Syntax: Series.map(arg, na_action=None). Return type: Pandas Series with the same as an index as a caller. Example: Replace the ‘commissioned’ column contains the values ‘yes’ and ‘no’ with True and False.Code: Python3 # import pandas libraryimport pandas as pd # load csv filedf = pd.read_csv("supermarkets.csv") # replace the ‘commissioned' column contains# the values 'yes' and 'no' with # True and False:df['commissioned'] = df['commissioned'].map( {'yes':True ,'no':False}) # show the dataframedf Output : Method 2: Using DataFrame.replace(). This method is used to replace a string, regex, list, dictionary, series, number, etc. from a data frame. Syntax: DataFrame.replace(to_replace=None, value=None, inplace=False, limit=None, regex=False, method=’pad’, axis=None) Return type: Updated Data frame Example: Replace the ‘commissioned’ column contains the values ‘yes’ and ‘no’ with True and False.Code: Python3 # import pandas libraryimport pandas as pd # load csv filedf = pd.read_csv("supermarkets.csv") # replace the ‘commissioned' column # contains the values 'yes' and 'no'# with True and False:df = df.replace({'commissioned': {'yes': True, 'no': False}}) # show the dataframedf Output: Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Convert integer to string in Python
[ { "code": null, "e": 26379, "s": 26351, "text": "\n28 Jul, 2020" }, { "code": null, "e": 26501, "s": 26379, "text": "Let’s discuss a program To change the values from a column that contains the values ‘YES’ and ‘NO’ with TRUE and FALSE. " }, { "code": null, "e": 26529, "s": 26501, "text": "First, Let’s see a dataset." }, { "code": null, "e": 26535, "s": 26529, "text": "Code:" }, { "code": null, "e": 26543, "s": 26535, "text": "Python3" }, { "code": "# import pandas libraryimport pandas as pd # load csv filedf = pd.read_csv(\"supermarkets.csv\") # show the dataframedf", "e": 26665, "s": 26543, "text": null }, { "code": null, "e": 26675, "s": 26665, "text": "Output : " }, { "code": null, "e": 26721, "s": 26675, "text": "For downloading the used csv file Click Here." }, { "code": null, "e": 26771, "s": 26721, "text": "Now, Let’s see the multiple ways to do this task:" }, { "code": null, "e": 26880, "s": 26771, "text": "Method 1: Using Series.map(). This method is used to map values from two series having one column the same. " }, { "code": null, "e": 26988, "s": 26880, "text": "Syntax: Series.map(arg, na_action=None). Return type: Pandas Series with the same as an index as a caller. " }, { "code": null, "e": 27092, "s": 26988, "text": "Example: Replace the ‘commissioned’ column contains the values ‘yes’ and ‘no’ with True and False.Code:" }, { "code": null, "e": 27100, "s": 27092, "text": "Python3" }, { "code": "# import pandas libraryimport pandas as pd # load csv filedf = pd.read_csv(\"supermarkets.csv\") # replace the ‘commissioned' column contains# the values 'yes' and 'no' with # True and False:df['commissioned'] = df['commissioned'].map( {'yes':True ,'no':False}) # show the dataframedf", "e": 27408, "s": 27100, "text": null }, { "code": null, "e": 27418, "s": 27408, "text": "Output : " }, { "code": null, "e": 27562, "s": 27418, "text": "Method 2: Using DataFrame.replace(). This method is used to replace a string, regex, list, dictionary, series, number, etc. from a data frame. " }, { "code": null, "e": 27715, "s": 27562, "text": "Syntax: DataFrame.replace(to_replace=None, value=None, inplace=False, limit=None, regex=False, method=’pad’, axis=None) Return type: Updated Data frame " }, { "code": null, "e": 27819, "s": 27715, "text": "Example: Replace the ‘commissioned’ column contains the values ‘yes’ and ‘no’ with True and False.Code:" }, { "code": null, "e": 27827, "s": 27819, "text": "Python3" }, { "code": "# import pandas libraryimport pandas as pd # load csv filedf = pd.read_csv(\"supermarkets.csv\") # replace the ‘commissioned' column # contains the values 'yes' and 'no'# with True and False:df = df.replace({'commissioned': {'yes': True, 'no': False}}) # show the dataframedf", "e": 28138, "s": 27827, "text": null }, { "code": null, "e": 28147, "s": 28138, "text": "Output: " }, { "code": null, "e": 28173, "s": 28149, "text": "Python pandas-dataFrame" }, { "code": null, "e": 28187, "s": 28173, "text": "Python-pandas" }, { "code": null, "e": 28194, "s": 28187, "text": "Python" }, { "code": null, "e": 28292, "s": 28194, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28310, "s": 28292, "text": "Python Dictionary" }, { "code": null, "e": 28345, "s": 28310, "text": "Read a file line by line in Python" }, { "code": null, "e": 28377, "s": 28345, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28399, "s": 28377, "text": "Enumerate() in Python" }, { "code": null, "e": 28441, "s": 28399, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28471, "s": 28441, "text": "Iterate over a list in Python" }, { "code": null, "e": 28497, "s": 28471, "text": "Python String | replace()" }, { "code": null, "e": 28526, "s": 28497, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28570, "s": 28526, "text": "Reading and Writing to text files in Python" } ]
ZonedDateTime format() method in Java with Examples - GeeksforGeeks
02 May, 2019 The format() method of ZonedDateTime class in Java is used to format this date-time using the specified formatter passed as parameter.This date-time will be passed to the formatter to produce a string. Syntax: public String format(DateTimeFormatter formatter) Parameters: This method accepts a single parameter formatter which represents the formatter to use. This is a mandatory parameter and should not be NULL. Return value: This method returns a String represents the formatted date-time string. Exception: This method throws a DateTimeException if an error occurs during printing. Below programs illustrate the format() method:Program 1: // Java program to demonstrate// ZonedDateTime.format() method import java.time.*;import java.time.format.*; public class GFG { public static void main(String[] args) { // create ZonedDateTime objects ZonedDateTime zoneddatetime = ZonedDateTime.parse("2018-12-06T19:21:12.123+05:30[Asia/Calcutta]"); // create a formatter DateTimeFormatter formatter = DateTimeFormatter.ISO_TIME; // apply format() String value = zoneddatetime.format(formatter); // print result System.out.println("Result: " + value); }} Result: 19:21:12.123+05:30 Program 2: // Java program to demonstrate// ZonedDateTime.format() method import java.time.*;import java.time.format.*; public class GFG { public static void main(String[] args) { // create ZonedDateTime objects ZonedDateTime zoneddatetime = ZonedDateTime.parse("2018-10-25T23:12:31.123+02:00[Europe/Paris]"); // create a formatter DateTimeFormatter formatter = DateTimeFormatter.BASIC_ISO_DATE; // apply format() String value = zoneddatetime.format(formatter); // print result System.out.println("Result: " + value); }} Result: 20181025+0200 Reference:https://docs.oracle.com/javase/10/docs/api/java/time/ZonedDateTime.html#format(java.time.format.DateTimeFormatter) Akanksha_Rai Java-Functions Java-time package Java-ZonedDateTime Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Stream In Java Interfaces in Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java
[ { "code": null, "e": 25763, "s": 25735, "text": "\n02 May, 2019" }, { "code": null, "e": 25965, "s": 25763, "text": "The format() method of ZonedDateTime class in Java is used to format this date-time using the specified formatter passed as parameter.This date-time will be passed to the formatter to produce a string." }, { "code": null, "e": 25973, "s": 25965, "text": "Syntax:" }, { "code": null, "e": 26024, "s": 25973, "text": "public String format(DateTimeFormatter formatter)\n" }, { "code": null, "e": 26178, "s": 26024, "text": "Parameters: This method accepts a single parameter formatter which represents the formatter to use. This is a mandatory parameter and should not be NULL." }, { "code": null, "e": 26264, "s": 26178, "text": "Return value: This method returns a String represents the formatted date-time string." }, { "code": null, "e": 26350, "s": 26264, "text": "Exception: This method throws a DateTimeException if an error occurs during printing." }, { "code": null, "e": 26407, "s": 26350, "text": "Below programs illustrate the format() method:Program 1:" }, { "code": "// Java program to demonstrate// ZonedDateTime.format() method import java.time.*;import java.time.format.*; public class GFG { public static void main(String[] args) { // create ZonedDateTime objects ZonedDateTime zoneddatetime = ZonedDateTime.parse(\"2018-12-06T19:21:12.123+05:30[Asia/Calcutta]\"); // create a formatter DateTimeFormatter formatter = DateTimeFormatter.ISO_TIME; // apply format() String value = zoneddatetime.format(formatter); // print result System.out.println(\"Result: \" + value); }}", "e": 26998, "s": 26407, "text": null }, { "code": null, "e": 27026, "s": 26998, "text": "Result: 19:21:12.123+05:30\n" }, { "code": null, "e": 27037, "s": 27026, "text": "Program 2:" }, { "code": "// Java program to demonstrate// ZonedDateTime.format() method import java.time.*;import java.time.format.*; public class GFG { public static void main(String[] args) { // create ZonedDateTime objects ZonedDateTime zoneddatetime = ZonedDateTime.parse(\"2018-10-25T23:12:31.123+02:00[Europe/Paris]\"); // create a formatter DateTimeFormatter formatter = DateTimeFormatter.BASIC_ISO_DATE; // apply format() String value = zoneddatetime.format(formatter); // print result System.out.println(\"Result: \" + value); }}", "e": 27633, "s": 27037, "text": null }, { "code": null, "e": 27656, "s": 27633, "text": "Result: 20181025+0200\n" }, { "code": null, "e": 27781, "s": 27656, "text": "Reference:https://docs.oracle.com/javase/10/docs/api/java/time/ZonedDateTime.html#format(java.time.format.DateTimeFormatter)" }, { "code": null, "e": 27794, "s": 27781, "text": "Akanksha_Rai" }, { "code": null, "e": 27809, "s": 27794, "text": "Java-Functions" }, { "code": null, "e": 27827, "s": 27809, "text": "Java-time package" }, { "code": null, "e": 27846, "s": 27827, "text": "Java-ZonedDateTime" }, { "code": null, "e": 27851, "s": 27846, "text": "Java" }, { "code": null, "e": 27856, "s": 27851, "text": "Java" }, { "code": null, "e": 27954, "s": 27856, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28005, "s": 27954, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 28035, "s": 28005, "text": "HashMap in Java with Examples" }, { "code": null, "e": 28050, "s": 28035, "text": "Stream In Java" }, { "code": null, "e": 28069, "s": 28050, "text": "Interfaces in Java" }, { "code": null, "e": 28100, "s": 28069, "text": "How to iterate any Map in Java" }, { "code": null, "e": 28118, "s": 28100, "text": "ArrayList in Java" }, { "code": null, "e": 28150, "s": 28118, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 28170, "s": 28150, "text": "Stack Class in Java" }, { "code": null, "e": 28202, "s": 28170, "text": "Multidimensional Arrays in Java" } ]
Python - Create UIs for prototyping Machine Learning model with Gradio - GeeksforGeeks
08 Sep, 2021 Gradio is an open-source python library which allows you to quickly create easy to use, customizable UI components for your ML model, any API, or any arbitrary function in just a few lines of code. You can integrate the GUI directly into your Python notebook, or you can share the link to anyone.Requirements : Example : We can create interfaces with Gradio using gradio.Interface() function. gradio.Interface(self, fn, inputs, outputs, examples=None, live=False, capture_session=False, title=None, description=None)Parameters : fn: (Callable)the function to wrap an interface. inputs: (Union[str, List[Union[str, AbstractInput]]]) a single Gradio input component, or list of Gradio input components. outputs: (Union[str, List[Union[str, AbstractOutput]]]) a single Gradio output component, or list of Gradio output components. live: (bool) whether the interface should automatically reload on change. capture_session: (bool) if True, captures the default graph and session (needed for Tensorflow 1.x) title: (str) a title for the interface; if provided, appears above the input and output components. description: (str) a description for the interface; if provided, appears above the input and output components. examples: (List[List[Any]]) sample inputs for the function; if provided, appears below the UI components and can be used to populate the interface. Should be nested list, in which the outer list consists of samples and each inner list consists of an input corresponding to each input component. UI for the interface can be generated by gradio.Interface, launch() function. gradio.Interface.launch(self, share=False)Parameters : share: (bool) - whether to create a publicly shareable link from your computer for the interface. There are several Input and Output Component given for the inputs and outputs parameter of gradio.Interface(). Code: function which returns the factorial of a number. Python3 def factorial(integer): """ Returns factorial of the given integer""" n = int(integer) if n<=1: return 1 fact=1 for i in range(1, n+1): fact*=i return fact Now, to wrap this function with gradio interface write following code in the same file. Python3 import gradiogradio.Interface(factorial, inputs="text", outputs="text").launch(share=True) When you run the above code cells in a jupyter notebook. It will generate a UI like this: You can also copy the link and share that to anyone, it will open the same UI in the browser. Now, we’ll show you how to make an interface for a Machine Learning model. For the demo, we’ll load a pre-trained Inception Net Image Classification model with tensorflow. Since this is an Image Classification model we’ll use Image input interface. We’ll output a dictionary of labels and their corresponding confidence scores with the Label output interface.Code: Python3 # imported necessary librariesimport gradio as grimport tensorflow as tfimport numpy as npimport requests # loading the modelinception_net = tf.keras.applications.InceptionV3() # Download human-readable labels.response = requests.get("https://git.io/JJkYN")labels = response.text.split("\n") def classify_image(image): """ Returns a dictionary with key as label and values as the predicted confidence for that label""" # reshaping the image image = image.reshape((-1, 299, 299, 3)) # preprocessing the image for inception_v3 image = tf.keras.applications.inception_v3.preprocess_input(image) # predicting the output prediction = inception_net.predict(image).flatten() return {labels[i]: float(prediction[i]) for i in range(1000)} # initializing the input componentimage = gr.inputs.Image(shape = (299, 299, 3))# initializing the output componentlabel = gr.outputs.Label(num_top_classes = 3) # launching the interfacegr.Interface(fn = classify_image, inputs = image, outputs = label, capture_session = True).launch() When you run the above code cell it will generate the UI like this: Here you can drag and drop the image in the left section of UI and click submit you will get the result like: Also if you copy the link and paste it in your browser, your interface will look like this: It is not localhost so you can open the same link on any device. For more information about input and output components checkout the Gradio’s documentation.Resource : Gradio’s documentation kk9826225 Python Framework Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Recurrent Neural Network Support Vector Machine Algorithm Intuition of Adam Optimizer CNN | Introduction to Pooling Layer Convolutional Neural Network (CNN) in Machine Learning 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": 25589, "s": 25561, "text": "\n08 Sep, 2021" }, { "code": null, "e": 25902, "s": 25589, "text": "Gradio is an open-source python library which allows you to quickly create easy to use, customizable UI components for your ML model, any API, or any arbitrary function in just a few lines of code. You can integrate the GUI directly into your Python notebook, or you can share the link to anyone.Requirements : " }, { "code": null, "e": 25916, "s": 25904, "text": "Example : " }, { "code": null, "e": 26135, "s": 25916, "text": "We can create interfaces with Gradio using gradio.Interface() function. gradio.Interface(self, fn, inputs, outputs, examples=None, live=False, capture_session=False, title=None, description=None)Parameters : " }, { "code": null, "e": 26184, "s": 26135, "text": "fn: (Callable)the function to wrap an interface." }, { "code": null, "e": 26307, "s": 26184, "text": "inputs: (Union[str, List[Union[str, AbstractInput]]]) a single Gradio input component, or list of Gradio input components." }, { "code": null, "e": 26434, "s": 26307, "text": "outputs: (Union[str, List[Union[str, AbstractOutput]]]) a single Gradio output component, or list of Gradio output components." }, { "code": null, "e": 26508, "s": 26434, "text": "live: (bool) whether the interface should automatically reload on change." }, { "code": null, "e": 26608, "s": 26508, "text": "capture_session: (bool) if True, captures the default graph and session (needed for Tensorflow 1.x)" }, { "code": null, "e": 26708, "s": 26608, "text": "title: (str) a title for the interface; if provided, appears above the input and output components." }, { "code": null, "e": 26820, "s": 26708, "text": "description: (str) a description for the interface; if provided, appears above the input and output components." }, { "code": null, "e": 27115, "s": 26820, "text": "examples: (List[List[Any]]) sample inputs for the function; if provided, appears below the UI components and can be used to populate the interface. Should be nested list, in which the outer list consists of samples and each inner list consists of an input corresponding to each input component." }, { "code": null, "e": 27250, "s": 27115, "text": "UI for the interface can be generated by gradio.Interface, launch() function. gradio.Interface.launch(self, share=False)Parameters : " }, { "code": null, "e": 27348, "s": 27250, "text": "share: (bool) - whether to create a publicly shareable link from your computer for the interface." }, { "code": null, "e": 27460, "s": 27348, "text": "There are several Input and Output Component given for the inputs and outputs parameter of gradio.Interface(). " }, { "code": null, "e": 27518, "s": 27460, "text": "Code: function which returns the factorial of a number. " }, { "code": null, "e": 27526, "s": 27518, "text": "Python3" }, { "code": "def factorial(integer): \"\"\" Returns factorial of the given integer\"\"\" n = int(integer) if n<=1: return 1 fact=1 for i in range(1, n+1): fact*=i return fact", "e": 27714, "s": 27526, "text": null }, { "code": null, "e": 27803, "s": 27714, "text": "Now, to wrap this function with gradio interface write following code in the same file. " }, { "code": null, "e": 27811, "s": 27803, "text": "Python3" }, { "code": "import gradiogradio.Interface(factorial, inputs=\"text\", outputs=\"text\").launch(share=True)", "e": 27902, "s": 27811, "text": null }, { "code": null, "e": 27994, "s": 27902, "text": "When you run the above code cells in a jupyter notebook. It will generate a UI like this: " }, { "code": null, "e": 28455, "s": 27994, "text": "You can also copy the link and share that to anyone, it will open the same UI in the browser. Now, we’ll show you how to make an interface for a Machine Learning model. For the demo, we’ll load a pre-trained Inception Net Image Classification model with tensorflow. Since this is an Image Classification model we’ll use Image input interface. We’ll output a dictionary of labels and their corresponding confidence scores with the Label output interface.Code: " }, { "code": null, "e": 28463, "s": 28455, "text": "Python3" }, { "code": "# imported necessary librariesimport gradio as grimport tensorflow as tfimport numpy as npimport requests # loading the modelinception_net = tf.keras.applications.InceptionV3() # Download human-readable labels.response = requests.get(\"https://git.io/JJkYN\")labels = response.text.split(\"\\n\") def classify_image(image): \"\"\" Returns a dictionary with key as label and values as the predicted confidence for that label\"\"\" # reshaping the image image = image.reshape((-1, 299, 299, 3)) # preprocessing the image for inception_v3 image = tf.keras.applications.inception_v3.preprocess_input(image) # predicting the output prediction = inception_net.predict(image).flatten() return {labels[i]: float(prediction[i]) for i in range(1000)} # initializing the input componentimage = gr.inputs.Image(shape = (299, 299, 3))# initializing the output componentlabel = gr.outputs.Label(num_top_classes = 3) # launching the interfacegr.Interface(fn = classify_image, inputs = image, outputs = label, capture_session = True).launch()", "e": 29518, "s": 28463, "text": null }, { "code": null, "e": 29588, "s": 29518, "text": "When you run the above code cell it will generate the UI like this: " }, { "code": null, "e": 29700, "s": 29588, "text": "Here you can drag and drop the image in the left section of UI and click submit you will get the result like: " }, { "code": null, "e": 29794, "s": 29700, "text": "Also if you copy the link and paste it in your browser, your interface will look like this: " }, { "code": null, "e": 29985, "s": 29794, "text": "It is not localhost so you can open the same link on any device. For more information about input and output components checkout the Gradio’s documentation.Resource : Gradio’s documentation " }, { "code": null, "e": 29995, "s": 29985, "text": "kk9826225" }, { "code": null, "e": 30012, "s": 29995, "text": "Python Framework" }, { "code": null, "e": 30029, "s": 30012, "text": "Machine Learning" }, { "code": null, "e": 30036, "s": 30029, "text": "Python" }, { "code": null, "e": 30053, "s": 30036, "text": "Machine Learning" }, { "code": null, "e": 30151, "s": 30053, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30192, "s": 30151, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 30225, "s": 30192, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 30253, "s": 30225, "text": "Intuition of Adam Optimizer" }, { "code": null, "e": 30289, "s": 30253, "text": "CNN | Introduction to Pooling Layer" }, { "code": null, "e": 30344, "s": 30289, "text": "Convolutional Neural Network (CNN) in Machine Learning" }, { "code": null, "e": 30372, "s": 30344, "text": "Read JSON file using Python" }, { "code": null, "e": 30422, "s": 30372, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 30444, "s": 30422, "text": "Python map() function" } ]
How to Use jQuery’s ajax() Function for Asynchronous HTTP Requests ? - GeeksforGeeks
04 Aug, 2021 In this article, we are going to see how we can use jQuery’s ajax() function to call backend function asynchronously or in other words HTTP Requests. AJAX is a set of web development techniques used by client-side frameworks and libraries to make asynchronous HTTP calls to the server. AJAX stands for “Asynchronous JavaScript and XML”. In simpler words, you can use Ajax to load data from backend without actually the page reloading. You can also send data to the server in the background, request data and receive data while the page has already loaded. Using ajax gives way better user experience on the application. Syntax: $.ajax(url); $.ajax(url,[options]); The following table lists downs commonly used options with ajax request. Creating a simple AJAX GET request Before we can use Ajax, we need to get jQuery in your application. For this article, we will use the Ajax jQuery script available online as in the code below. For the purpose of this article, we will be considering a JSON file where we will be sending an ajax() request and retrieve data from the file. Let’s consider that the JSON file named “data.json” is inside a folder named data which is in the root directory or in other words the folder where our html file currently is and has the data as shown below. Note: Remember that you need to be on localhost or some deployed path for ajax requests to work otherwise it will give you a CORS (Cross-Origin Resource Sharing) error. The data.json file: [ { "Name":"Aman Prakash Jha", "Occupation": "Student" }, { "Name":"Sharan Swaroop", "Occupation":"SDE-1" }, { "Name":"Chiraag Kakar", "Occupation":"Sr. Software Engineer" } ] Example: HTML <!DOCTYPE html><html> <head> <!--Loading the script so that we can use Ajax--> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script></head> <body> <h2>Welcome To GFG</h2> <p> Default code has been loaded into the Editor. </p> <button id="getData">GET</button> <script> $("#getData").click(function (event) { event.preventDefault(); $.ajax({ url: "data/data.json", type: "GET", dataType: "json", success: function (data) { // This here will print the // retrieved json on the console. console.log(data); }, error: function () { console.log("Something went wrong"); }, }); }); </script></body> </html> Output: [ { "Name":"Aman Prakash Jha", "Occupation": "Student" }, { "Name":"Sharan Swaroop", "Occupation":"SDE-1" }, { "Name":"Chiraag Kakar", "Occupation":"Sr. Software Engineer" } ] Sending a simple AJAX POST request Now let’s move on and try sending a “POST” request using the ajax() method. For this example, we will be using a simple python function written in flask-microframework which will receive the POST request from ajax() and simply return the data. If you wish to know more about flask you can read its official documentation here. Python from flask import Flask, redirect, render_template, request app = Flask(__name__) @app.route('/data/post_data/', methods = ["GET","POST"])def post_data(): '''Function which is supposed to process the POST request received from ajax''' data = None if request.method == "POST": '''Stores the Json file that is posted by ajax. This function simply returns the Json file it recieves.''' data = request.get_json() print(data) return ({"status":200, "data":data}) return render_template("post.html") if __name__ == '__main__': app.run(debug=True) Example: This is how you can set the HTML with ajax() for the “POST” request. HTML <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> </head> <body> <h2>Welcome To GFG</h2> <p>Default code has been loaded into the Editor.</p> <form method="POST"> <input type="text" placeholder="Name" id="name"> <button id="btn">POST</button> </form> <script> $("#btn").click(function(event){ event.preventDefault(); var name = $("#name").val(); $.ajax({ url:"/data/post_data/", type:"POST", contentType:"application/json", dataType:"json", data: JSON.stringify({ name: name, occupation: "SDE" }), success: function(data) { console.log(data) }, error: function(data ){ console.log("Something went wrong"); } }); }); </script> </body></html> Output: { data: {name: "Aman Prakash Jha", occupation: "SDE"}, status:200 } Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. jQuery-Methods jQuery-Questions Picked HTML JQuery Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? How to Upload Image into Database and Display it using PHP ? HTML | <img> align Attribute Types of CSS (Cascading Style Sheet) HTML Introduction JQuery | Set the value of an input text field How to prevent Body from scrolling when a modal is opened using jQuery ? Scroll to the top of the page using JavaScript/jQuery How to add options to a select element using jQuery? jQuery | children() with Examples
[ { "code": null, "e": 26526, "s": 26498, "text": "\n04 Aug, 2021" }, { "code": null, "e": 26863, "s": 26526, "text": "In this article, we are going to see how we can use jQuery’s ajax() function to call backend function asynchronously or in other words HTTP Requests. AJAX is a set of web development techniques used by client-side frameworks and libraries to make asynchronous HTTP calls to the server. AJAX stands for “Asynchronous JavaScript and XML”." }, { "code": null, "e": 27146, "s": 26863, "text": "In simpler words, you can use Ajax to load data from backend without actually the page reloading. You can also send data to the server in the background, request data and receive data while the page has already loaded. Using ajax gives way better user experience on the application." }, { "code": null, "e": 27154, "s": 27146, "text": "Syntax:" }, { "code": null, "e": 27190, "s": 27154, "text": "$.ajax(url);\n$.ajax(url,[options]);" }, { "code": null, "e": 27263, "s": 27190, "text": "The following table lists downs commonly used options with ajax request." }, { "code": null, "e": 27300, "s": 27265, "text": "Creating a simple AJAX GET request" }, { "code": null, "e": 27603, "s": 27300, "text": "Before we can use Ajax, we need to get jQuery in your application. For this article, we will use the Ajax jQuery script available online as in the code below. For the purpose of this article, we will be considering a JSON file where we will be sending an ajax() request and retrieve data from the file." }, { "code": null, "e": 27811, "s": 27603, "text": "Let’s consider that the JSON file named “data.json” is inside a folder named data which is in the root directory or in other words the folder where our html file currently is and has the data as shown below." }, { "code": null, "e": 27980, "s": 27811, "text": "Note: Remember that you need to be on localhost or some deployed path for ajax requests to work otherwise it will give you a CORS (Cross-Origin Resource Sharing) error." }, { "code": null, "e": 28000, "s": 27980, "text": "The data.json file:" }, { "code": null, "e": 28248, "s": 28000, "text": "[\n {\n \"Name\":\"Aman Prakash Jha\",\n \"Occupation\": \"Student\"\n },\n {\n \"Name\":\"Sharan Swaroop\",\n \"Occupation\":\"SDE-1\"\n },\n {\n \"Name\":\"Chiraag Kakar\",\n \"Occupation\":\"Sr. Software Engineer\"\n }\n]" }, { "code": null, "e": 28257, "s": 28248, "text": "Example:" }, { "code": null, "e": 28262, "s": 28257, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <!--Loading the script so that we can use Ajax--> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script></head> <body> <h2>Welcome To GFG</h2> <p> Default code has been loaded into the Editor. </p> <button id=\"getData\">GET</button> <script> $(\"#getData\").click(function (event) { event.preventDefault(); $.ajax({ url: \"data/data.json\", type: \"GET\", dataType: \"json\", success: function (data) { // This here will print the // retrieved json on the console. console.log(data); }, error: function () { console.log(\"Something went wrong\"); }, }); }); </script></body> </html>", "e": 29205, "s": 28262, "text": null }, { "code": null, "e": 29215, "s": 29207, "text": "Output:" }, { "code": null, "e": 29463, "s": 29215, "text": "[\n {\n \"Name\":\"Aman Prakash Jha\",\n \"Occupation\": \"Student\"\n },\n {\n \"Name\":\"Sharan Swaroop\",\n \"Occupation\":\"SDE-1\"\n },\n {\n \"Name\":\"Chiraag Kakar\",\n \"Occupation\":\"Sr. Software Engineer\"\n }\n]" }, { "code": null, "e": 29498, "s": 29463, "text": "Sending a simple AJAX POST request" }, { "code": null, "e": 29574, "s": 29498, "text": "Now let’s move on and try sending a “POST” request using the ajax() method." }, { "code": null, "e": 29825, "s": 29574, "text": "For this example, we will be using a simple python function written in flask-microframework which will receive the POST request from ajax() and simply return the data. If you wish to know more about flask you can read its official documentation here." }, { "code": null, "e": 29832, "s": 29825, "text": "Python" }, { "code": "from flask import Flask, redirect, render_template, request app = Flask(__name__) @app.route('/data/post_data/', methods = [\"GET\",\"POST\"])def post_data(): '''Function which is supposed to process the POST request received from ajax''' data = None if request.method == \"POST\": '''Stores the Json file that is posted by ajax. This function simply returns the Json file it recieves.''' data = request.get_json() print(data) return ({\"status\":200, \"data\":data}) return render_template(\"post.html\") if __name__ == '__main__': app.run(debug=True)", "e": 30438, "s": 29832, "text": null }, { "code": null, "e": 30516, "s": 30438, "text": "Example: This is how you can set the HTML with ajax() for the “POST” request." }, { "code": null, "e": 30521, "s": 30516, "text": "HTML" }, { "code": "<html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> </head> <body> <h2>Welcome To GFG</h2> <p>Default code has been loaded into the Editor.</p> <form method=\"POST\"> <input type=\"text\" placeholder=\"Name\" id=\"name\"> <button id=\"btn\">POST</button> </form> <script> $(\"#btn\").click(function(event){ event.preventDefault(); var name = $(\"#name\").val(); $.ajax({ url:\"/data/post_data/\", type:\"POST\", contentType:\"application/json\", dataType:\"json\", data: JSON.stringify({ name: name, occupation: \"SDE\" }), success: function(data) { console.log(data) }, error: function(data ){ console.log(\"Something went wrong\"); } }); }); </script> </body></html>", "e": 31531, "s": 30521, "text": null }, { "code": null, "e": 31539, "s": 31531, "text": "Output:" }, { "code": null, "e": 31615, "s": 31539, "text": "{\n data: {name: \"Aman Prakash Jha\", occupation: \"SDE\"},\n status:200\n}" }, { "code": null, "e": 31752, "s": 31615, "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": 31767, "s": 31752, "text": "jQuery-Methods" }, { "code": null, "e": 31784, "s": 31767, "text": "jQuery-Questions" }, { "code": null, "e": 31791, "s": 31784, "text": "Picked" }, { "code": null, "e": 31796, "s": 31791, "text": "HTML" }, { "code": null, "e": 31803, "s": 31796, "text": "JQuery" }, { "code": null, "e": 31820, "s": 31803, "text": "Web Technologies" }, { "code": null, "e": 31825, "s": 31820, "text": "HTML" }, { "code": null, "e": 31923, "s": 31825, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31971, "s": 31923, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 32032, "s": 31971, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 32061, "s": 32032, "text": "HTML | <img> align Attribute" }, { "code": null, "e": 32098, "s": 32061, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 32116, "s": 32098, "text": "HTML Introduction" }, { "code": null, "e": 32162, "s": 32116, "text": "JQuery | Set the value of an input text field" }, { "code": null, "e": 32235, "s": 32162, "text": "How to prevent Body from scrolling when a modal is opened using jQuery ?" }, { "code": null, "e": 32289, "s": 32235, "text": "Scroll to the top of the page using JavaScript/jQuery" }, { "code": null, "e": 32342, "s": 32289, "text": "How to add options to a select element using jQuery?" } ]
Number of Digits in a^b - GeeksforGeeks
06 Apr, 2021 Given two positive integers a and b, task is to find the number of digits in a^b (a raised to the power b).Example: Input: a = 2 b = 5 Output: no. of digits = 2 Explanation: 2^5 = 32 Hence, no. of digits = 2 Input: a = 2 b = 100 Output: no. of digits = 31 Explanation: 2^100 = 1.2676506e+30 Hence, no. of digits = 31 Approach: The number of digits in a^b can be calculated using the formula: Number of Digits = 1 + b * (log10a) When a number is divided by 10, it is reduced by 1 digit. Example: 554 / 10 = 55, 55 / 10 = 5 Notice, 554 initially has 3 digits but after division there are 2 digits 55 and after further division there is only 1 digit 5. So it can be concluded that to count number of digits, how many times a number is divided by 10 to reach 1 needs to be calculated. log base 10 of a number is the number of times a number needs to be divided by 10 to reach 1 but as 1 itself is not included in log base 10, 1 is added to get the number of digits. Note: Floor value of b * (log10a) is taken.Below is the implementation to calculate the number of digits in a^b. CPP Java Python3 C# PHP Javascript // CPP Program to calculate// no. of digits in a^b#include<iostream>#include<math.h>using namespace std; // function to calculate number// of digits in a^bint no_of_digit(int a, int b){ return ((int)(b * log10(a)) + 1);} // driver programint main(){ int a = 2, b = 100; cout <<"no. of digits = "<< no_of_digit(a, b);} // This code is contributed by Smitha // Java Program to calculate// no. of digits in a^bclass GFG { // function to calculate number // of digits in a^b static int no_of_digit(int a, int b) { return ((int)(b * Math.log10(a)) + 1); } // driver program public static void main(String[] args) { int a = 2, b = 100; System.out.print("no. of digits = " + no_of_digit(a, b)); }} # Python Program to calculate# no. of digits in a^bimport math # function to calculate number# of digits in a^bdef no_of_digit(a, b): return ((int)(b * math.log10(a)) + 1) # Driver Programa = 2b = 100print("no of digits = ", no_of_digit(a, b)) # This code is contributed by Shrikant13 // C# Program to calculate// no. of digits in a^busing System; class GFG { // function to calculate number // of digits in a^b static int no_of_digit(int a, int b) { return ((int)(b * Math.Log10(a)) + 1); } // driver program public static void Main() { int a = 2, b = 100; Console.Write("no. of digits = " + no_of_digit(a, b)); }} // This code is contributed by Smitha. <?php// PHP Program to calculate// no. of digits in a^b // function to calculate number// of digits in a^bfunction no_of_digit($a, $b){ return ((int)($b * log10($a)) + 1);} // Driver Code$a = 2; $b = 100;echo("no. of digits = " .no_of_digit($a, $b)); // This code is contributed by Ajit.?> <script> // JavaScript Program to calculate// no. of digits in a^b // function to calculate number // of digits in a^b function no_of_digit(a, b) { return (Math.round((b * Math.log10(a)) + 1)); } // Driver program let a = 2, b = 100; document.write("no. of digits = " + no_of_digit(a, b)); // This code is contributed by susmitakundugoaldanga.</script> Output: no.of digits = 31 shrikanth13 jit_t Smitha Dinesh Semwal susmitakundugoaldanga number-digits Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Print all possible combinations of r elements in a given array of size n Operators in C / C++ The Knight's tour problem | Backtracking-1 Program for factorial of a number Program for Decimal to Binary Conversion Find minimum number of coins that make a given value Program to find sum of elements in a given array
[ { "code": null, "e": 26311, "s": 26283, "text": "\n06 Apr, 2021" }, { "code": null, "e": 26429, "s": 26311, "text": "Given two positive integers a and b, task is to find the number of digits in a^b (a raised to the power b).Example: " }, { "code": null, "e": 26634, "s": 26429, "text": "Input: a = 2 b = 5\nOutput: no. of digits = 2\nExplanation:\n2^5 = 32 \nHence, no. of digits = 2\n\nInput: a = 2 b = 100\nOutput: no. of digits = 31\nExplanation:\n2^100 = 1.2676506e+30\nHence, no. of digits = 31" }, { "code": null, "e": 26713, "s": 26636, "text": "Approach: The number of digits in a^b can be calculated using the formula: " }, { "code": null, "e": 26749, "s": 26713, "text": "Number of Digits = 1 + b * (log10a)" }, { "code": null, "e": 26817, "s": 26749, "text": "When a number is divided by 10, it is reduced by 1 digit. Example: " }, { "code": null, "e": 26844, "s": 26817, "text": "554 / 10 = 55, 55 / 10 = 5" }, { "code": null, "e": 27399, "s": 26844, "text": "Notice, 554 initially has 3 digits but after division there are 2 digits 55 and after further division there is only 1 digit 5. So it can be concluded that to count number of digits, how many times a number is divided by 10 to reach 1 needs to be calculated. log base 10 of a number is the number of times a number needs to be divided by 10 to reach 1 but as 1 itself is not included in log base 10, 1 is added to get the number of digits. Note: Floor value of b * (log10a) is taken.Below is the implementation to calculate the number of digits in a^b. " }, { "code": null, "e": 27403, "s": 27399, "text": "CPP" }, { "code": null, "e": 27408, "s": 27403, "text": "Java" }, { "code": null, "e": 27416, "s": 27408, "text": "Python3" }, { "code": null, "e": 27419, "s": 27416, "text": "C#" }, { "code": null, "e": 27423, "s": 27419, "text": "PHP" }, { "code": null, "e": 27434, "s": 27423, "text": "Javascript" }, { "code": "// CPP Program to calculate// no. of digits in a^b#include<iostream>#include<math.h>using namespace std; // function to calculate number// of digits in a^bint no_of_digit(int a, int b){ return ((int)(b * log10(a)) + 1);} // driver programint main(){ int a = 2, b = 100; cout <<\"no. of digits = \"<< no_of_digit(a, b);} // This code is contributed by Smitha", "e": 27820, "s": 27434, "text": null }, { "code": "// Java Program to calculate// no. of digits in a^bclass GFG { // function to calculate number // of digits in a^b static int no_of_digit(int a, int b) { return ((int)(b * Math.log10(a)) + 1); } // driver program public static void main(String[] args) { int a = 2, b = 100; System.out.print(\"no. of digits = \" + no_of_digit(a, b)); }}", "e": 28238, "s": 27820, "text": null }, { "code": "# Python Program to calculate# no. of digits in a^bimport math # function to calculate number# of digits in a^bdef no_of_digit(a, b): return ((int)(b * math.log10(a)) + 1) # Driver Programa = 2b = 100print(\"no of digits = \", no_of_digit(a, b)) # This code is contributed by Shrikant13", "e": 28526, "s": 28238, "text": null }, { "code": "// C# Program to calculate// no. of digits in a^busing System; class GFG { // function to calculate number // of digits in a^b static int no_of_digit(int a, int b) { return ((int)(b * Math.Log10(a)) + 1); } // driver program public static void Main() { int a = 2, b = 100; Console.Write(\"no. of digits = \" + no_of_digit(a, b)); }} // This code is contributed by Smitha.", "e": 28977, "s": 28526, "text": null }, { "code": "<?php// PHP Program to calculate// no. of digits in a^b // function to calculate number// of digits in a^bfunction no_of_digit($a, $b){ return ((int)($b * log10($a)) + 1);} // Driver Code$a = 2; $b = 100;echo(\"no. of digits = \" .no_of_digit($a, $b)); // This code is contributed by Ajit.?>", "e": 29274, "s": 28977, "text": null }, { "code": "<script> // JavaScript Program to calculate// no. of digits in a^b // function to calculate number // of digits in a^b function no_of_digit(a, b) { return (Math.round((b * Math.log10(a)) + 1)); } // Driver program let a = 2, b = 100; document.write(\"no. of digits = \" + no_of_digit(a, b)); // This code is contributed by susmitakundugoaldanga.</script>", "e": 29703, "s": 29274, "text": null }, { "code": null, "e": 29713, "s": 29703, "text": "Output: " }, { "code": null, "e": 29731, "s": 29713, "text": "no.of digits = 31" }, { "code": null, "e": 29745, "s": 29733, "text": "shrikanth13" }, { "code": null, "e": 29751, "s": 29745, "text": "jit_t" }, { "code": null, "e": 29772, "s": 29751, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 29794, "s": 29772, "text": "susmitakundugoaldanga" }, { "code": null, "e": 29808, "s": 29794, "text": "number-digits" }, { "code": null, "e": 29821, "s": 29808, "text": "Mathematical" }, { "code": null, "e": 29834, "s": 29821, "text": "Mathematical" }, { "code": null, "e": 29932, "s": 29834, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29956, "s": 29932, "text": "Merge two sorted arrays" }, { "code": null, "e": 29999, "s": 29956, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 30013, "s": 29999, "text": "Prime Numbers" }, { "code": null, "e": 30086, "s": 30013, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 30107, "s": 30086, "text": "Operators in C / C++" }, { "code": null, "e": 30150, "s": 30107, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 30184, "s": 30150, "text": "Program for factorial of a number" }, { "code": null, "e": 30225, "s": 30184, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 30278, "s": 30225, "text": "Find minimum number of coins that make a given value" } ]
Difference between CSS Grid and CSS Flexbox - GeeksforGeeks
05 Mar, 2021 Grid:CSS Grid Layout, is a two-dimensional grid-based layout system with rows and columns, making it easier to design web pages without having to use floats and positioning. Like tables, grid layout allow us to align elements into columns and rows. To get started you have to define a container element as a grid with display: grid, set the column and row sizes with grid-template-columns and grid-template-rows, and then place its child elements into the grid with grid-column and grid-row. Example: HTML <!DOCTYPE html><html lang="en"><head> <style> .main{ display: grid; display: grid; grid: auto auto / auto auto auto auto; grid-gap: 10px; background-color: green; padding: 10px; } .gfg { background-color: rgb(255, 255, 255); text-align: center; padding: 25px 0; font-size: 30px; } </style></head><body> <h2 style="text-align: center;">Welcome To GeeksForGeeks </h2> <div class="main"> <div class="gfg">Home</div> <div class="gfg">Read</div> <div class="gfg">Write</div> <div class="gfg">About Us</div> <div class="gfg">Contact Us</div> <div class="gfg">Privacy Policy</div> </div></body></html> Flexbox: The CSS Flexbox offers a one-dimensional layout. It is helpful in allocating and aligning the space among items in a container (made of grids). It works with all kinds of display devices and screen sizes. To get started you have to define a container element as a grid with display: flex; Example: HTML <!DOCTYPE html><html lang="en"><head> <style> .main{ display: flex; display: flex; grid: auto auto / auto auto auto auto; grid-gap: 10px; background-color: green; padding: 10px; } .gfg { background-color: rgb(255, 255, 255); text-align: center; padding: 25px 0; font-size: 30px; } </style></head><body> <h2 style="text-align: center;">Welcome To GeeksForGeeks </h2> <div class="main"> <div class="gfg">Home</div> <div class="gfg">Read</div> <div class="gfg">Write</div> <div class="gfg">About Us</div> <div class="gfg">Contact Us</div> <div class="gfg">Privacy Policy</div> </div></body></html> Uniqueness In Grid And Flexbox: One Vs Two Dimension: Grid is made for two-dimensional layout while Flexbox is for one. This means Flexbox can work on either row or columns at a time, but Grids can work on both. Flexbox, gives you more flexibility while working on either element (row or column). HTML markup and CSS will be easy to manage in this type of scenario. GRID gives you more flexibility to move around the blocks irrespective of your HTML markup. Content-First vs Layout-First: Major Uniqueness between Flexbox and Grids is that the former works on content while the latter is based on the layout. The Flexbox layout is best suited to application components and small-scale layouts, while the Grid layout is designed for larger-scale layouts that are not linear in design. Difference Between Grid and Flexbox: 1. Dimensionality and Flexibility: Flexbox offers greater control over alignment and space distribution between items. Being one-dimensional, Flexbox only deals with either columns or rows. Grid has two-dimension layout capabilities which allow flexible widths as a unit of length. This compensates for the limitations in Flex. 2. Alignment: Flex Direction allows developers to align elements vertically or horizontally, which is used when developers create and reverse rows or columns. CSS Grid deploys fractional measure units for grid fluidity and auto-keyword functionality to automatically adjust columns or rows. 3. Item Management Flex Container is the parent element while Flex Item represents the children. The Flex Container can ensure balanced representation by adjusting item dimensions. This allows developers to design for fluctuating screen sizes. Grid supports both implicit and explicit content placement. Its inbuilt automation allows it to automatically extend line items and copy values into the new creation from the preceding item. Property Grid Flexbox Dimension Two – Dimensional One – Dimensional Features Can flex combination of items through space-occupying Features Can push content element to extreme alignment Support Type Layout First Content First Conclusion CSS Grids helps you create the outer layout of the webpage. You can build complex as well responsive design with this. This is why it is called ‘layout first’. Flexbox mostly helps align content & move blocks. CSS grids are for 2D layouts. It works with both rows and columns. Flexbox works better in one dimension only (either rows OR columns). It will be more time saving and helpful if you use both at the same time. CSS-Properties Picked Technical Scripter 2020 CSS Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to apply style to parent if it has child with CSS? How to position a div at the bottom of its container using CSS? How to set space between the flexbox ? Design a web page using HTML and CSS How to Upload Image into Database and Display it using PHP ? Create a Responsive Navbar using ReactJS Making a div vertically scrollable using CSS Form validation using jQuery CSS | :not(:last-child):after Selector How to select all child elements recursively using CSS?
[ { "code": null, "e": 25923, "s": 25895, "text": "\n05 Mar, 2021" }, { "code": null, "e": 26172, "s": 25923, "text": "Grid:CSS Grid Layout, is a two-dimensional grid-based layout system with rows and columns, making it easier to design web pages without having to use floats and positioning. Like tables, grid layout allow us to align elements into columns and rows." }, { "code": null, "e": 26415, "s": 26172, "text": "To get started you have to define a container element as a grid with display: grid, set the column and row sizes with grid-template-columns and grid-template-rows, and then place its child elements into the grid with grid-column and grid-row." }, { "code": null, "e": 26424, "s": 26415, "text": "Example:" }, { "code": null, "e": 26429, "s": 26424, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <style> .main{ display: grid; display: grid; grid: auto auto / auto auto auto auto; grid-gap: 10px; background-color: green; padding: 10px; } .gfg { background-color: rgb(255, 255, 255); text-align: center; padding: 25px 0; font-size: 30px; } </style></head><body> <h2 style=\"text-align: center;\">Welcome To GeeksForGeeks </h2> <div class=\"main\"> <div class=\"gfg\">Home</div> <div class=\"gfg\">Read</div> <div class=\"gfg\">Write</div> <div class=\"gfg\">About Us</div> <div class=\"gfg\">Contact Us</div> <div class=\"gfg\">Privacy Policy</div> </div></body></html>", "e": 27244, "s": 26429, "text": null }, { "code": null, "e": 27458, "s": 27244, "text": "Flexbox: The CSS Flexbox offers a one-dimensional layout. It is helpful in allocating and aligning the space among items in a container (made of grids). It works with all kinds of display devices and screen sizes." }, { "code": null, "e": 27542, "s": 27458, "text": "To get started you have to define a container element as a grid with display: flex;" }, { "code": null, "e": 27551, "s": 27542, "text": "Example:" }, { "code": null, "e": 27556, "s": 27551, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <style> .main{ display: flex; display: flex; grid: auto auto / auto auto auto auto; grid-gap: 10px; background-color: green; padding: 10px; } .gfg { background-color: rgb(255, 255, 255); text-align: center; padding: 25px 0; font-size: 30px; } </style></head><body> <h2 style=\"text-align: center;\">Welcome To GeeksForGeeks </h2> <div class=\"main\"> <div class=\"gfg\">Home</div> <div class=\"gfg\">Read</div> <div class=\"gfg\">Write</div> <div class=\"gfg\">About Us</div> <div class=\"gfg\">Contact Us</div> <div class=\"gfg\">Privacy Policy</div> </div></body></html>", "e": 28371, "s": 27556, "text": null }, { "code": null, "e": 28403, "s": 28371, "text": "Uniqueness In Grid And Flexbox:" }, { "code": null, "e": 28425, "s": 28403, "text": "One Vs Two Dimension:" }, { "code": null, "e": 28583, "s": 28425, "text": "Grid is made for two-dimensional layout while Flexbox is for one. This means Flexbox can work on either row or columns at a time, but Grids can work on both." }, { "code": null, "e": 28737, "s": 28583, "text": "Flexbox, gives you more flexibility while working on either element (row or column). HTML markup and CSS will be easy to manage in this type of scenario." }, { "code": null, "e": 28829, "s": 28737, "text": "GRID gives you more flexibility to move around the blocks irrespective of your HTML markup." }, { "code": null, "e": 28860, "s": 28829, "text": "Content-First vs Layout-First:" }, { "code": null, "e": 28980, "s": 28860, "text": "Major Uniqueness between Flexbox and Grids is that the former works on content while the latter is based on the layout." }, { "code": null, "e": 29155, "s": 28980, "text": "The Flexbox layout is best suited to application components and small-scale layouts, while the Grid layout is designed for larger-scale layouts that are not linear in design." }, { "code": null, "e": 29192, "s": 29155, "text": "Difference Between Grid and Flexbox:" }, { "code": null, "e": 29227, "s": 29192, "text": "1. Dimensionality and Flexibility:" }, { "code": null, "e": 29382, "s": 29227, "text": "Flexbox offers greater control over alignment and space distribution between items. Being one-dimensional, Flexbox only deals with either columns or rows." }, { "code": null, "e": 29520, "s": 29382, "text": "Grid has two-dimension layout capabilities which allow flexible widths as a unit of length. This compensates for the limitations in Flex." }, { "code": null, "e": 29534, "s": 29520, "text": "2. Alignment:" }, { "code": null, "e": 29679, "s": 29534, "text": "Flex Direction allows developers to align elements vertically or horizontally, which is used when developers create and reverse rows or columns." }, { "code": null, "e": 29811, "s": 29679, "text": "CSS Grid deploys fractional measure units for grid fluidity and auto-keyword functionality to automatically adjust columns or rows." }, { "code": null, "e": 29830, "s": 29811, "text": "3. Item Management" }, { "code": null, "e": 30055, "s": 29830, "text": "Flex Container is the parent element while Flex Item represents the children. The Flex Container can ensure balanced representation by adjusting item dimensions. This allows developers to design for fluctuating screen sizes." }, { "code": null, "e": 30246, "s": 30055, "text": "Grid supports both implicit and explicit content placement. Its inbuilt automation allows it to automatically extend line items and copy values into the new creation from the preceding item." }, { "code": null, "e": 30255, "s": 30246, "text": "Property" }, { "code": null, "e": 30260, "s": 30255, "text": "Grid" }, { "code": null, "e": 30268, "s": 30260, "text": "Flexbox" }, { "code": null, "e": 30278, "s": 30268, "text": "Dimension" }, { "code": null, "e": 30296, "s": 30278, "text": "Two – Dimensional" }, { "code": null, "e": 30314, "s": 30296, "text": "One – Dimensional" }, { "code": null, "e": 30323, "s": 30314, "text": "Features" }, { "code": null, "e": 30386, "s": 30323, "text": "Can flex combination of items through space-occupying Features" }, { "code": null, "e": 30432, "s": 30386, "text": "Can push content element to extreme alignment" }, { "code": null, "e": 30445, "s": 30432, "text": "Support Type" }, { "code": null, "e": 30458, "s": 30445, "text": "Layout First" }, { "code": null, "e": 30472, "s": 30458, "text": "Content First" }, { "code": null, "e": 30483, "s": 30472, "text": "Conclusion" }, { "code": null, "e": 30643, "s": 30483, "text": "CSS Grids helps you create the outer layout of the webpage. You can build complex as well responsive design with this. This is why it is called ‘layout first’." }, { "code": null, "e": 30693, "s": 30643, "text": "Flexbox mostly helps align content & move blocks." }, { "code": null, "e": 30760, "s": 30693, "text": "CSS grids are for 2D layouts. It works with both rows and columns." }, { "code": null, "e": 30829, "s": 30760, "text": "Flexbox works better in one dimension only (either rows OR columns)." }, { "code": null, "e": 30903, "s": 30829, "text": "It will be more time saving and helpful if you use both at the same time." }, { "code": null, "e": 30918, "s": 30903, "text": "CSS-Properties" }, { "code": null, "e": 30925, "s": 30918, "text": "Picked" }, { "code": null, "e": 30949, "s": 30925, "text": "Technical Scripter 2020" }, { "code": null, "e": 30953, "s": 30949, "text": "CSS" }, { "code": null, "e": 30972, "s": 30953, "text": "Technical Scripter" }, { "code": null, "e": 31070, "s": 30972, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31125, "s": 31070, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 31189, "s": 31125, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 31228, "s": 31189, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 31265, "s": 31228, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 31326, "s": 31265, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 31367, "s": 31326, "text": "Create a Responsive Navbar using ReactJS" }, { "code": null, "e": 31412, "s": 31367, "text": "Making a div vertically scrollable using CSS" }, { "code": null, "e": 31441, "s": 31412, "text": "Form validation using jQuery" }, { "code": null, "e": 31480, "s": 31441, "text": "CSS | :not(:last-child):after Selector" } ]
Check if two Linked Lists are permutations of each other - GeeksforGeeks
29 Jun, 2021 Given two singly Linked list of integer data. The task is to write a program that efficiently checks if two linked lists are permutations of each other. Examples: Input: 1 -> 2 -> 3 -> 4 -> 5 2 -> 1 -> 3 -> 5 -> 4 Output: Yes Input: 10 -> 20 -> 30 -> 40 20 -> 50 -> 60 -> 70 Output: No Approach: Do the following for both linked lists: Take a temporary node pointing to the head of the linked list.Start traversing through the linked list, and keep sum and multiplications of data of nodes. Take a temporary node pointing to the head of the linked list. Start traversing through the linked list, and keep sum and multiplications of data of nodes. Note : After having sum and multiplication of both linked list, check if sum and multiplication of both linked lists are equal. If they are equal, it means linked lists are permutations of each other, else not. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to check if linked lists// are permutations of each other#include <bits/stdc++.h> using namespace std; // A linked list nodestruct Node { int data; struct Node* next;}; /*Function to check if two linked lists* are permutations of each other* first : reference to head of first linked list* second : reference to head of second linked list*/bool isPermutation(struct Node* first, struct Node* second){ // Variables to keep track of sum and multiplication int sum1 = 0, sum2 = 0, mul1 = 1, mul2 = 1; struct Node* temp1 = first; // Traversing through linked list // and calculating sum and multiply while (temp1 != NULL) { sum1 += temp1->data; mul1 *= temp1->data; temp1 = temp1->next; } struct Node* temp2 = second; // Traversing through linked list // and calculating sum and multiply while (temp2 != NULL) { sum2 += temp2->data; mul2 *= temp2->data; temp2 = temp2->next; } return ((sum1 == sum2) && (mul1 == mul2));} // Function to add a node at the// beginning of Linked Listvoid push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} // Driver program to test above functionint main(){ struct Node* first = NULL; /* First constructed linked list is: 12 -> 35 -> 1 -> 10 -> 34 -> 1 */ push(&first, 1); push(&first, 34); push(&first, 10); push(&first, 1); push(&first, 35); push(&first, 12); struct Node* second = NULL; /* Second constructed linked list is: 35 -> 1 -> 12 -> 1 -> 10 -> 34 */ push(&second, 35); push(&second, 1); push(&second, 12); push(&second, 1); push(&second, 10); push(&second, 34); if (isPermutation(first, second)) { cout << "Yes" << endl; } else { cout << "No" << endl; } return 0;} // Java program to check if linked lists// are permutations of each otherimport java.util.*; class GFG{static class Node{ int data; Node next;}; /*Function to check if two linked lists* are permutations of each other* first : reference to head of first linked list* second : reference to head of second linked list*/static boolean isPermutation(Node first, Node second){ // Variables to keep track of // sum and multiplication int sum1 = 0, sum2 = 0, mul1 = 1, mul2 = 1; Node temp1 = first; // Traversing through linked list // and calculating sum and multiply while (temp1 != null) { sum1 += temp1.data; mul1 *= temp1.data; temp1 = temp1.next; } Node temp2 = second; // Traversing through linked list // and calculating sum and multiply while (temp2 != null) { sum2 += temp2.data; mul2 *= temp2.data; temp2 = temp2.next; } return ((sum1 == sum2) && (mul1 == mul2));} // Function to add a node at the// beginning of Linked Liststatic Node push(Node head_ref, int new_data){ /* allocate node */ Node new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list off the new node */ new_node.next = head_ref; /* move the head to point to the new node */ head_ref = new_node; return head_ref;} // Driver Codepublic static void main(String[] args){ Node first = null; /* First constructed linked list is: 12 . 35 . 1 . 10 . 34 . 1 */ first = push(first, 1); first = push(first, 34); first = push(first, 10); first = push(first, 1); first = push(first, 35); first = push(first, 12); Node second = null; /* Second constructed linked list is: 35 . 1 . 12 . 1 . 10 . 34 */ second = push(second, 35); second = push(second, 1); second = push(second, 12); second = push(second, 1); second = push(second, 10); second = push(second, 34); if (isPermutation(first, second)) { System.out.print("Yes"); } else { System.out.print("No"); }}} // This code is contributed by 29AjayKumar # Python3 program to check if linked lists# are permutations of each otherclass Node: def __init__(self): self.data = 0 self.next = None # Function to check if two linked lists# are permutations of each other# first : reference to head of first linked list# second : reference to head of second linked listdef isPermutation(first, second): # Variables to keep track of # sum and multiplication sum1 = 0 sum2 = 0 mul1 = 1 mul2 = 1 temp1 = first # Traversing through linked list # and calculating sum and multiply while (temp1 != None): sum1 += temp1.data mul1 *= temp1.data temp1 = temp1.next temp2 = second # Traversing through linked list # and calculating sum and multiply while (temp2 != None): sum2 += temp2.data mul2 *= temp2.data temp2 = temp2.next return ((sum1 == sum2) and (mul1 == mul2)) # Function to add a node at the# beginning of Linked Listdef push(head_ref, new_data): # Allocate node new_node = Node() # Put in the data new_node.data = new_data # Link the old list off the new node new_node.next = head_ref # Move the head to point to the new node head_ref = new_node return head_ref # Driver Codeif __name__=='__main__': first = None # First constructed linked list is: # 12 . 35 . 1 . 10 . 34 . 1 first = push(first, 1) first = push(first, 34) first = push(first, 10) first = push(first, 1) first = push(first, 35) first = push(first, 12) second = None # Second constructed linked list is: # 35 . 1 . 12 . 1 . 10 . 34 second = push(second, 35) second = push(second, 1) second = push(second, 12) second = push(second, 1) second = push(second, 10) second = push(second, 34) if (isPermutation(first, second)): print("Yes") else: print("No") # This code is contributed by pratham76 // C# program to check if linked lists// are permutations of each otherusing System; class GFG{public class Node{ public int data; public Node next;}; /*Function to check if two linked lists* are permutations of each other* first : reference to head of first linked list* second : reference to head of second linked list*/static bool isPermutation(Node first, Node second){ // Variables to keep track of // sum and multiplication int sum1 = 0, sum2 = 0, mul1 = 1, mul2 = 1; Node temp1 = first; // Traversing through linked list // and calculating sum and multiply while (temp1 != null) { sum1 += temp1.data; mul1 *= temp1.data; temp1 = temp1.next; } Node temp2 = second; // Traversing through linked list // and calculating sum and multiply while (temp2 != null) { sum2 += temp2.data; mul2 *= temp2.data; temp2 = temp2.next; } return ((sum1 == sum2) && (mul1 == mul2));} // Function to add a node at the// beginning of Linked Liststatic Node push(Node head_ref, int new_data){ /* allocate node */ Node new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list off the new node */ new_node.next = head_ref; /* move the head to point to the new node */ head_ref = new_node; return head_ref;} // Driver Codepublic static void Main(String[] args){ Node first = null; /* First constructed linked list is: 12 . 35 . 1 . 10 . 34 . 1 */ first = push(first, 1); first = push(first, 34); first = push(first, 10); first = push(first, 1); first = push(first, 35); first = push(first, 12); Node second = null; /* Second constructed linked list is: 35 . 1 . 12 . 1 . 10 . 34 */ second = push(second, 35); second = push(second, 1); second = push(second, 12); second = push(second, 1); second = push(second, 10); second = push(second, 34); if (isPermutation(first, second)) { Console.Write("Yes"); } else { Console.Write("No"); }}} // This code is contributed by PrinciRaj1992 <script> // JavaScript program to check if linked lists // are permutations of each other class Node { constructor() { this.data = 0; this.next = null; } } /*Function to check if two linked lists * are permutations of each other * first : reference to head of first linked list * second : reference to head of second linked list */ function isPermutation(first, second) { // Variables to keep track of // sum and multiplication var sum1 = 0, sum2 = 0, mul1 = 1, mul2 = 1; var temp1 = first; // Traversing through linked list // and calculating sum and multiply while (temp1 != null) { sum1 += temp1.data; mul1 *= temp1.data; temp1 = temp1.next; } var temp2 = second; // Traversing through linked list // and calculating sum and multiply while (temp2 != null) { sum2 += temp2.data; mul2 *= temp2.data; temp2 = temp2.next; } return sum1 == sum2 && mul1 == mul2; } // Function to add a node at the // beginning of Linked List function push(head_ref, new_data) { /* allocate node */ var new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list off the new node */ new_node.next = head_ref; /* move the head to point to the new node */ head_ref = new_node; return head_ref; } // Driver Code var first = null; /* First constructed linked list is: 12 . 35 . 1 . 10 . 34 . 1 */ first = push(first, 1); first = push(first, 34); first = push(first, 10); first = push(first, 1); first = push(first, 35); first = push(first, 12); var second = null; /* Second constructed linked list is: 35 . 1 . 12 . 1 . 10 . 34 */ second = push(second, 35); second = push(second, 1); second = push(second, 12); second = push(second, 1); second = push(second, 10); second = push(second, 34); if (isPermutation(first, second)) { document.write("Yes"); } else { document.write("No"); } </script> Yes 29AjayKumar princiraj1992 nidhi_biet pratham76 rdtank permutation Permutation and Combination Linked List Mathematical Linked List Mathematical permutation Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Delete a Linked List node at a given position Queue - Linked List Implementation Implement a stack using singly linked list Implementing a Linked List in Java using Class Circular Linked List | Set 1 (Introduction and Applications) Program for Fibonacci numbers Write a program to print all permutations of a given string Set in C++ Standard Template Library (STL) C++ Data Types Coin Change | DP-7
[ { "code": null, "e": 25957, "s": 25929, "text": "\n29 Jun, 2021" }, { "code": null, "e": 26110, "s": 25957, "text": "Given two singly Linked list of integer data. The task is to write a program that efficiently checks if two linked lists are permutations of each other." }, { "code": null, "e": 26122, "s": 26110, "text": "Examples: " }, { "code": null, "e": 26262, "s": 26122, "text": "Input: 1 -> 2 -> 3 -> 4 -> 5\n 2 -> 1 -> 3 -> 5 -> 4\nOutput: Yes\n\nInput: 10 -> 20 -> 30 -> 40\n 20 -> 50 -> 60 -> 70\nOutput: No" }, { "code": null, "e": 26314, "s": 26262, "text": "Approach: Do the following for both linked lists: " }, { "code": null, "e": 26469, "s": 26314, "text": "Take a temporary node pointing to the head of the linked list.Start traversing through the linked list, and keep sum and multiplications of data of nodes." }, { "code": null, "e": 26532, "s": 26469, "text": "Take a temporary node pointing to the head of the linked list." }, { "code": null, "e": 26625, "s": 26532, "text": "Start traversing through the linked list, and keep sum and multiplications of data of nodes." }, { "code": null, "e": 26836, "s": 26625, "text": "Note : After having sum and multiplication of both linked list, check if sum and multiplication of both linked lists are equal. If they are equal, it means linked lists are permutations of each other, else not." }, { "code": null, "e": 26889, "s": 26836, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26893, "s": 26889, "text": "C++" }, { "code": null, "e": 26898, "s": 26893, "text": "Java" }, { "code": null, "e": 26906, "s": 26898, "text": "Python3" }, { "code": null, "e": 26909, "s": 26906, "text": "C#" }, { "code": null, "e": 26920, "s": 26909, "text": "Javascript" }, { "code": "// C++ program to check if linked lists// are permutations of each other#include <bits/stdc++.h> using namespace std; // A linked list nodestruct Node { int data; struct Node* next;}; /*Function to check if two linked lists* are permutations of each other* first : reference to head of first linked list* second : reference to head of second linked list*/bool isPermutation(struct Node* first, struct Node* second){ // Variables to keep track of sum and multiplication int sum1 = 0, sum2 = 0, mul1 = 1, mul2 = 1; struct Node* temp1 = first; // Traversing through linked list // and calculating sum and multiply while (temp1 != NULL) { sum1 += temp1->data; mul1 *= temp1->data; temp1 = temp1->next; } struct Node* temp2 = second; // Traversing through linked list // and calculating sum and multiply while (temp2 != NULL) { sum2 += temp2->data; mul2 *= temp2->data; temp2 = temp2->next; } return ((sum1 == sum2) && (mul1 == mul2));} // Function to add a node at the// beginning of Linked Listvoid push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} // Driver program to test above functionint main(){ struct Node* first = NULL; /* First constructed linked list is: 12 -> 35 -> 1 -> 10 -> 34 -> 1 */ push(&first, 1); push(&first, 34); push(&first, 10); push(&first, 1); push(&first, 35); push(&first, 12); struct Node* second = NULL; /* Second constructed linked list is: 35 -> 1 -> 12 -> 1 -> 10 -> 34 */ push(&second, 35); push(&second, 1); push(&second, 12); push(&second, 1); push(&second, 10); push(&second, 34); if (isPermutation(first, second)) { cout << \"Yes\" << endl; } else { cout << \"No\" << endl; } return 0;}", "e": 29015, "s": 26920, "text": null }, { "code": "// Java program to check if linked lists// are permutations of each otherimport java.util.*; class GFG{static class Node{ int data; Node next;}; /*Function to check if two linked lists* are permutations of each other* first : reference to head of first linked list* second : reference to head of second linked list*/static boolean isPermutation(Node first, Node second){ // Variables to keep track of // sum and multiplication int sum1 = 0, sum2 = 0, mul1 = 1, mul2 = 1; Node temp1 = first; // Traversing through linked list // and calculating sum and multiply while (temp1 != null) { sum1 += temp1.data; mul1 *= temp1.data; temp1 = temp1.next; } Node temp2 = second; // Traversing through linked list // and calculating sum and multiply while (temp2 != null) { sum2 += temp2.data; mul2 *= temp2.data; temp2 = temp2.next; } return ((sum1 == sum2) && (mul1 == mul2));} // Function to add a node at the// beginning of Linked Liststatic Node push(Node head_ref, int new_data){ /* allocate node */ Node new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list off the new node */ new_node.next = head_ref; /* move the head to point to the new node */ head_ref = new_node; return head_ref;} // Driver Codepublic static void main(String[] args){ Node first = null; /* First constructed linked list is: 12 . 35 . 1 . 10 . 34 . 1 */ first = push(first, 1); first = push(first, 34); first = push(first, 10); first = push(first, 1); first = push(first, 35); first = push(first, 12); Node second = null; /* Second constructed linked list is: 35 . 1 . 12 . 1 . 10 . 34 */ second = push(second, 35); second = push(second, 1); second = push(second, 12); second = push(second, 1); second = push(second, 10); second = push(second, 34); if (isPermutation(first, second)) { System.out.print(\"Yes\"); } else { System.out.print(\"No\"); }}} // This code is contributed by 29AjayKumar", "e": 31183, "s": 29015, "text": null }, { "code": "# Python3 program to check if linked lists# are permutations of each otherclass Node: def __init__(self): self.data = 0 self.next = None # Function to check if two linked lists# are permutations of each other# first : reference to head of first linked list# second : reference to head of second linked listdef isPermutation(first, second): # Variables to keep track of # sum and multiplication sum1 = 0 sum2 = 0 mul1 = 1 mul2 = 1 temp1 = first # Traversing through linked list # and calculating sum and multiply while (temp1 != None): sum1 += temp1.data mul1 *= temp1.data temp1 = temp1.next temp2 = second # Traversing through linked list # and calculating sum and multiply while (temp2 != None): sum2 += temp2.data mul2 *= temp2.data temp2 = temp2.next return ((sum1 == sum2) and (mul1 == mul2)) # Function to add a node at the# beginning of Linked Listdef push(head_ref, new_data): # Allocate node new_node = Node() # Put in the data new_node.data = new_data # Link the old list off the new node new_node.next = head_ref # Move the head to point to the new node head_ref = new_node return head_ref # Driver Codeif __name__=='__main__': first = None # First constructed linked list is: # 12 . 35 . 1 . 10 . 34 . 1 first = push(first, 1) first = push(first, 34) first = push(first, 10) first = push(first, 1) first = push(first, 35) first = push(first, 12) second = None # Second constructed linked list is: # 35 . 1 . 12 . 1 . 10 . 34 second = push(second, 35) second = push(second, 1) second = push(second, 12) second = push(second, 1) second = push(second, 10) second = push(second, 34) if (isPermutation(first, second)): print(\"Yes\") else: print(\"No\") # This code is contributed by pratham76", "e": 33154, "s": 31183, "text": null }, { "code": "// C# program to check if linked lists// are permutations of each otherusing System; class GFG{public class Node{ public int data; public Node next;}; /*Function to check if two linked lists* are permutations of each other* first : reference to head of first linked list* second : reference to head of second linked list*/static bool isPermutation(Node first, Node second){ // Variables to keep track of // sum and multiplication int sum1 = 0, sum2 = 0, mul1 = 1, mul2 = 1; Node temp1 = first; // Traversing through linked list // and calculating sum and multiply while (temp1 != null) { sum1 += temp1.data; mul1 *= temp1.data; temp1 = temp1.next; } Node temp2 = second; // Traversing through linked list // and calculating sum and multiply while (temp2 != null) { sum2 += temp2.data; mul2 *= temp2.data; temp2 = temp2.next; } return ((sum1 == sum2) && (mul1 == mul2));} // Function to add a node at the// beginning of Linked Liststatic Node push(Node head_ref, int new_data){ /* allocate node */ Node new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list off the new node */ new_node.next = head_ref; /* move the head to point to the new node */ head_ref = new_node; return head_ref;} // Driver Codepublic static void Main(String[] args){ Node first = null; /* First constructed linked list is: 12 . 35 . 1 . 10 . 34 . 1 */ first = push(first, 1); first = push(first, 34); first = push(first, 10); first = push(first, 1); first = push(first, 35); first = push(first, 12); Node second = null; /* Second constructed linked list is: 35 . 1 . 12 . 1 . 10 . 34 */ second = push(second, 35); second = push(second, 1); second = push(second, 12); second = push(second, 1); second = push(second, 10); second = push(second, 34); if (isPermutation(first, second)) { Console.Write(\"Yes\"); } else { Console.Write(\"No\"); }}} // This code is contributed by PrinciRaj1992", "e": 35318, "s": 33154, "text": null }, { "code": "<script> // JavaScript program to check if linked lists // are permutations of each other class Node { constructor() { this.data = 0; this.next = null; } } /*Function to check if two linked lists * are permutations of each other * first : reference to head of first linked list * second : reference to head of second linked list */ function isPermutation(first, second) { // Variables to keep track of // sum and multiplication var sum1 = 0, sum2 = 0, mul1 = 1, mul2 = 1; var temp1 = first; // Traversing through linked list // and calculating sum and multiply while (temp1 != null) { sum1 += temp1.data; mul1 *= temp1.data; temp1 = temp1.next; } var temp2 = second; // Traversing through linked list // and calculating sum and multiply while (temp2 != null) { sum2 += temp2.data; mul2 *= temp2.data; temp2 = temp2.next; } return sum1 == sum2 && mul1 == mul2; } // Function to add a node at the // beginning of Linked List function push(head_ref, new_data) { /* allocate node */ var new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list off the new node */ new_node.next = head_ref; /* move the head to point to the new node */ head_ref = new_node; return head_ref; } // Driver Code var first = null; /* First constructed linked list is: 12 . 35 . 1 . 10 . 34 . 1 */ first = push(first, 1); first = push(first, 34); first = push(first, 10); first = push(first, 1); first = push(first, 35); first = push(first, 12); var second = null; /* Second constructed linked list is: 35 . 1 . 12 . 1 . 10 . 34 */ second = push(second, 35); second = push(second, 1); second = push(second, 12); second = push(second, 1); second = push(second, 10); second = push(second, 34); if (isPermutation(first, second)) { document.write(\"Yes\"); } else { document.write(\"No\"); } </script>", "e": 37614, "s": 35318, "text": null }, { "code": null, "e": 37618, "s": 37614, "text": "Yes" }, { "code": null, "e": 37632, "s": 37620, "text": "29AjayKumar" }, { "code": null, "e": 37646, "s": 37632, "text": "princiraj1992" }, { "code": null, "e": 37657, "s": 37646, "text": "nidhi_biet" }, { "code": null, "e": 37667, "s": 37657, "text": "pratham76" }, { "code": null, "e": 37674, "s": 37667, "text": "rdtank" }, { "code": null, "e": 37686, "s": 37674, "text": "permutation" }, { "code": null, "e": 37714, "s": 37686, "text": "Permutation and Combination" }, { "code": null, "e": 37726, "s": 37714, "text": "Linked List" }, { "code": null, "e": 37739, "s": 37726, "text": "Mathematical" }, { "code": null, "e": 37751, "s": 37739, "text": "Linked List" }, { "code": null, "e": 37764, "s": 37751, "text": "Mathematical" }, { "code": null, "e": 37776, "s": 37764, "text": "permutation" }, { "code": null, "e": 37874, "s": 37776, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37920, "s": 37874, "text": "Delete a Linked List node at a given position" }, { "code": null, "e": 37955, "s": 37920, "text": "Queue - Linked List Implementation" }, { "code": null, "e": 37998, "s": 37955, "text": "Implement a stack using singly linked list" }, { "code": null, "e": 38045, "s": 37998, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 38106, "s": 38045, "text": "Circular Linked List | Set 1 (Introduction and Applications)" }, { "code": null, "e": 38136, "s": 38106, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 38196, "s": 38136, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 38239, "s": 38196, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 38254, "s": 38239, "text": "C++ Data Types" } ]
Maximize the value of the given expression - GeeksforGeeks
07 Mar, 2022 Given three non-zero integers a, b and c. The task is to find the maximum value possible by putting addition and multiplication signs between them in any order. Note: Rearrangement of integers is allowed but addition and multiplication sign must be used once. Braces can also be placed between equations as per your need. Examples: Input: a = 2, b = 1, c = 4 Output: 12 (1 + 2) * 4 = 3 * 4 = 12 Input: a = 2, b = 2, c = 2 Output: 8 (2 + 2) * 2 = 4 * 2 = 8 Approach: To solve this problem one can opt the method of generating all the possibilities and calculate them to get the maximum value but this approach is not efficient. Take the advantage of given conditions that integers may got rearranged and mandatory use of each mathematical sign (+, *). There are total of four cases to solve which are listed below: All three integers are non-negative: For this simply add two smaller one and multiply their result by largest integer.One integer is negative and rest two positive : Multiply the both positive integer and add their result to negative integer.Two integers are negative and one is positive: As the product of two negative numbers is positive multiply both negative integers and then add their result to positive integer.All three are negative integers: add the two largest integers and multiply them to smallest one. case 3-: (sum – smallest) * smallest All three integers are non-negative: For this simply add two smaller one and multiply their result by largest integer. One integer is negative and rest two positive : Multiply the both positive integer and add their result to negative integer. Two integers are negative and one is positive: As the product of two negative numbers is positive multiply both negative integers and then add their result to positive integer. All three are negative integers: add the two largest integers and multiply them to smallest one. case 3-: (sum – smallest) * smallest Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the maximum resultint maximumResult(int a, int b, int c){ // To store the count of negative integers int countOfNegative = 0; // Sum of all the three integers int sum = a + b + c; // Product of all the three integers int product = a * b * c; // To store the smallest and the largest // among all the three integers int largest = max(a,max(b,c)); int smallest = min(a,min(b,c) ); // Calculate the count of negative integers if (a < 0) countOfNegative++; if (b < 0) countOfNegative++; if (c < 0) countOfNegative++; // Depending upon count of negatives switch (countOfNegative) { // When all three are positive integers case 0: return (sum - largest) * largest; // For single negative integer case 1: return (product / smallest) + smallest; // For two negative integers case 2: return (product / largest) + largest; // For three negative integers case 3: return (sum - smallest) * smallest; }} // Driver Codeint main(){ int a=-2,b=-1,c=-4; cout << maximumResult(a, b, c); return 0;}// This code contributed by Nikhil // Java implementation of the approachclass GFG{ // Function to return the maximum resultstatic int maximumResult(int a, int b, int c){ // To store the count of negative integers int countOfNegative = 0; // Sum of all the three integers int sum = a + b + c; // Product of all the three integers int product = a * b * c; // To store the smallest and the largest // among all the three integers int largest = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c); int smallest= (a<b)?((a<c)? a : c):((b<c) ? b : c); // Calculate the count of negative integers if (a < 0) countOfNegative++; if (b < 0) countOfNegative++; if (c < 0) countOfNegative++; // Depending upon count of negatives switch (countOfNegative) { // When all three are positive integers case 0: return (sum - largest) * largest; // For single negative integer case 1: return (product / smallest) + smallest; // For two negative integers case 2: return (product / largest) + largest; // For three negative integers case 3: return (sum - smallest) * smallest; } return -1;} // Driver Codepublic static void main(String[] args){ int a=-2,b=-1,c=-4; System.out.print(maximumResult(a, b, c));}} // This code contributed by Nikhil # Python3 implementation of the approach # Function to return the maximum result# Python3 implementation of the approach # Function to return the maximum resultdef maximumResult(a, b, c): # To store the count of negative integers countOfNegative = 0 # Sum of all the three integers Sum = a + b + c # Product of all the three integers product = a * b * c # To store the smallest and the # largest among all the three integers largest = max(a, b, c) smallest = min(a, b, c) # Calculate the count of negative integers if a < 0: countOfNegative += 1 if b < 0: countOfNegative += 1 if c < 0: countOfNegative += 1 # When all three are positive integers if countOfNegative == 0: return (Sum - largest) * largest # For single negative integer elif countOfNegative == 1: return (product // smallest) + smallest # For two negative integers elif countOfNegative == 2: return (product // largest) + largest # For three negative integers elif countOfNegative == 3: return (Sum - smallest) * smallest # Driver Codeif __name__ == "__main__": a, b, c = -2, -1, -4 print(maximumResult(a, b, c)) // C# implementation of the approachusing System; class GFG{ // Function to return the maximum resultstatic int maximumResult(int a, int b, int c){ // To store the count of negative integers int countOfNegative = 0; // Sum of all the three integers int sum = a + b + c; // Product of all the three integers int product = a * b * c; // To store the smallest and the largest // among all the three integers int largest = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c); int smallest=(a<b)?((a<c)? a : c):((b<c) ? b : c); // Calculate the count of negative integers if (a < 0) countOfNegative++; if (b < 0) countOfNegative++; if (c < 0) countOfNegative++; // Depending upon count of negatives switch (countOfNegative) { // When all three are positive integers case 0: return (sum - largest) * largest; // For single negative integer case 1: return (product / smallest) + smallest; // For two negative integers case 2: return (product / largest) + largest; // For three negative integers case 3: return (sum - smallest) * smallest; } return -1;} // Driver Codestatic void Main(){ int a = -2, b = -1, c = -4; Console.WriteLine(maximumResult(a, b, c));}} // This code is contributed by mits & Nikhil <?php// PHP implementation of the approach // Function to return the maximum resultfunction maximumResult($a, $b, $c){ // To store the count of // negative integers $countOfNegative = 0; // Sum of all the three integers $sum = $a + $b + $c; // Product of all the three integers $product = $a * $b * $c; // To store the smallest and the largest // among all the three integers $largest = max($a ,$b, $c); $smallest = min($a ,$b, $c); // Calculate the count of negative integers if ($a < 0) $countOfNegative++; if ($b < 0) $countOfNegative++; if ($c < 0) $countOfNegative++; // Depending upon count of negatives switch ($countOfNegative) { // When all three are positive integers case 0: return ($sum - $largest) * $largest; // For single negative integer case 1: return ($product / $smallest) + $smallest; // For two negative integers case 2: return ($product / $largest) + $largest; // For three negative integers case 3: return ($sum - $smallest) * $smallest; }} // Driver Code$a = -2;$b = -1;$c = -4;echo maximumResult($a, $b, $c); // This code is contributed by ihritik?> <script>// JavaScript implementation of the approach // Function to return the maximum resultfunction maximumResult(a, b, c){ // To store the count of negative integers let countOfNegative = 0; // Sum of all the three integers let sum = a + b + c; // Product of all the three integers let product = a * b * c; // To store the smallest and the largest // among all the three integers let largest = Math.max(a,Math.max(b,c)); let smallest = Math.min(a,Math.min(b,c) ); // Calculate the count of negative integers if (a < 0) countOfNegative++; if (b < 0) countOfNegative++; if (c < 0) countOfNegative++; // Depending upon count of negatives switch (countOfNegative) { // When all three are positive integers case 0: return (sum - largest) * largest; // For single negative integer case 1: return (product / smallest) + smallest; // For two negative integers case 2: return (product / largest) + largest; // For three negative integers case 3: return (sum - smallest) * smallest; }} // Driver Code let a = -2, b = -1, c = -4; document.write(maximumResult(a, b, c)); // This code is contributed by Surbhi Tyagi.</script> 12 Time Complexity: O(1) Auxiliary Space: O(1) Mithun Kumar rituraj_jain Rajput-Ji ihritik Nikhil_Mishra surbhityagi15 simranarora5sos prophet1999 Greedy Mathematical Greedy Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Huffman Coding | Greedy Algo-3 Coin Change | DP-7 Activity Selection Problem | Greedy Algo-1 Fractional Knapsack Problem Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive) Program for Fibonacci numbers C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7 Merge two sorted arrays
[ { "code": null, "e": 26439, "s": 26411, "text": "\n07 Mar, 2022" }, { "code": null, "e": 26601, "s": 26439, "text": "Given three non-zero integers a, b and c. The task is to find the maximum value possible by putting addition and multiplication signs between them in any order. " }, { "code": null, "e": 26762, "s": 26601, "text": "Note: Rearrangement of integers is allowed but addition and multiplication sign must be used once. Braces can also be placed between equations as per your need." }, { "code": null, "e": 26773, "s": 26762, "text": "Examples: " }, { "code": null, "e": 26836, "s": 26773, "text": "Input: a = 2, b = 1, c = 4 Output: 12 (1 + 2) * 4 = 3 * 4 = 12" }, { "code": null, "e": 26898, "s": 26836, "text": "Input: a = 2, b = 2, c = 2 Output: 8 (2 + 2) * 2 = 4 * 2 = 8 " }, { "code": null, "e": 27258, "s": 26898, "text": "Approach: To solve this problem one can opt the method of generating all the possibilities and calculate them to get the maximum value but this approach is not efficient. Take the advantage of given conditions that integers may got rearranged and mandatory use of each mathematical sign (+, *). There are total of four cases to solve which are listed below: " }, { "code": null, "e": 27810, "s": 27258, "text": "All three integers are non-negative: For this simply add two smaller one and multiply their result by largest integer.One integer is negative and rest two positive : Multiply the both positive integer and add their result to negative integer.Two integers are negative and one is positive: As the product of two negative numbers is positive multiply both negative integers and then add their result to positive integer.All three are negative integers: add the two largest integers and multiply them to smallest one. case 3-: (sum – smallest) * smallest" }, { "code": null, "e": 27929, "s": 27810, "text": "All three integers are non-negative: For this simply add two smaller one and multiply their result by largest integer." }, { "code": null, "e": 28054, "s": 27929, "text": "One integer is negative and rest two positive : Multiply the both positive integer and add their result to negative integer." }, { "code": null, "e": 28231, "s": 28054, "text": "Two integers are negative and one is positive: As the product of two negative numbers is positive multiply both negative integers and then add their result to positive integer." }, { "code": null, "e": 28365, "s": 28231, "text": "All three are negative integers: add the two largest integers and multiply them to smallest one. case 3-: (sum – smallest) * smallest" }, { "code": null, "e": 28418, "s": 28365, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 28422, "s": 28418, "text": "C++" }, { "code": null, "e": 28427, "s": 28422, "text": "Java" }, { "code": null, "e": 28435, "s": 28427, "text": "Python3" }, { "code": null, "e": 28438, "s": 28435, "text": "C#" }, { "code": null, "e": 28442, "s": 28438, "text": "PHP" }, { "code": null, "e": 28453, "s": 28442, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the maximum resultint maximumResult(int a, int b, int c){ // To store the count of negative integers int countOfNegative = 0; // Sum of all the three integers int sum = a + b + c; // Product of all the three integers int product = a * b * c; // To store the smallest and the largest // among all the three integers int largest = max(a,max(b,c)); int smallest = min(a,min(b,c) ); // Calculate the count of negative integers if (a < 0) countOfNegative++; if (b < 0) countOfNegative++; if (c < 0) countOfNegative++; // Depending upon count of negatives switch (countOfNegative) { // When all three are positive integers case 0: return (sum - largest) * largest; // For single negative integer case 1: return (product / smallest) + smallest; // For two negative integers case 2: return (product / largest) + largest; // For three negative integers case 3: return (sum - smallest) * smallest; }} // Driver Codeint main(){ int a=-2,b=-1,c=-4; cout << maximumResult(a, b, c); return 0;}// This code contributed by Nikhil", "e": 29730, "s": 28453, "text": null }, { "code": "// Java implementation of the approachclass GFG{ // Function to return the maximum resultstatic int maximumResult(int a, int b, int c){ // To store the count of negative integers int countOfNegative = 0; // Sum of all the three integers int sum = a + b + c; // Product of all the three integers int product = a * b * c; // To store the smallest and the largest // among all the three integers int largest = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c); int smallest= (a<b)?((a<c)? a : c):((b<c) ? b : c); // Calculate the count of negative integers if (a < 0) countOfNegative++; if (b < 0) countOfNegative++; if (c < 0) countOfNegative++; // Depending upon count of negatives switch (countOfNegative) { // When all three are positive integers case 0: return (sum - largest) * largest; // For single negative integer case 1: return (product / smallest) + smallest; // For two negative integers case 2: return (product / largest) + largest; // For three negative integers case 3: return (sum - smallest) * smallest; } return -1;} // Driver Codepublic static void main(String[] args){ int a=-2,b=-1,c=-4; System.out.print(maximumResult(a, b, c));}} // This code contributed by Nikhil", "e": 31138, "s": 29730, "text": null }, { "code": "# Python3 implementation of the approach # Function to return the maximum result# Python3 implementation of the approach # Function to return the maximum resultdef maximumResult(a, b, c): # To store the count of negative integers countOfNegative = 0 # Sum of all the three integers Sum = a + b + c # Product of all the three integers product = a * b * c # To store the smallest and the # largest among all the three integers largest = max(a, b, c) smallest = min(a, b, c) # Calculate the count of negative integers if a < 0: countOfNegative += 1 if b < 0: countOfNegative += 1 if c < 0: countOfNegative += 1 # When all three are positive integers if countOfNegative == 0: return (Sum - largest) * largest # For single negative integer elif countOfNegative == 1: return (product // smallest) + smallest # For two negative integers elif countOfNegative == 2: return (product // largest) + largest # For three negative integers elif countOfNegative == 3: return (Sum - smallest) * smallest # Driver Codeif __name__ == \"__main__\": a, b, c = -2, -1, -4 print(maximumResult(a, b, c))", "e": 32347, "s": 31138, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to return the maximum resultstatic int maximumResult(int a, int b, int c){ // To store the count of negative integers int countOfNegative = 0; // Sum of all the three integers int sum = a + b + c; // Product of all the three integers int product = a * b * c; // To store the smallest and the largest // among all the three integers int largest = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c); int smallest=(a<b)?((a<c)? a : c):((b<c) ? b : c); // Calculate the count of negative integers if (a < 0) countOfNegative++; if (b < 0) countOfNegative++; if (c < 0) countOfNegative++; // Depending upon count of negatives switch (countOfNegative) { // When all three are positive integers case 0: return (sum - largest) * largest; // For single negative integer case 1: return (product / smallest) + smallest; // For two negative integers case 2: return (product / largest) + largest; // For three negative integers case 3: return (sum - smallest) * smallest; } return -1;} // Driver Codestatic void Main(){ int a = -2, b = -1, c = -4; Console.WriteLine(maximumResult(a, b, c));}} // This code is contributed by mits & Nikhil", "e": 33766, "s": 32347, "text": null }, { "code": "<?php// PHP implementation of the approach // Function to return the maximum resultfunction maximumResult($a, $b, $c){ // To store the count of // negative integers $countOfNegative = 0; // Sum of all the three integers $sum = $a + $b + $c; // Product of all the three integers $product = $a * $b * $c; // To store the smallest and the largest // among all the three integers $largest = max($a ,$b, $c); $smallest = min($a ,$b, $c); // Calculate the count of negative integers if ($a < 0) $countOfNegative++; if ($b < 0) $countOfNegative++; if ($c < 0) $countOfNegative++; // Depending upon count of negatives switch ($countOfNegative) { // When all three are positive integers case 0: return ($sum - $largest) * $largest; // For single negative integer case 1: return ($product / $smallest) + $smallest; // For two negative integers case 2: return ($product / $largest) + $largest; // For three negative integers case 3: return ($sum - $smallest) * $smallest; }} // Driver Code$a = -2;$b = -1;$c = -4;echo maximumResult($a, $b, $c); // This code is contributed by ihritik?>", "e": 35159, "s": 33766, "text": null }, { "code": "<script>// JavaScript implementation of the approach // Function to return the maximum resultfunction maximumResult(a, b, c){ // To store the count of negative integers let countOfNegative = 0; // Sum of all the three integers let sum = a + b + c; // Product of all the three integers let product = a * b * c; // To store the smallest and the largest // among all the three integers let largest = Math.max(a,Math.max(b,c)); let smallest = Math.min(a,Math.min(b,c) ); // Calculate the count of negative integers if (a < 0) countOfNegative++; if (b < 0) countOfNegative++; if (c < 0) countOfNegative++; // Depending upon count of negatives switch (countOfNegative) { // When all three are positive integers case 0: return (sum - largest) * largest; // For single negative integer case 1: return (product / smallest) + smallest; // For two negative integers case 2: return (product / largest) + largest; // For three negative integers case 3: return (sum - smallest) * smallest; }} // Driver Code let a = -2, b = -1, c = -4; document.write(maximumResult(a, b, c)); // This code is contributed by Surbhi Tyagi.</script>", "e": 36428, "s": 35159, "text": null }, { "code": null, "e": 36431, "s": 36428, "text": "12" }, { "code": null, "e": 36455, "s": 36433, "text": "Time Complexity: O(1)" }, { "code": null, "e": 36477, "s": 36455, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 36490, "s": 36477, "text": "Mithun Kumar" }, { "code": null, "e": 36503, "s": 36490, "text": "rituraj_jain" }, { "code": null, "e": 36513, "s": 36503, "text": "Rajput-Ji" }, { "code": null, "e": 36521, "s": 36513, "text": "ihritik" }, { "code": null, "e": 36535, "s": 36521, "text": "Nikhil_Mishra" }, { "code": null, "e": 36549, "s": 36535, "text": "surbhityagi15" }, { "code": null, "e": 36565, "s": 36549, "text": "simranarora5sos" }, { "code": null, "e": 36577, "s": 36565, "text": "prophet1999" }, { "code": null, "e": 36584, "s": 36577, "text": "Greedy" }, { "code": null, "e": 36597, "s": 36584, "text": "Mathematical" }, { "code": null, "e": 36604, "s": 36597, "text": "Greedy" }, { "code": null, "e": 36617, "s": 36604, "text": "Mathematical" }, { "code": null, "e": 36715, "s": 36617, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36746, "s": 36715, "text": "Huffman Coding | Greedy Algo-3" }, { "code": null, "e": 36765, "s": 36746, "text": "Coin Change | DP-7" }, { "code": null, "e": 36808, "s": 36765, "text": "Activity Selection Problem | Greedy Algo-1" }, { "code": null, "e": 36836, "s": 36808, "text": "Fractional Knapsack Problem" }, { "code": null, "e": 36917, "s": 36836, "text": "Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)" }, { "code": null, "e": 36947, "s": 36917, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 36962, "s": 36947, "text": "C++ Data Types" }, { "code": null, "e": 37005, "s": 36962, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 37024, "s": 37005, "text": "Coin Change | DP-7" } ]
HTTP headers | Access-Control-Allow-Origin - GeeksforGeeks
22 Nov, 2019 The Access-Control-Allow-Origin is a response header that is used to indicates whether the response can be shared with requesting code from the given origin. Syntax: Access-Control-Allow-Origin: * | <origin> | null Directives: Access-Control-Allow-Origin accepts there types of directives mentioned above and described below: *: This directive tells the browsers to allow requesting code from any origin to access the resource. Used as a wildcard. <origin>: This directive defines any single origin. null: This directive defines null that should not be used due to any origin can create a hostile document with a “null” Origin. The “null” value for the ACAO(Access-Control-Allow-Origin) header should therefore, be avoided.” Example: This example tells the browser to allow code from any origin to access a resource.access-control-allow-origin: * access-control-allow-origin: * A response that tells the browser to allow requesting code from the origin https://www.geeksforgeeks.org to access a resource will include the following:access-control-allow-origin:https://www.geeksforgeeks.orgHere the value of the Origin request header is compared with the list of allowed origins, and if the response header origin value is present in that compared list. Then set the Access-Control-Allow-Origin value to the same value as the Origin value. access-control-allow-origin:https://www.geeksforgeeks.org Here the value of the Origin request header is compared with the list of allowed origins, and if the response header origin value is present in that compared list. Then set the Access-Control-Allow-Origin value to the same value as the Origin value. To check this Access-Control-Allow-Origin in action go to Inspect Element -> Network check the response header for Access-Control-Allow-Origin like below, Access-Control-Allow-Origin is highlighted you can see.Supported browsers: The browsers compatible with HTTP headers Access-Control-Allow-Origin are listed below: Google Chrome 4.0 Internet Explorer 10.0 Firefox 3.5 Safari 4.0 Opera 12.0 HTTP-headers Picked Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript How to create footer to stay at the bottom of a Web page? Differences between Functional Components and Class Components in React Node.js fs.readFileSync() Method How to apply style to parent if it has child with CSS? How to Open URL in New Tab using JavaScript ? How to execute PHP code using command line ?
[ { "code": null, "e": 26069, "s": 26041, "text": "\n22 Nov, 2019" }, { "code": null, "e": 26227, "s": 26069, "text": "The Access-Control-Allow-Origin is a response header that is used to indicates whether the response can be shared with requesting code from the given origin." }, { "code": null, "e": 26235, "s": 26227, "text": "Syntax:" }, { "code": null, "e": 26284, "s": 26235, "text": "Access-Control-Allow-Origin: * | <origin> | null" }, { "code": null, "e": 26395, "s": 26284, "text": "Directives: Access-Control-Allow-Origin accepts there types of directives mentioned above and described below:" }, { "code": null, "e": 26517, "s": 26395, "text": "*: This directive tells the browsers to allow requesting code from any origin to access the resource. Used as a wildcard." }, { "code": null, "e": 26569, "s": 26517, "text": "<origin>: This directive defines any single origin." }, { "code": null, "e": 26794, "s": 26569, "text": "null: This directive defines null that should not be used due to any origin can create a hostile document with a “null” Origin. The “null” value for the ACAO(Access-Control-Allow-Origin) header should therefore, be avoided.”" }, { "code": null, "e": 26803, "s": 26794, "text": "Example:" }, { "code": null, "e": 26916, "s": 26803, "text": "This example tells the browser to allow code from any origin to access a resource.access-control-allow-origin: *" }, { "code": null, "e": 26947, "s": 26916, "text": "access-control-allow-origin: *" }, { "code": null, "e": 27407, "s": 26947, "text": "A response that tells the browser to allow requesting code from the origin https://www.geeksforgeeks.org to access a resource will include the following:access-control-allow-origin:https://www.geeksforgeeks.orgHere the value of the Origin request header is compared with the list of allowed origins, and if the response header origin value is present in that compared list. Then set the Access-Control-Allow-Origin value to the same value as the Origin value." }, { "code": null, "e": 27465, "s": 27407, "text": "access-control-allow-origin:https://www.geeksforgeeks.org" }, { "code": null, "e": 27715, "s": 27465, "text": "Here the value of the Origin request header is compared with the list of allowed origins, and if the response header origin value is present in that compared list. Then set the Access-Control-Allow-Origin value to the same value as the Origin value." }, { "code": null, "e": 28033, "s": 27715, "text": "To check this Access-Control-Allow-Origin in action go to Inspect Element -> Network check the response header for Access-Control-Allow-Origin like below, Access-Control-Allow-Origin is highlighted you can see.Supported browsers: The browsers compatible with HTTP headers Access-Control-Allow-Origin are listed below:" }, { "code": null, "e": 28051, "s": 28033, "text": "Google Chrome 4.0" }, { "code": null, "e": 28074, "s": 28051, "text": "Internet Explorer 10.0" }, { "code": null, "e": 28086, "s": 28074, "text": "Firefox 3.5" }, { "code": null, "e": 28097, "s": 28086, "text": "Safari 4.0" }, { "code": null, "e": 28108, "s": 28097, "text": "Opera 12.0" }, { "code": null, "e": 28121, "s": 28108, "text": "HTTP-headers" }, { "code": null, "e": 28128, "s": 28121, "text": "Picked" }, { "code": null, "e": 28145, "s": 28128, "text": "Web Technologies" }, { "code": null, "e": 28243, "s": 28145, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28283, "s": 28243, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28328, "s": 28283, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28371, "s": 28328, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28432, "s": 28371, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28490, "s": 28432, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 28562, "s": 28490, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 28595, "s": 28562, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 28650, "s": 28595, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 28696, "s": 28650, "text": "How to Open URL in New Tab using JavaScript ?" } ]
Interchange elements of first and last columns in matrix - GeeksforGeeks
19 Apr, 2021 Given a 4 x 4 matrix, the task is to interchange the elements of first and last columns and show the resulting matrix.Examples: Input: 8 9 7 6 4 7 6 5 3 2 1 8 9 9 7 7 Output: 6 9 7 8 5 7 6 4 8 2 1 3 7 9 7 9 Input: 9 7 5 1 2 3 4 1 5 6 6 5 1 2 3 1 Output: 1 7 5 9 1 3 4 2 5 6 6 5 1 2 3 1 The approach is very simple, we can simply swap the elements of first and last column of the matrix in order to get the desired matrix as output.Below is the implementation of the above approach : C++ Java Python 3 C# PHP Javascript // C++ code to swap the element of first// and last column and display the result#include <iostream>using namespace std; #define n 4 void interchangeFirstLast(int m[][n]){ // swapping of element between first // and last columns for (int i = 0; i < n; i++) { int t = m[i][0]; m[i][0] = m[i][n - 1]; m[i][n - 1] = t; }} // Driver functionint main(){ // input in the array int m[n][n] = { { 8, 9, 7, 6 }, { 4, 7, 6, 5 }, { 3, 2, 1, 8 }, { 9, 9, 7, 7 } }; interchangeFirstLast(m); // printing the interchanged matrix for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) cout << m[i][j] << " "; cout << endl; }} // Java code to swap the element of first// and last column and display the result import java.io.*; class GFG { static int n = 4; static void interchangeFirstLast(int m[][]){ int cols = n; // swapping of element between first // and last columns for (int i = 0; i < n; i++) { int t = m[i][0]; m[i][0] = m[i][n - 1]; m[i][n - 1] = t; }} // Driver function public static void main (String[] args) { // input in the array int m[][] = { { 8, 9, 7, 6 }, { 4, 7, 6, 5 }, { 3, 2, 1, 8 }, { 9, 9, 7, 7 } }; interchangeFirstLast(m); // printing the interchanged matrix for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) System.out.print(m[i][j] + " "); System.out.println(); } }}// This code is contributed by inder_verma # Python3 code to swap the element of# first and last column and display# the result def interchangeFirstLast(mat, n, m): rows = n # swapping of element between # first and last columns for i in range(n): t = mat[i][0]; mat[i][0] = mat[i][n-1]; mat[i][n-1] = t; # Driver Programmat = [[8, 9, 7, 6], [4, 7, 6, 5], [3, 2, 1, 8], [9, 9, 7, 7]] n = 4m = 4interchangeFirstLast(mat, n, m) # printing the interchanged matrixfor i in range(n): for j in range(m): print(mat[i][j], end = " ") print("\n") // C# code to swap the element of first// and last column and display the resultusing System; class GFG{ static int n = 4; static void interchangeFirstLast(int[, ] m){ int cols = n; // swapping of element between first // and last columns for (int i = 0; i < n; i++) { int t = m[i, 0]; m[i, 0] = m[i, n - 1]; m[i, n - 1] = t; }} // Driver Codepublic static void Main (){// input in the arrayint[,] m = { { 8, 9, 7, 6 }, { 4, 7, 6, 5 }, { 3, 2, 1, 8 }, { 9, 9, 7, 7 } }; interchangeFirstLast(m); // printing the interchanged matrixfor (int i = 0; i < n; i++){ for (int j = 0; j < n; j++) Console.Write(m[i, j] + " "); Console.WriteLine();}}} // This code is contributed// by Akanksha Rai <?php// PHP code to swap the element of first// and last column and display the result function interchangeFirstLast($m, $n){ $cols = $n; // swapping of element between first // and last columns for ($i = 0; $i < $n; $i++) { $t = $m[$i][0]; $m[$i][0] = $m[$i][$n - 1]; $m[$i][$n - 1] = $t; } return $m ;} // Driver Code // input in the array$m = array( array( 8, 9, 7, 6 ), array (4, 7, 6, 5 ), array (3, 2, 1, 8 ), array (9, 9, 7, 7 )); $n = 4 ;$m = interchangeFirstLast($m,$n); // printing the interchanged matrixfor ($i = 0; $i < $n; $i++){ for ($j = 0; $j < $n; $j++) echo $m[$i][$j], " "; echo "\n" ;} // This code is contributed by Ryuga?> <script> // Javascript code to swap the element of first// and last column and display the resultn = 4 function interchangeFirstLast(m){ // swapping of element between first // and last columns for (var i = 0; i < n; i++) { var t = m[i][0]; m[i][0] = m[i][n - 1]; m[i][n - 1] = t; }} // Driver function// input in the arraym = [ [ 8, 9, 7, 6 ], [ 4, 7, 6, 5 ], [ 3, 2, 1, 8 ], [ 9, 9, 7, 7 ] ];interchangeFirstLast(m); // printing the interchanged matrixfor (var i = 0; i < n; i++){ for (var j = 0; j < n; j++) document.write( m[i][j] + " "); document.write("<br>");} // This code is contributed by noob2000.</script> 6 9 7 8 5 7 6 4 8 2 1 3 7 9 7 9 inderDuMCA ankthon Akanksha_Rai sahil_tah noob2000 Matrix School Programming Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum size square sub-matrix with all 1s Sudoku | Backtracking-7 Divide and Conquer | Set 5 (Strassen's Matrix Multiplication) Maximum size rectangle binary sub-matrix with all 1s Program to multiply two matrices Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java C++ Classes and Objects
[ { "code": null, "e": 26289, "s": 26261, "text": "\n19 Apr, 2021" }, { "code": null, "e": 26419, "s": 26289, "text": "Given a 4 x 4 matrix, the task is to interchange the elements of first and last columns and show the resulting matrix.Examples: " }, { "code": null, "e": 26580, "s": 26419, "text": "Input:\n8 9 7 6\n4 7 6 5\n3 2 1 8\n9 9 7 7\nOutput:\n6 9 7 8\n5 7 6 4\n8 2 1 3\n7 9 7 9\n\nInput: \n9 7 5 1\n2 3 4 1\n5 6 6 5\n1 2 3 1\nOutput: \n1 7 5 9\n1 3 4 2\n5 6 6 5\n1 2 3 1" }, { "code": null, "e": 26781, "s": 26582, "text": "The approach is very simple, we can simply swap the elements of first and last column of the matrix in order to get the desired matrix as output.Below is the implementation of the above approach : " }, { "code": null, "e": 26785, "s": 26781, "text": "C++" }, { "code": null, "e": 26790, "s": 26785, "text": "Java" }, { "code": null, "e": 26799, "s": 26790, "text": "Python 3" }, { "code": null, "e": 26802, "s": 26799, "text": "C#" }, { "code": null, "e": 26806, "s": 26802, "text": "PHP" }, { "code": null, "e": 26817, "s": 26806, "text": "Javascript" }, { "code": "// C++ code to swap the element of first// and last column and display the result#include <iostream>using namespace std; #define n 4 void interchangeFirstLast(int m[][n]){ // swapping of element between first // and last columns for (int i = 0; i < n; i++) { int t = m[i][0]; m[i][0] = m[i][n - 1]; m[i][n - 1] = t; }} // Driver functionint main(){ // input in the array int m[n][n] = { { 8, 9, 7, 6 }, { 4, 7, 6, 5 }, { 3, 2, 1, 8 }, { 9, 9, 7, 7 } }; interchangeFirstLast(m); // printing the interchanged matrix for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) cout << m[i][j] << \" \"; cout << endl; }}", "e": 27565, "s": 26817, "text": null }, { "code": "// Java code to swap the element of first// and last column and display the result import java.io.*; class GFG { static int n = 4; static void interchangeFirstLast(int m[][]){ int cols = n; // swapping of element between first // and last columns for (int i = 0; i < n; i++) { int t = m[i][0]; m[i][0] = m[i][n - 1]; m[i][n - 1] = t; }} // Driver function public static void main (String[] args) { // input in the array int m[][] = { { 8, 9, 7, 6 }, { 4, 7, 6, 5 }, { 3, 2, 1, 8 }, { 9, 9, 7, 7 } }; interchangeFirstLast(m); // printing the interchanged matrix for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) System.out.print(m[i][j] + \" \"); System.out.println(); } }}// This code is contributed by inder_verma", "e": 28447, "s": 27565, "text": null }, { "code": "# Python3 code to swap the element of# first and last column and display# the result def interchangeFirstLast(mat, n, m): rows = n # swapping of element between # first and last columns for i in range(n): t = mat[i][0]; mat[i][0] = mat[i][n-1]; mat[i][n-1] = t; # Driver Programmat = [[8, 9, 7, 6], [4, 7, 6, 5], [3, 2, 1, 8], [9, 9, 7, 7]] n = 4m = 4interchangeFirstLast(mat, n, m) # printing the interchanged matrixfor i in range(n): for j in range(m): print(mat[i][j], end = \" \") print(\"\\n\")", "e": 29033, "s": 28447, "text": null }, { "code": "// C# code to swap the element of first// and last column and display the resultusing System; class GFG{ static int n = 4; static void interchangeFirstLast(int[, ] m){ int cols = n; // swapping of element between first // and last columns for (int i = 0; i < n; i++) { int t = m[i, 0]; m[i, 0] = m[i, n - 1]; m[i, n - 1] = t; }} // Driver Codepublic static void Main (){// input in the arrayint[,] m = { { 8, 9, 7, 6 }, { 4, 7, 6, 5 }, { 3, 2, 1, 8 }, { 9, 9, 7, 7 } }; interchangeFirstLast(m); // printing the interchanged matrixfor (int i = 0; i < n; i++){ for (int j = 0; j < n; j++) Console.Write(m[i, j] + \" \"); Console.WriteLine();}}} // This code is contributed// by Akanksha Rai", "e": 29826, "s": 29033, "text": null }, { "code": "<?php// PHP code to swap the element of first// and last column and display the result function interchangeFirstLast($m, $n){ $cols = $n; // swapping of element between first // and last columns for ($i = 0; $i < $n; $i++) { $t = $m[$i][0]; $m[$i][0] = $m[$i][$n - 1]; $m[$i][$n - 1] = $t; } return $m ;} // Driver Code // input in the array$m = array( array( 8, 9, 7, 6 ), array (4, 7, 6, 5 ), array (3, 2, 1, 8 ), array (9, 9, 7, 7 )); $n = 4 ;$m = interchangeFirstLast($m,$n); // printing the interchanged matrixfor ($i = 0; $i < $n; $i++){ for ($j = 0; $j < $n; $j++) echo $m[$i][$j], \" \"; echo \"\\n\" ;} // This code is contributed by Ryuga?>", "e": 30574, "s": 29826, "text": null }, { "code": "<script> // Javascript code to swap the element of first// and last column and display the resultn = 4 function interchangeFirstLast(m){ // swapping of element between first // and last columns for (var i = 0; i < n; i++) { var t = m[i][0]; m[i][0] = m[i][n - 1]; m[i][n - 1] = t; }} // Driver function// input in the arraym = [ [ 8, 9, 7, 6 ], [ 4, 7, 6, 5 ], [ 3, 2, 1, 8 ], [ 9, 9, 7, 7 ] ];interchangeFirstLast(m); // printing the interchanged matrixfor (var i = 0; i < n; i++){ for (var j = 0; j < n; j++) document.write( m[i][j] + \" \"); document.write(\"<br>\");} // This code is contributed by noob2000.</script>", "e": 31286, "s": 30574, "text": null }, { "code": null, "e": 31321, "s": 31286, "text": "6 9 7 8 \n5 7 6 4 \n8 2 1 3 \n7 9 7 9" }, { "code": null, "e": 31334, "s": 31323, "text": "inderDuMCA" }, { "code": null, "e": 31342, "s": 31334, "text": "ankthon" }, { "code": null, "e": 31355, "s": 31342, "text": "Akanksha_Rai" }, { "code": null, "e": 31365, "s": 31355, "text": "sahil_tah" }, { "code": null, "e": 31374, "s": 31365, "text": "noob2000" }, { "code": null, "e": 31381, "s": 31374, "text": "Matrix" }, { "code": null, "e": 31400, "s": 31381, "text": "School Programming" }, { "code": null, "e": 31407, "s": 31400, "text": "Matrix" }, { "code": null, "e": 31505, "s": 31407, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31548, "s": 31505, "text": "Maximum size square sub-matrix with all 1s" }, { "code": null, "e": 31572, "s": 31548, "text": "Sudoku | Backtracking-7" }, { "code": null, "e": 31634, "s": 31572, "text": "Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)" }, { "code": null, "e": 31687, "s": 31634, "text": "Maximum size rectangle binary sub-matrix with all 1s" }, { "code": null, "e": 31720, "s": 31687, "text": "Program to multiply two matrices" }, { "code": null, "e": 31738, "s": 31720, "text": "Python Dictionary" }, { "code": null, "e": 31754, "s": 31738, "text": "Arrays in C/C++" }, { "code": null, "e": 31773, "s": 31754, "text": "Inheritance in C++" }, { "code": null, "e": 31798, "s": 31773, "text": "Reverse a string in Java" } ]
How to display loading screen when navigating between routes using Angular? - GeeksforGeeks
12 Mar, 2021 In this post, we will see how to display a loading screen when navigating from one component to another. When the user navigates through routes, the app may communicate with the backend to load some useful data, and it may produce some delay. At that time, if the user doesn’t see anything on the screen, he may think that either the app is broken or something is wrong with the client machine. Hence, it is necessary to keep the user engaged with the app with the help of some message or loading animation. Prerequisites: NPM must be installed Environment Setup: We will create a simple app that will simulate some delays while navigation and show a loading spinner while navigating through routes. Let’s quickly set up the environment: npm install -g @angular/cli ng new <project-name> Project Structure: After executing the above commands, you will get a project structure like this: Project Structure Now execute these commands: cd <project-name> ng serve -o Output: Open http://localhost:4200 and check whether the default angular landing page is loading or not. Follow the below steps: Step 1: We will be loading data from a JSON file instead of an actual server. In src/assets/ create a new file data.json and add the following data.data.json:{ "K.S. Williamson": 0, "S.P.D. Smith": 0, "M. Labuschagne": 0, "J.E. Root": 0, "V. Kohli": 0, "Babar Azam": 0, "H.M. Nicholls": 0, "C.A. Pujara": 0, "D.A. Warner": 0, "B.A. Stokes": 0, "Gerard Abood": 1, "Afzaal Ahmed": 1, "Mesbahuddin Ahmed": 1, "Tanvir Ahmed": 1, "Javed Akhtar": 1, "A. F. M. Akhtaruddin": 1, "Rizwan Akram": 1, "Jahangir Alam": 1, "Brian Aldridge": 1 } Step 1: We will be loading data from a JSON file instead of an actual server. In src/assets/ create a new file data.json and add the following data. data.json: { "K.S. Williamson": 0, "S.P.D. Smith": 0, "M. Labuschagne": 0, "J.E. Root": 0, "V. Kohli": 0, "Babar Azam": 0, "H.M. Nicholls": 0, "C.A. Pujara": 0, "D.A. Warner": 0, "B.A. Stokes": 0, "Gerard Abood": 1, "Afzaal Ahmed": 1, "Mesbahuddin Ahmed": 1, "Tanvir Ahmed": 1, "Javed Akhtar": 1, "A. F. M. Akhtaruddin": 1, "Rizwan Akram": 1, "Jahangir Alam": 1, "Brian Aldridge": 1 } Step 2: To read this data we will use HttpClient module of angular. We need to register it in the file app.module.ts.app.module.tsapp.module.tsimport { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module';import { AppComponent } from './app.component';// Import this moduleimport {HttpClientModule} from '@angular/common/http';@NgModule({ declarations: [ AppComponent, ], imports: [ BrowserModule, AppRoutingModule, HttpClientModule // Register the module here ], providers: [], bootstrap: [AppComponent]})export class AppModule { } Step 2: To read this data we will use HttpClient module of angular. We need to register it in the file app.module.ts. app.module.ts import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module';import { AppComponent } from './app.component';// Import this moduleimport {HttpClientModule} from '@angular/common/http';@NgModule({ declarations: [ AppComponent, ], imports: [ BrowserModule, AppRoutingModule, HttpClientModule // Register the module here ], providers: [], bootstrap: [AppComponent]})export class AppModule { } Step 3: Now create two new components. We will navigate between these two.ng generate component batsman ng generate component umpireIt will generate 4 files for each component. We will understand the code of one of these. The other one will have similar working. In batsman.component.ts, add the following code.batsman.component.tsbatsman.component.tsimport { HttpClient } from '@angular/common/http';import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-batsman', templateUrl: './batsman.component.html', styleUrls: ['./batsman.component.css']})export class BatsmanComponent implements OnInit { constructor(private http:HttpClient) { } batsman = [] ngOnInit(): void { this.http.get('assets/data.json').subscribe( result => { setTimeout(() => { for (let key in result) { if (!result[key]) { this.batsman.push(key); } } }, 2000); } ) } }First, import the HttpClient class. We have created an HttpClient object in the constructor as a dependency injection. We have also initialized an empty batsman array. The get() method of HttpClient will return an Observable which returns the data as the first parameter in its subscribe(result_callback, error_callback) method. In the callback, we have simulated a 2000 ms delay and pushed the names with 0 value. This means that as soon as the page is loaded, there will be a 2 seconds delay and the batsman array will be populated. Now add the following code to batsman.component.html.batsman.component.htmlbatsman.component.html<div *ngIf="!batsman.length"> <div class="spinner-border m-5" role="status"> <span class="sr-only"></span> </div></div> <div *ngIf="batsman.length"> <table> <tr *ngFor="let person of batsman"> <td>{{person}}</td> </tr> </table></div> Step 3: Now create two new components. We will navigate between these two. ng generate component batsman ng generate component umpire It will generate 4 files for each component. We will understand the code of one of these. The other one will have similar working. In batsman.component.ts, add the following code. batsman.component.ts import { HttpClient } from '@angular/common/http';import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-batsman', templateUrl: './batsman.component.html', styleUrls: ['./batsman.component.css']})export class BatsmanComponent implements OnInit { constructor(private http:HttpClient) { } batsman = [] ngOnInit(): void { this.http.get('assets/data.json').subscribe( result => { setTimeout(() => { for (let key in result) { if (!result[key]) { this.batsman.push(key); } } }, 2000); } ) } } First, import the HttpClient class. We have created an HttpClient object in the constructor as a dependency injection. We have also initialized an empty batsman array. The get() method of HttpClient will return an Observable which returns the data as the first parameter in its subscribe(result_callback, error_callback) method. In the callback, we have simulated a 2000 ms delay and pushed the names with 0 value. This means that as soon as the page is loaded, there will be a 2 seconds delay and the batsman array will be populated. Now add the following code to batsman.component.html. batsman.component.html <div *ngIf="!batsman.length"> <div class="spinner-border m-5" role="status"> <span class="sr-only"></span> </div></div> <div *ngIf="batsman.length"> <table> <tr *ngFor="let person of batsman"> <td>{{person}}</td> </tr> </table></div> Step 4: There are two div tags. The first one is displayed when the batsman array is empty. The other one will be displayed when the array is populated. So until the data is not received, we will be viewing the first div which contains the loading animation. The spinner-border class exists in Bootstrap. So we need to add bootstrap to our project. Edit the index.html file as below.index.htmlindex.html<!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8" /> <title>Geeks For Geeks</title> <base href="/" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="icon" type="image/x-icon" href="favicon.ico" /> <!--Add this line--> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous"/> </head> <body> <app-root></app-root> <!--Add these lines--> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.6.0/dist/umd/popper.min.js" integrity="sha384-KsvD1yqQ1/1+IA7gi3P0tyJcT3vR+NdBTt13hSJ2lnve8agRGXTTyNaBYmCR/Nwi" crossorigin="anonymous"> </script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/js/bootstrap.min.js" integrity="sha384-nsg8ua9HAw1y0W1btsyWgBklPnCUAFLuTMS2G72MMONqmOymq585AcH49TLBQObG" crossorigin="anonymous"> </script> </body></html> Step 4: There are two div tags. The first one is displayed when the batsman array is empty. The other one will be displayed when the array is populated. So until the data is not received, we will be viewing the first div which contains the loading animation. The spinner-border class exists in Bootstrap. So we need to add bootstrap to our project. Edit the index.html file as below. index.html <!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8" /> <title>Geeks For Geeks</title> <base href="/" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="icon" type="image/x-icon" href="favicon.ico" /> <!--Add this line--> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous"/> </head> <body> <app-root></app-root> <!--Add these lines--> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.6.0/dist/umd/popper.min.js" integrity="sha384-KsvD1yqQ1/1+IA7gi3P0tyJcT3vR+NdBTt13hSJ2lnve8agRGXTTyNaBYmCR/Nwi" crossorigin="anonymous"> </script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/js/bootstrap.min.js" integrity="sha384-nsg8ua9HAw1y0W1btsyWgBklPnCUAFLuTMS2G72MMONqmOymq585AcH49TLBQObG" crossorigin="anonymous"> </script> </body></html> Step 5: Now add the following codes to umpires.component.ts and umpires.component.html respectively.umpires.component.tsumpires.component.tsimport { HttpClient } from '@angular/common/http';import { Component, OnInit } from '@angular/core';import { CricketService } from '../cricket.service'; @Component({ selector: 'app-umpires', templateUrl: './umpires.component.html', styleUrls: ['./umpires.component.css']})export class UmpiresComponent implements OnInit { constructor(private http:HttpClient) { } umpires = []; ngOnInit(): void { this.http.get('assets/data.json').subscribe( result => { setTimeout(() => { for (let key in result) { if (result[key]) { this.umpires.push(key); } } }, 2000); } ) } }umpires.component.htmlumpires.component.html<div *ngIf="!umpires.length"> <div class="spinner-border m-5" role="status"> <span class="sr-only"></span> </div> </div> <div *ngIf="umpires.length"> <table> <tr *ngFor="let person of umpires"> <td>{{person}}</td> </tr> </table></div> Step 5: Now add the following codes to umpires.component.ts and umpires.component.html respectively. umpires.component.ts import { HttpClient } from '@angular/common/http';import { Component, OnInit } from '@angular/core';import { CricketService } from '../cricket.service'; @Component({ selector: 'app-umpires', templateUrl: './umpires.component.html', styleUrls: ['./umpires.component.css']})export class UmpiresComponent implements OnInit { constructor(private http:HttpClient) { } umpires = []; ngOnInit(): void { this.http.get('assets/data.json').subscribe( result => { setTimeout(() => { for (let key in result) { if (result[key]) { this.umpires.push(key); } } }, 2000); } ) } } umpires.component.html <div *ngIf="!umpires.length"> <div class="spinner-border m-5" role="status"> <span class="sr-only"></span> </div> </div> <div *ngIf="umpires.length"> <table> <tr *ngFor="let person of umpires"> <td>{{person}}</td> </tr> </table></div> Step 6: Create routes for these components in app-routing.module.ts as below:app-routing.module.tsapp-routing.module.tsimport { NgModule } from '@angular/core';import { RouterModule, Routes } from '@angular/router';import { BatsmanComponent } from './batsman/batsman.component';import { UmpiresComponent } from './umpires/umpires.component'; const routes: Routes = [ {path:'batsman', component:BatsmanComponent}, {path:'umpires', component:UmpiresComponent}]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule]})export class AppRoutingModule { } Step 6: Create routes for these components in app-routing.module.ts as below: app-routing.module.ts import { NgModule } from '@angular/core';import { RouterModule, Routes } from '@angular/router';import { BatsmanComponent } from './batsman/batsman.component';import { UmpiresComponent } from './umpires/umpires.component'; const routes: Routes = [ {path:'batsman', component:BatsmanComponent}, {path:'umpires', component:UmpiresComponent}]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule]})export class AppRoutingModule { } Step 7: Add the path in ‘path‘ key and respective component in ‘component‘ key. Import the necessary Components. Now create the links for the user in app.component.html and the coding part is finished:app.component.htmlapp.component.html<div> <a [routerLink]="['batsman']">Batsman</a> || <a [routerLink]="['umpires']">Umpires</a> <router-outlet></router-outlet></div>The above code creates two links that navigate to the respective components. The <router-outlet> tag displays the navigated component. Step 7: Add the path in ‘path‘ key and respective component in ‘component‘ key. Import the necessary Components. Now create the links for the user in app.component.html and the coding part is finished: app.component.html <div> <a [routerLink]="['batsman']">Batsman</a> || <a [routerLink]="['umpires']">Umpires</a> <router-outlet></router-outlet></div> The above code creates two links that navigate to the respective components. The <router-outlet> tag displays the navigated component. Run the below command: ng serve -o Output: AngularJS-Questions AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Angular PrimeNG Dropdown Component Angular PrimeNG Calendar Component Angular 10 (blur) Event Angular PrimeNG Messages Component How to make a Bootstrap Modal Popup in Angular 9/8 ? 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": 26380, "s": 26352, "text": "\n12 Mar, 2021" }, { "code": null, "e": 26888, "s": 26380, "text": "In this post, we will see how to display a loading screen when navigating from one component to another. When the user navigates through routes, the app may communicate with the backend to load some useful data, and it may produce some delay. At that time, if the user doesn’t see anything on the screen, he may think that either the app is broken or something is wrong with the client machine. Hence, it is necessary to keep the user engaged with the app with the help of some message or loading animation." }, { "code": null, "e": 26925, "s": 26888, "text": "Prerequisites: NPM must be installed" }, { "code": null, "e": 27118, "s": 26925, "text": "Environment Setup: We will create a simple app that will simulate some delays while navigation and show a loading spinner while navigating through routes. Let’s quickly set up the environment:" }, { "code": null, "e": 27168, "s": 27118, "text": "npm install -g @angular/cli\nng new <project-name>" }, { "code": null, "e": 27267, "s": 27168, "text": "Project Structure: After executing the above commands, you will get a project structure like this:" }, { "code": null, "e": 27285, "s": 27267, "text": "Project Structure" }, { "code": null, "e": 27313, "s": 27285, "text": "Now execute these commands:" }, { "code": null, "e": 27343, "s": 27313, "text": "cd <project-name>\nng serve -o" }, { "code": null, "e": 27448, "s": 27343, "text": "Output: Open http://localhost:4200 and check whether the default angular landing page is loading or not." }, { "code": null, "e": 27472, "s": 27448, "text": "Follow the below steps:" }, { "code": null, "e": 28080, "s": 27472, "text": "Step 1: We will be loading data from a JSON file instead of an actual server. In src/assets/ create a new file data.json and add the following data.data.json:{\n \"K.S. Williamson\": 0,\n \"S.P.D. Smith\": 0,\n \"M. Labuschagne\": 0,\n \"J.E. Root\": 0,\n \"V. Kohli\": 0,\n \"Babar Azam\": 0,\n \"H.M. Nicholls\": 0,\n \"C.A. Pujara\": 0,\n \"D.A. Warner\": 0,\n \"B.A. Stokes\": 0,\n \"Gerard Abood\": 1,\n \"Afzaal Ahmed\": 1,\n \"Mesbahuddin Ahmed\": 1,\n \"Tanvir Ahmed\": 1,\n \"Javed Akhtar\": 1,\n \"A. F. M. Akhtaruddin\": 1,\n \"Rizwan Akram\": 1,\n \"Jahangir Alam\": 1,\n \"Brian Aldridge\": 1\n}" }, { "code": null, "e": 28229, "s": 28080, "text": "Step 1: We will be loading data from a JSON file instead of an actual server. In src/assets/ create a new file data.json and add the following data." }, { "code": null, "e": 28240, "s": 28229, "text": "data.json:" }, { "code": null, "e": 28690, "s": 28240, "text": "{\n \"K.S. Williamson\": 0,\n \"S.P.D. Smith\": 0,\n \"M. Labuschagne\": 0,\n \"J.E. Root\": 0,\n \"V. Kohli\": 0,\n \"Babar Azam\": 0,\n \"H.M. Nicholls\": 0,\n \"C.A. Pujara\": 0,\n \"D.A. Warner\": 0,\n \"B.A. Stokes\": 0,\n \"Gerard Abood\": 1,\n \"Afzaal Ahmed\": 1,\n \"Mesbahuddin Ahmed\": 1,\n \"Tanvir Ahmed\": 1,\n \"Javed Akhtar\": 1,\n \"A. F. M. Akhtaruddin\": 1,\n \"Rizwan Akram\": 1,\n \"Jahangir Alam\": 1,\n \"Brian Aldridge\": 1\n}" }, { "code": null, "e": 29338, "s": 28690, "text": "Step 2: To read this data we will use HttpClient module of angular. We need to register it in the file app.module.ts.app.module.tsapp.module.tsimport { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module';import { AppComponent } from './app.component';// Import this moduleimport {HttpClientModule} from '@angular/common/http';@NgModule({ declarations: [ AppComponent, ], imports: [ BrowserModule, AppRoutingModule, HttpClientModule // Register the module here ], providers: [], bootstrap: [AppComponent]})export class AppModule { }" }, { "code": null, "e": 29456, "s": 29338, "text": "Step 2: To read this data we will use HttpClient module of angular. We need to register it in the file app.module.ts." }, { "code": null, "e": 29470, "s": 29456, "text": "app.module.ts" }, { "code": "import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module';import { AppComponent } from './app.component';// Import this moduleimport {HttpClientModule} from '@angular/common/http';@NgModule({ declarations: [ AppComponent, ], imports: [ BrowserModule, AppRoutingModule, HttpClientModule // Register the module here ], providers: [], bootstrap: [AppComponent]})export class AppModule { }", "e": 29975, "s": 29470, "text": null }, { "code": null, "e": 31843, "s": 29975, "text": "Step 3: Now create two new components. We will navigate between these two.ng generate component batsman\nng generate component umpireIt will generate 4 files for each component. We will understand the code of one of these. The other one will have similar working. In batsman.component.ts, add the following code.batsman.component.tsbatsman.component.tsimport { HttpClient } from '@angular/common/http';import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-batsman', templateUrl: './batsman.component.html', styleUrls: ['./batsman.component.css']})export class BatsmanComponent implements OnInit { constructor(private http:HttpClient) { } batsman = [] ngOnInit(): void { this.http.get('assets/data.json').subscribe( result => { setTimeout(() => { for (let key in result) { if (!result[key]) { this.batsman.push(key); } } }, 2000); } ) } }First, import the HttpClient class. We have created an HttpClient object in the constructor as a dependency injection. We have also initialized an empty batsman array. The get() method of HttpClient will return an Observable which returns the data as the first parameter in its subscribe(result_callback, error_callback) method. In the callback, we have simulated a 2000 ms delay and pushed the names with 0 value. This means that as soon as the page is loaded, there will be a 2 seconds delay and the batsman array will be populated. Now add the following code to batsman.component.html.batsman.component.htmlbatsman.component.html<div *ngIf=\"!batsman.length\"> <div class=\"spinner-border m-5\" role=\"status\"> <span class=\"sr-only\"></span> </div></div> <div *ngIf=\"batsman.length\"> <table> <tr *ngFor=\"let person of batsman\"> <td>{{person}}</td> </tr> </table></div>" }, { "code": null, "e": 31918, "s": 31843, "text": "Step 3: Now create two new components. We will navigate between these two." }, { "code": null, "e": 31977, "s": 31918, "text": "ng generate component batsman\nng generate component umpire" }, { "code": null, "e": 32157, "s": 31977, "text": "It will generate 4 files for each component. We will understand the code of one of these. The other one will have similar working. In batsman.component.ts, add the following code." }, { "code": null, "e": 32178, "s": 32157, "text": "batsman.component.ts" }, { "code": "import { HttpClient } from '@angular/common/http';import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-batsman', templateUrl: './batsman.component.html', styleUrls: ['./batsman.component.css']})export class BatsmanComponent implements OnInit { constructor(private http:HttpClient) { } batsman = [] ngOnInit(): void { this.http.get('assets/data.json').subscribe( result => { setTimeout(() => { for (let key in result) { if (!result[key]) { this.batsman.push(key); } } }, 2000); } ) } }", "e": 32783, "s": 32178, "text": null }, { "code": null, "e": 33372, "s": 32783, "text": "First, import the HttpClient class. We have created an HttpClient object in the constructor as a dependency injection. We have also initialized an empty batsman array. The get() method of HttpClient will return an Observable which returns the data as the first parameter in its subscribe(result_callback, error_callback) method. In the callback, we have simulated a 2000 ms delay and pushed the names with 0 value. This means that as soon as the page is loaded, there will be a 2 seconds delay and the batsman array will be populated. Now add the following code to batsman.component.html." }, { "code": null, "e": 33395, "s": 33372, "text": "batsman.component.html" }, { "code": "<div *ngIf=\"!batsman.length\"> <div class=\"spinner-border m-5\" role=\"status\"> <span class=\"sr-only\"></span> </div></div> <div *ngIf=\"batsman.length\"> <table> <tr *ngFor=\"let person of batsman\"> <td>{{person}}</td> </tr> </table></div>", "e": 33676, "s": 33395, "text": null }, { "code": null, "e": 35185, "s": 33676, "text": "Step 4: There are two div tags. The first one is displayed when the batsman array is empty. The other one will be displayed when the array is populated. So until the data is not received, we will be viewing the first div which contains the loading animation. The spinner-border class exists in Bootstrap. So we need to add bootstrap to our project. Edit the index.html file as below.index.htmlindex.html<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\" /> <title>Geeks For Geeks</title> <base href=\"/\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" /> <link rel=\"icon\" type=\"image/x-icon\" href=\"favicon.ico\" /> <!--Add this line--> <link href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css\" rel=\"stylesheet\" integrity=\"sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl\" crossorigin=\"anonymous\"/> </head> <body> <app-root></app-root> <!--Add these lines--> <script src=\"https://cdn.jsdelivr.net/npm/@popperjs/core@2.6.0/dist/umd/popper.min.js\" integrity=\"sha384-KsvD1yqQ1/1+IA7gi3P0tyJcT3vR+NdBTt13hSJ2lnve8agRGXTTyNaBYmCR/Nwi\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/js/bootstrap.min.js\" integrity=\"sha384-nsg8ua9HAw1y0W1btsyWgBklPnCUAFLuTMS2G72MMONqmOymq585AcH49TLBQObG\" crossorigin=\"anonymous\"> </script> </body></html>" }, { "code": null, "e": 35569, "s": 35185, "text": "Step 4: There are two div tags. The first one is displayed when the batsman array is empty. The other one will be displayed when the array is populated. So until the data is not received, we will be viewing the first div which contains the loading animation. The spinner-border class exists in Bootstrap. So we need to add bootstrap to our project. Edit the index.html file as below." }, { "code": null, "e": 35580, "s": 35569, "text": "index.html" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\" /> <title>Geeks For Geeks</title> <base href=\"/\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" /> <link rel=\"icon\" type=\"image/x-icon\" href=\"favicon.ico\" /> <!--Add this line--> <link href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css\" rel=\"stylesheet\" integrity=\"sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl\" crossorigin=\"anonymous\"/> </head> <body> <app-root></app-root> <!--Add these lines--> <script src=\"https://cdn.jsdelivr.net/npm/@popperjs/core@2.6.0/dist/umd/popper.min.js\" integrity=\"sha384-KsvD1yqQ1/1+IA7gi3P0tyJcT3vR+NdBTt13hSJ2lnve8agRGXTTyNaBYmCR/Nwi\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/js/bootstrap.min.js\" integrity=\"sha384-nsg8ua9HAw1y0W1btsyWgBklPnCUAFLuTMS2G72MMONqmOymq585AcH49TLBQObG\" crossorigin=\"anonymous\"> </script> </body></html>", "e": 36686, "s": 35580, "text": null }, { "code": null, "e": 37810, "s": 36686, "text": "Step 5: Now add the following codes to umpires.component.ts and umpires.component.html respectively.umpires.component.tsumpires.component.tsimport { HttpClient } from '@angular/common/http';import { Component, OnInit } from '@angular/core';import { CricketService } from '../cricket.service'; @Component({ selector: 'app-umpires', templateUrl: './umpires.component.html', styleUrls: ['./umpires.component.css']})export class UmpiresComponent implements OnInit { constructor(private http:HttpClient) { } umpires = []; ngOnInit(): void { this.http.get('assets/data.json').subscribe( result => { setTimeout(() => { for (let key in result) { if (result[key]) { this.umpires.push(key); } } }, 2000); } ) } }umpires.component.htmlumpires.component.html<div *ngIf=\"!umpires.length\"> <div class=\"spinner-border m-5\" role=\"status\"> <span class=\"sr-only\"></span> </div> </div> <div *ngIf=\"umpires.length\"> <table> <tr *ngFor=\"let person of umpires\"> <td>{{person}}</td> </tr> </table></div>" }, { "code": null, "e": 37911, "s": 37810, "text": "Step 5: Now add the following codes to umpires.component.ts and umpires.component.html respectively." }, { "code": null, "e": 37932, "s": 37911, "text": "umpires.component.ts" }, { "code": "import { HttpClient } from '@angular/common/http';import { Component, OnInit } from '@angular/core';import { CricketService } from '../cricket.service'; @Component({ selector: 'app-umpires', templateUrl: './umpires.component.html', styleUrls: ['./umpires.component.css']})export class UmpiresComponent implements OnInit { constructor(private http:HttpClient) { } umpires = []; ngOnInit(): void { this.http.get('assets/data.json').subscribe( result => { setTimeout(() => { for (let key in result) { if (result[key]) { this.umpires.push(key); } } }, 2000); } ) } }", "e": 38591, "s": 37932, "text": null }, { "code": null, "e": 38614, "s": 38591, "text": "umpires.component.html" }, { "code": "<div *ngIf=\"!umpires.length\"> <div class=\"spinner-border m-5\" role=\"status\"> <span class=\"sr-only\"></span> </div> </div> <div *ngIf=\"umpires.length\"> <table> <tr *ngFor=\"let person of umpires\"> <td>{{person}}</td> </tr> </table></div>", "e": 38896, "s": 38614, "text": null }, { "code": null, "e": 39474, "s": 38896, "text": "Step 6: Create routes for these components in app-routing.module.ts as below:app-routing.module.tsapp-routing.module.tsimport { NgModule } from '@angular/core';import { RouterModule, Routes } from '@angular/router';import { BatsmanComponent } from './batsman/batsman.component';import { UmpiresComponent } from './umpires/umpires.component'; const routes: Routes = [ {path:'batsman', component:BatsmanComponent}, {path:'umpires', component:UmpiresComponent}]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule]})export class AppRoutingModule { }" }, { "code": null, "e": 39552, "s": 39474, "text": "Step 6: Create routes for these components in app-routing.module.ts as below:" }, { "code": null, "e": 39574, "s": 39552, "text": "app-routing.module.ts" }, { "code": "import { NgModule } from '@angular/core';import { RouterModule, Routes } from '@angular/router';import { BatsmanComponent } from './batsman/batsman.component';import { UmpiresComponent } from './umpires/umpires.component'; const routes: Routes = [ {path:'batsman', component:BatsmanComponent}, {path:'umpires', component:UmpiresComponent}]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule]})export class AppRoutingModule { }", "e": 40033, "s": 39574, "text": null }, { "code": null, "e": 40538, "s": 40033, "text": "Step 7: Add the path in ‘path‘ key and respective component in ‘component‘ key. Import the necessary Components. Now create the links for the user in app.component.html and the coding part is finished:app.component.htmlapp.component.html<div> <a [routerLink]=\"['batsman']\">Batsman</a> || <a [routerLink]=\"['umpires']\">Umpires</a> <router-outlet></router-outlet></div>The above code creates two links that navigate to the respective components. The <router-outlet> tag displays the navigated component." }, { "code": null, "e": 40740, "s": 40538, "text": "Step 7: Add the path in ‘path‘ key and respective component in ‘component‘ key. Import the necessary Components. Now create the links for the user in app.component.html and the coding part is finished:" }, { "code": null, "e": 40759, "s": 40740, "text": "app.component.html" }, { "code": "<div> <a [routerLink]=\"['batsman']\">Batsman</a> || <a [routerLink]=\"['umpires']\">Umpires</a> <router-outlet></router-outlet></div>", "e": 40893, "s": 40759, "text": null }, { "code": null, "e": 41028, "s": 40893, "text": "The above code creates two links that navigate to the respective components. The <router-outlet> tag displays the navigated component." }, { "code": null, "e": 41051, "s": 41028, "text": "Run the below command:" }, { "code": null, "e": 41063, "s": 41051, "text": "ng serve -o" }, { "code": null, "e": 41071, "s": 41063, "text": "Output:" }, { "code": null, "e": 41091, "s": 41071, "text": "AngularJS-Questions" }, { "code": null, "e": 41101, "s": 41091, "text": "AngularJS" }, { "code": null, "e": 41118, "s": 41101, "text": "Web Technologies" }, { "code": null, "e": 41216, "s": 41118, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41251, "s": 41216, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 41286, "s": 41251, "text": "Angular PrimeNG Calendar Component" }, { "code": null, "e": 41310, "s": 41286, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 41345, "s": 41310, "text": "Angular PrimeNG Messages Component" }, { "code": null, "e": 41398, "s": 41345, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 41438, "s": 41398, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 41471, "s": 41438, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 41516, "s": 41471, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 41559, "s": 41516, "text": "How to fetch data from an API in ReactJS ?" } ]
Minimum Swaps required to group all 1's together - GeeksforGeeks
09 Aug, 2021 Given an array of 0’s and 1’s, we need to write a program to find the minimum number of swaps required to group all 1’s present in the array together. Examples: Input : arr[] = {1, 0, 1, 0, 1} Output : 1 Explanation: Only 1 swap is required to group all 1's together. Swapping index 1 and 4 will give arr[] = {1, 1, 1, 0, 0} Input : arr[] = {1, 0, 1, 0, 1, 1} Output : 1 A simple solution is to first count total number of 1’s in the array. Suppose this count is x, now we need to find the subarray of length x of this array with maximum number of 1’s. And minimum swaps required will be the number of 0’s in the subarray of length x with maximum number of 1’s. Time Complexity: O(n2) An efficient solution is to optimize the brute force technique of finding the subarray in above approach using the concept of sliding window technique. We can maintain a preCount array to find number of 1’s present in a subarray in O(1) time complexity. Below is the implementation of above idea: C++ Java Python3 C# PHP Javascript // C++ program to find minimum swaps// required to group all 1's together#include <iostream>#include <limits.h> using namespace std; // Function to find minimum swaps// to group all 1's togetherint minSwaps(int arr[], int n) { int noOfOnes = 0; // find total number of all in the array for (int i = 0; i < n; i++) { if (arr[i] == 1) noOfOnes++; } // length of subarray to check for int x = noOfOnes; int maxOnes = INT_MIN; // array to store number of 1's upto // ith index int preCompute[n] = {0}; // calculate number of 1's upto ith // index and store in the array preCompute[] if (arr[0] == 1) preCompute[0] = 1; for (int i = 1; i < n; i++) { if (arr[i] == 1) { preCompute[i] = preCompute[i - 1] + 1; } else preCompute[i] = preCompute[i - 1]; } // using sliding window technique to find // max number of ones in subarray of length x for (int i = x - 1; i < n; i++) { if (i == (x - 1)) noOfOnes = preCompute[i]; else noOfOnes = preCompute[i] - preCompute[i - x]; if (maxOnes < noOfOnes) maxOnes = noOfOnes; } // calculate number of zeros in subarray // of length x with maximum number of 1's int noOfZeroes = x - maxOnes; return noOfZeroes;} // Driver Codeint main() { int a[] = {1, 0, 1, 0, 1}; int n = sizeof(a) / sizeof(a[0]); cout << minSwaps(a, n); return 0;} // Java program to find minimum swaps// required to group all 1's together import java.io.*; class GFG { // Function to find minimum swaps// to group all 1's together static int minSwaps(int arr[], int n) { int noOfOnes = 0; // find total number of all in the arrayfor (int i = 0; i < n; i++) { if (arr[i] == 1) noOfOnes++;} // length of subarray to check forint x = noOfOnes; int maxOnes = Integer.MIN_VALUE; // array to store number of 1's upto// ith indexint preCompute[] = new int[n]; // calculate number of 1's upto ith// index and store in the array preCompute[]if (arr[0] == 1) preCompute[0] = 1;for (int i = 1; i < n; i++) { if (arr[i] == 1) { preCompute[i] = preCompute[i - 1] + 1; } else preCompute[i] = preCompute[i - 1];} // using sliding window technique to find// max number of ones in subarray of length xfor (int i = x - 1; i < n; i++) { if (i == (x - 1)) noOfOnes = preCompute[i]; else noOfOnes = preCompute[i] - preCompute[i - x]; if (maxOnes < noOfOnes) maxOnes = noOfOnes;} // calculate number of zeros in subarray// of length x with maximum number of 1'sint noOfZeroes = x - maxOnes; return noOfZeroes;} // Driver Codepublic static void main (String[] args) {int a[] = {1, 0, 1, 0, 1};int n = a.length;System.out.println( minSwaps(a, n)); }} // This code is contributed by vt_m. # Python program to# find minimum swaps# required to group# all 1's together # Function to find minimum swaps# to group all 1's togetherdef minSwaps(arr,n): noOfOnes = 0 # find total number of # all in the array for i in range(n): if (arr[i] == 1): noOfOnes=noOfOnes+1 # length of subarray to check for x = noOfOnes maxOnes = -2147483648 # array to store number of 1's upto # ith index preCompute={} # calculate number of 1's upto ith # index and store in the # array preCompute[] if (arr[0] == 1): preCompute[0] = 1 for i in range(1,n): if (arr[i] == 1): preCompute[i] = preCompute[i - 1] + 1 else: preCompute[i] = preCompute[i - 1] # using sliding window # technique to find # max number of ones in # subarray of length x for i in range(x-1,n): if (i == (x - 1)): noOfOnes = preCompute[i] else: noOfOnes = preCompute[i] - preCompute[i - x] if (maxOnes < noOfOnes): maxOnes = noOfOnes # calculate number of zeros in subarray # of length x with maximum number of 1's noOfZeroes = x - maxOnes return noOfZeroes # Driver code a = [1, 0, 1, 0, 1]n = len(a) print(minSwaps(a, n)) # This code is contributed# by Anant Agarwal. // C# program to find minimum swaps// required to group all 1's together using System; class GFG { // Function to find minimum swaps // to group all 1's together static int minSwaps(int []arr, int n) { int noOfOnes = 0; // find total number of all in the array for (int i = 0; i < n; i++) { if (arr[i] == 1) noOfOnes++; } // length of subarray to check for int x = noOfOnes; int maxOnes = int.MinValue; // array to store number of 1's upto // ith index int []preCompute = new int[n]; // calculate number of 1's upto ith // index and store in the array preCompute[] if (arr[0] == 1) preCompute[0] = 1; for (int i = 1; i < n; i++) { if (arr[i] == 1) { preCompute[i] = preCompute[i - 1] + 1; } else preCompute[i] = preCompute[i - 1]; } // using sliding window technique to find // max number of ones in subarray of length x for (int i = x - 1; i < n; i++) { if (i == (x - 1)) noOfOnes = preCompute[i]; else noOfOnes = preCompute[i] - preCompute[i - x]; if (maxOnes < noOfOnes) maxOnes = noOfOnes; } // calculate number of zeros in subarray // of length x with maximum number of 1's int noOfZeroes = x - maxOnes; return noOfZeroes; } // Driver Code public static void Main () { int []a = {1, 0, 1, 0, 1}; int n = a.Length; Console.WriteLine( minSwaps(a, n)); }} // This code is contributed by vt_m. <?php// PHP program to find minimum swaps// required to group all 1's together // Function to find minimum swaps// to group all 1's togetherfunction minSwaps($arr, $n){ $noOfOnes = 0; // find total number of // all in the array for($i = 0; $i < $n; $i++) { if ($arr[$i] == 1) $noOfOnes++; } // length of subarray // to check for $x = $noOfOnes; $maxOnes = PHP_INT_MIN; // array to store number of // 1's upto ith index $preCompute = array(); // calculate number of 1's // upto ith index and store // in the array preCompute[] if ($arr[0] == 1) $preCompute[0] = 1; for($i = 1; $i < $n; $i++) { if ($arr[$i] == 1) { $preCompute[$i] = $preCompute[$i - 1] + 1; } else $preCompute[$i] = $preCompute[$i - 1]; } // using sliding window // technique to find // max number of ones in // subarray of length x for ( $i = $x - 1; $i < $n; $i++) { if ($i == ($x - 1)) $noOfOnes = $preCompute[$i]; else $noOfOnes = $preCompute[$i] - $preCompute[$i - $x]; if ($maxOnes < $noOfOnes) $maxOnes = $noOfOnes; } // calculate number of zeros in subarray // of length x with maximum number of 1's $noOfZeroes = $x - $maxOnes; return $noOfZeroes;} // Driver Code$a = array(1, 0, 1, 0, 10);$n = count($a);echo minSwaps($a, $n); // This code is contributed by anuj_67.?> <script> // Javascript program to find minimum swaps // required to group all 1's together // Function to find minimum swaps // to group all 1's together function minSwaps(arr, n) { let noOfOnes = 0; // find total number of all in the array for (let i = 0; i < n; i++) { if (arr[i] == 1) noOfOnes++; } // length of subarray to check for let x = noOfOnes; let maxOnes = Number.MIN_VALUE; // array to store number of 1's upto // ith index let preCompute = new Array(n); preCompute.fill(0); // calculate number of 1's upto ith // index and store in the array preCompute[] if (arr[0] == 1) preCompute[0] = 1; for (let i = 1; i < n; i++) { if (arr[i] == 1) { preCompute[i] = preCompute[i - 1] + 1; } else preCompute[i] = preCompute[i - 1]; } // using sliding window technique to find // max number of ones in subarray of length x for (let i = x - 1; i < n; i++) { if (i == (x - 1)) noOfOnes = preCompute[i]; else noOfOnes = preCompute[i] - preCompute[i - x]; if (maxOnes < noOfOnes) maxOnes = noOfOnes; } // calculate number of zeros in subarray // of length x with maximum number of 1's let noOfZeroes = x - maxOnes; return noOfZeroes; } let a = [1, 0, 1, 0, 1]; let n = a.length; document.write( minSwaps(a, n)); </script> 1 Time Complexity: O(n) Auxiliary Space: O(n) Another efficient approach : First count total number of 1’s in the array. Suppose this count is x, now find the subarray of length x of this array with maximum number of 1’s using the concept of window-sliding technique. Maintain a variable to find number of 1’s present in a subarray in O(1) extra space and for each sub array maintain maxOnes Variable and at last Return numberOfZeros (numberOfZeroes = x – maxOnes). C++ Java Python3 C# PHP Javascript // C++ code for minimum swaps// required to group all 1's together#include <iostream>#include <limits.h> using namespace std; // Function to find minimum swaps// to group all 1's togetherint minSwaps(int arr[], int n){ int numberOfOnes = 0; // find total number of all 1's in the arrayfor (int i = 0; i < n; i++) { if (arr[i] == 1) numberOfOnes++;} // length of subarray to check forint x = numberOfOnes; int count_ones = 0, maxOnes; // Find 1's for first subarray of length xfor(int i = 0; i < x; i++){ if(arr[i] == 1) count_ones++;} maxOnes = count_ones; // using sliding window technique to find// max number of ones in subarray of length xfor (int i = 1; i <= n-x; i++) { // first remove leading element and check // if it is equal to 1 then decrement the // value of count_ones by 1 if (arr[i-1] == 1) count_ones--; // Now add trailing element and check // if it is equal to 1 Then increment // the value of count_ones by 1 if(arr[i+x-1] == 1) count_ones++; if (maxOnes < count_ones) maxOnes = count_ones;} // calculate number of zeros in subarray// of length x with maximum number of 1'sint numberOfZeroes = x - maxOnes; return numberOfZeroes;} // Driver Codeint main() { int a[] = {0, 0, 1, 0, 1, 1, 0, 0, 1};int n = sizeof(a) / sizeof(a[0]); cout << minSwaps(a, n); return 0; } // java program to find largest number// smaller than equal to n with m set// bits then m-1 0 bits.public class GFG { // Function to find minimum swaps // to group all 1's together static int minSwaps(int arr[], int n) { int numberOfOnes = 0; // find total number of all 1's // in the array for (int i = 0; i < n; i++) { if (arr[i] == 1) numberOfOnes++; } // length of subarray to check for int x = numberOfOnes; int count_ones = 0, maxOnes; // Find 1's for first subarray // of length x for(int i = 0; i < x; i++){ if(arr[i] == 1) count_ones++; } maxOnes = count_ones; // using sliding window technique // to find max number of ones in // subarray of length x for (int i = 1; i <= n-x; i++) { // first remove leading element // and check if it is equal to // 1 then decrement the // value of count_ones by 1 if (arr[i - 1] == 1) count_ones--; // Now add trailing element // and check if it is equal // to 1 Then increment the // value of count_ones by 1 if(arr[i + x - 1] == 1) count_ones++; if (maxOnes < count_ones) maxOnes = count_ones; } // calculate number of zeros in // subarray of length x with // maximum number of 1's int numberOfZeroes = x - maxOnes; return numberOfZeroes; } // Driver code public static void main(String args[]) { int a[] = new int[]{0, 0, 1, 0, 1, 1, 0, 0, 1}; int n = a.length; System.out.println(minSwaps(a, n)); }} // This code is contributed by Sam007 # Python code for minimum# swaps required to group# all 1's together # Function to find minimum# swaps to group all 1's# togetherdef minSwaps(arr, n) : numberOfOnes = 0 # find total number of # all 1's in the array for i in range(0, n) : if (arr[i] == 1) : numberOfOnes = numberOfOnes + 1 # length of subarray # to check for x = numberOfOnes count_ones = 0 maxOnes = 0 # Find 1's for first # subarray of length x for i in range(0, x) : if(arr[i] == 1) : count_ones = count_ones + 1 maxOnes = count_ones # using sliding window # technique to find # max number of ones in # subarray of length x for i in range(1, (n - x + 1)) : # first remove leading # element and check # if it is equal to 1 # then decrement the # value of count_ones by 1 if (arr[i - 1] == 1) : count_ones = count_ones - 1 # Now add trailing # element and check # if it is equal to 1 # Then increment # the value of count_ones by 1 if(arr[i + x - 1] == 1) : count_ones = count_ones + 1 if (maxOnes < count_ones) : maxOnes = count_ones # calculate number of # zeros in subarray # of length x with # maximum number of 1's numberOfZeroes = x - maxOnes return numberOfZeroes # Driver Codea = [0, 0, 1, 0, 1, 1, 0, 0, 1]n = 9print (minSwaps(a, n)) # This code is contributed# by Manish Shaw(manishshaw1) // C# code for minimum swaps// required to group all 1's togetherusing System; class GFG{ // Function to find minimum swaps // to group all 1's together static int minSwaps(int []arr, int n) { int numberOfOnes = 0; // find total number of all 1's in the array for (int i = 0; i < n; i++) { if (arr[i] == 1) numberOfOnes++; } // length of subarray to check for int x = numberOfOnes; int count_ones = 0, maxOnes; // Find 1's for first subarray of length x for(int i = 0; i < x; i++){ if(arr[i] == 1) count_ones++; } maxOnes = count_ones; // using sliding window technique to find // max number of ones in subarray of length x for (int i = 1; i <= n-x; i++) { // first remove leading element and check // if it is equal to 1 then decrement the // value of count_ones by 1 if (arr[i - 1] == 1) count_ones--; // Now add trailing element and check // if it is equal to 1 Then increment // the value of count_ones by 1 if(arr[i + x - 1] == 1) count_ones++; if (maxOnes < count_ones) maxOnes = count_ones; } // calculate number of zeros in subarray // of length x with maximum number of 1's int numberOfZeroes = x - maxOnes; return numberOfZeroes; } // Driver Code static public void Main () { int []a = {0, 0, 1, 0, 1, 1, 0, 0, 1}; int n = a.Length; Console.WriteLine(minSwaps(a, n)); }}// This code is contributed by vt_m. <?php// PHP code for minimum swaps// required to group all 1's together // Function to find minimum swaps// to group all 1's togetherfunction minSwaps($arr, $n){ $numberOfOnes = 0; // find total number of // all 1's in the array for ($i = 0; $i < $n; $i++) { if ($arr[$i] == 1) $numberOfOnes++; } // length of subarray to check for $x = $numberOfOnes; $count_ones = 0; $maxOnes; // Find 1's for first // subarray of length x for($i = 0; $i < $x; $i++) { if($arr[$i] == 1) $count_ones++; } $maxOnes = $count_ones; // using sliding window // technique to find // max number of ones in // subarray of length x for ($i = 1; $i <= $n - $x; $i++) { // first remove leading // element and check // if it is equal to 1 // then decrement the // value of count_ones by 1 if ($arr[$i - 1] === 1) $count_ones--; // Now add trailing // element and check // if it is equal to 1 // Then increment // the value of count_ones by 1 if($arr[$i + $x - 1] === 1) $count_ones++; if ($maxOnes < $count_ones) $maxOnes = $count_ones; } // calculate number of zeros in subarray // of length x with maximum number of 1's $numberOfZeroes = $x - $maxOnes; return $numberOfZeroes;} // Driver Code$a = array(0, 0, 1, 0, 1, 1, 0, 0, 1);$n = 9;echo minSwaps($a, $n); // This code is contributed by Anuj_67?> <script> // Javascript code for minimum swaps // required to group all 1's together // Function to find minimum swaps // to group all 1's together function minSwaps(arr, n) { let numberOfOnes = 0; // find total number of all 1's in the array for (let i = 0; i < n; i++) { if (arr[i] == 1) numberOfOnes++; } // length of subarray to check for let x = numberOfOnes; let count_ones = 0, maxOnes; // Find 1's for first subarray of length x for(let i = 0; i < x; i++){ if(arr[i] == 1) count_ones++; } maxOnes = count_ones; // using sliding window technique to find // max number of ones in subarray of length x for (let i = 1; i <= n-x; i++) { // first remove leading element and check // if it is equal to 1 then decrement the // value of count_ones by 1 if (arr[i - 1] == 1) count_ones--; // Now add trailing element and check // if it is equal to 1 Then increment // the value of count_ones by 1 if(arr[i + x - 1] == 1) count_ones++; if (maxOnes < count_ones) maxOnes = count_ones; } // calculate number of zeros in subarray // of length x with maximum number of 1's let numberOfZeroes = x - maxOnes; return numberOfZeroes; } let a = [0, 0, 1, 0, 1, 1, 0, 0, 1]; let n = a.length; document.write(minSwaps(a, n)); </script> 1 Time Complexity : O(n) Auxiliary Space : O(1)Thanks to Mr. Gera for suggesting this approach. Sliding window Easy to understand version Algorithm: 1. Store the total no of ones in a variable say count. This will be the window size. 2. Initialise a variable to store maximum no of ones out of all the sub arrays of size count and a variable to store count of ones in current window. 3. Now iterate over the array and as soon as you hit the window size compare the no of ones in that window with the maximum count of ones in all the windows so far and update max count of ones if count of ones in the current window is more. If the first element of window is 1 then decrease the current count. 4. Answer will be total count of ones – max count of ones out of all window. C++ Java Python C# Javascript #include <bits/stdc++.h> using namespace std; int minSwaps(int arr[], int n){ int totalCount = 0; // To store total number of ones // count total no of ones for (int i = 0; i < n; i++) totalCount += arr[i]; int currCount = 0; // To store count of ones in current window int maxCount = 0; // To store maximum count ones out of all windows int i = 0; // start of window int j = 0; // end of window while (j < n) { currCount += arr[j]; // update maxCount when reach window size i.e. total count of ones in array if ((j - i + 1) == totalCount) { maxCount = max(maxCount, currCount); if (arr[i] == 1) currCount--; // decrease current count if first element of window is 1 i++; // slide window } j++; } return totalCount - maxCount; // return total no of ones in array - maximum count of ones out of all windows} // Driver Codeint main(){ int a[] = {1, 0, 1, 0, 1, 1}; int n = sizeof(a) / sizeof(a[0]); cout << minSwaps(a, n); return 0;} import java.io.*;import java.util.*; class GFG{ static int minSwaps(int[] arr, int n){ // To store total number of ones int totalCount = 0; // Count total no of ones int i; for(i = 0; i < n; i++) totalCount += arr[i]; int currCount = 0; // To store count of ones in current window int maxCount = 0; // To store maximum count ones out // of all windows // start of window i = 0; // end of window int j = 0; while (j < n) { currCount += arr[j]; // update maxCount when reach window size i.e. // total count of ones in array if ((j - i + 1) == totalCount) { maxCount = Math.max(maxCount, currCount); if (arr[i] == 1) currCount--; // decrease current count // if first element of // window is 1 // slide window i++; } j++; } return totalCount - maxCount; // return total no of ones in array // - maximum count of ones out of // all windows} // Driver Codepublic static void main(String args[]) { int[] a = { 1, 0, 1, 0, 1, 1 }; int n = a.length; System.out.println(minSwaps(a, n));}} // This code is contributed by shivanisinghss2110 def minSwaps(arr, n): # To store total number of ones totalCount = 0 # count total no of ones for i in range(0,n): totalCount += arr[i] currCount = 0 # To store count of ones in current window maxCount = 0 # To store maximum count ones out of all windows i = 0 # start of window j = 0 # end of window while (j < n): currCount += arr[j] # update maxCount when reach window size i.e. total count of ones in array if ((j - i + 1) == totalCount): maxCount = max(maxCount, currCount) if (arr[i] == 1): currCount -= 1 # decrease current count if first element of window is 1 i += 1 # slide window j += 1 return totalCount - maxCount # return total no of ones in array - maximum count of ones out of all windows # Driver Codea = [1, 0, 1, 0, 1, 1]n = len(a)print(minSwaps(a, n)) # this code is contributed by shivanisighss2110 using System; class GFG{ static int minSwaps(int[] arr, int n){ // To store total number of ones int totalCount = 0; // Count total no of ones int i; for(i = 0; i < n; i++) totalCount += arr[i]; int currCount = 0; // To store count of ones in current window int maxCount = 0; // To store maximum count ones out // of all windows // start of window i = 0; // end of window int j = 0; while (j < n) { currCount += arr[j]; // update maxCount when reach window size i.e. // total count of ones in array if ((j - i + 1) == totalCount) { maxCount = Math.Max(maxCount, currCount); if (arr[i] == 1) currCount--; // decrease current count // if first element of // window is 1 // slide window i++; } j++; } return totalCount - maxCount; // return total no of ones in array // - maximum count of ones out of // all windows} // Driver Codepublic static void Main(){ int[] a = { 1, 0, 1, 0, 1, 1 }; int n = a.Length; Console.WriteLine(minSwaps(a, n));}} // This code is contributed by ukasp <script> function minSwaps(arr, n){ // To store total number of ones let totalCount = 0; // Count total no of ones let i; for(i = 0; i < n; i++) totalCount += arr[i]; let currCount = 0; // To store count of ones in current window let maxCount = 0; // To store maximum count ones out // of all windows // start of window i = 0; // end of window let j = 0; while (j < n) { currCount += arr[j]; // update maxCount when reach window size i.e. // total count of ones in array if ((j - i + 1) == totalCount) { maxCount = Math.max(maxCount, currCount); if (arr[i] == 1) currCount--; // decrease current count // if first element of // window is 1 // slide window i++; } j++; } return totalCount - maxCount; // return total no of ones in array // - maximum count of ones out of // all windows} // Driver Code let a = [ 1, 0, 1, 0, 1, 1 ]; let n = a.length; document.write(minSwaps(a, n)); // This code is contributed by shivanisinghss2110 </script> 1 Complexities: Time: O(n) Space: O(1) Sam007 vt_m manishshaw1 shubham_singh priyanka dahiya mukesh07 suresh07 ukasp shivanisinghss2110 akshaysingh98088 prefix-sum sliding-window Arrays prefix-sum sliding-window Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Stack Data Structure (Introduction and Program) Introduction to Arrays Multidimensional Arrays in Java Linear Search Linked List vs Array Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Python | Using 2D arrays/lists the right way Search an element in a sorted and rotated array
[ { "code": null, "e": 26195, "s": 26167, "text": "\n09 Aug, 2021" }, { "code": null, "e": 26346, "s": 26195, "text": "Given an array of 0’s and 1’s, we need to write a program to find the minimum number of swaps required to group all 1’s present in the array together." }, { "code": null, "e": 26357, "s": 26346, "text": "Examples: " }, { "code": null, "e": 26569, "s": 26357, "text": "Input : arr[] = {1, 0, 1, 0, 1}\nOutput : 1\nExplanation: Only 1 swap is required to \ngroup all 1's together. Swapping index 1\nand 4 will give arr[] = {1, 1, 1, 0, 0}\n\nInput : arr[] = {1, 0, 1, 0, 1, 1}\nOutput : 1" }, { "code": null, "e": 26883, "s": 26569, "text": "A simple solution is to first count total number of 1’s in the array. Suppose this count is x, now we need to find the subarray of length x of this array with maximum number of 1’s. And minimum swaps required will be the number of 0’s in the subarray of length x with maximum number of 1’s. Time Complexity: O(n2)" }, { "code": null, "e": 27137, "s": 26883, "text": "An efficient solution is to optimize the brute force technique of finding the subarray in above approach using the concept of sliding window technique. We can maintain a preCount array to find number of 1’s present in a subarray in O(1) time complexity." }, { "code": null, "e": 27181, "s": 27137, "text": "Below is the implementation of above idea: " }, { "code": null, "e": 27185, "s": 27181, "text": "C++" }, { "code": null, "e": 27190, "s": 27185, "text": "Java" }, { "code": null, "e": 27198, "s": 27190, "text": "Python3" }, { "code": null, "e": 27201, "s": 27198, "text": "C#" }, { "code": null, "e": 27205, "s": 27201, "text": "PHP" }, { "code": null, "e": 27216, "s": 27205, "text": "Javascript" }, { "code": "// C++ program to find minimum swaps// required to group all 1's together#include <iostream>#include <limits.h> using namespace std; // Function to find minimum swaps// to group all 1's togetherint minSwaps(int arr[], int n) { int noOfOnes = 0; // find total number of all in the array for (int i = 0; i < n; i++) { if (arr[i] == 1) noOfOnes++; } // length of subarray to check for int x = noOfOnes; int maxOnes = INT_MIN; // array to store number of 1's upto // ith index int preCompute[n] = {0}; // calculate number of 1's upto ith // index and store in the array preCompute[] if (arr[0] == 1) preCompute[0] = 1; for (int i = 1; i < n; i++) { if (arr[i] == 1) { preCompute[i] = preCompute[i - 1] + 1; } else preCompute[i] = preCompute[i - 1]; } // using sliding window technique to find // max number of ones in subarray of length x for (int i = x - 1; i < n; i++) { if (i == (x - 1)) noOfOnes = preCompute[i]; else noOfOnes = preCompute[i] - preCompute[i - x]; if (maxOnes < noOfOnes) maxOnes = noOfOnes; } // calculate number of zeros in subarray // of length x with maximum number of 1's int noOfZeroes = x - maxOnes; return noOfZeroes;} // Driver Codeint main() { int a[] = {1, 0, 1, 0, 1}; int n = sizeof(a) / sizeof(a[0]); cout << minSwaps(a, n); return 0;}", "e": 28574, "s": 27216, "text": null }, { "code": "// Java program to find minimum swaps// required to group all 1's together import java.io.*; class GFG { // Function to find minimum swaps// to group all 1's together static int minSwaps(int arr[], int n) { int noOfOnes = 0; // find total number of all in the arrayfor (int i = 0; i < n; i++) { if (arr[i] == 1) noOfOnes++;} // length of subarray to check forint x = noOfOnes; int maxOnes = Integer.MIN_VALUE; // array to store number of 1's upto// ith indexint preCompute[] = new int[n]; // calculate number of 1's upto ith// index and store in the array preCompute[]if (arr[0] == 1) preCompute[0] = 1;for (int i = 1; i < n; i++) { if (arr[i] == 1) { preCompute[i] = preCompute[i - 1] + 1; } else preCompute[i] = preCompute[i - 1];} // using sliding window technique to find// max number of ones in subarray of length xfor (int i = x - 1; i < n; i++) { if (i == (x - 1)) noOfOnes = preCompute[i]; else noOfOnes = preCompute[i] - preCompute[i - x]; if (maxOnes < noOfOnes) maxOnes = noOfOnes;} // calculate number of zeros in subarray// of length x with maximum number of 1'sint noOfZeroes = x - maxOnes; return noOfZeroes;} // Driver Codepublic static void main (String[] args) {int a[] = {1, 0, 1, 0, 1};int n = a.length;System.out.println( minSwaps(a, n)); }} // This code is contributed by vt_m.", "e": 29927, "s": 28574, "text": null }, { "code": "# Python program to# find minimum swaps# required to group# all 1's together # Function to find minimum swaps# to group all 1's togetherdef minSwaps(arr,n): noOfOnes = 0 # find total number of # all in the array for i in range(n): if (arr[i] == 1): noOfOnes=noOfOnes+1 # length of subarray to check for x = noOfOnes maxOnes = -2147483648 # array to store number of 1's upto # ith index preCompute={} # calculate number of 1's upto ith # index and store in the # array preCompute[] if (arr[0] == 1): preCompute[0] = 1 for i in range(1,n): if (arr[i] == 1): preCompute[i] = preCompute[i - 1] + 1 else: preCompute[i] = preCompute[i - 1] # using sliding window # technique to find # max number of ones in # subarray of length x for i in range(x-1,n): if (i == (x - 1)): noOfOnes = preCompute[i] else: noOfOnes = preCompute[i] - preCompute[i - x] if (maxOnes < noOfOnes): maxOnes = noOfOnes # calculate number of zeros in subarray # of length x with maximum number of 1's noOfZeroes = x - maxOnes return noOfZeroes # Driver code a = [1, 0, 1, 0, 1]n = len(a) print(minSwaps(a, n)) # This code is contributed# by Anant Agarwal.", "e": 31274, "s": 29927, "text": null }, { "code": "// C# program to find minimum swaps// required to group all 1's together using System; class GFG { // Function to find minimum swaps // to group all 1's together static int minSwaps(int []arr, int n) { int noOfOnes = 0; // find total number of all in the array for (int i = 0; i < n; i++) { if (arr[i] == 1) noOfOnes++; } // length of subarray to check for int x = noOfOnes; int maxOnes = int.MinValue; // array to store number of 1's upto // ith index int []preCompute = new int[n]; // calculate number of 1's upto ith // index and store in the array preCompute[] if (arr[0] == 1) preCompute[0] = 1; for (int i = 1; i < n; i++) { if (arr[i] == 1) { preCompute[i] = preCompute[i - 1] + 1; } else preCompute[i] = preCompute[i - 1]; } // using sliding window technique to find // max number of ones in subarray of length x for (int i = x - 1; i < n; i++) { if (i == (x - 1)) noOfOnes = preCompute[i]; else noOfOnes = preCompute[i] - preCompute[i - x]; if (maxOnes < noOfOnes) maxOnes = noOfOnes; } // calculate number of zeros in subarray // of length x with maximum number of 1's int noOfZeroes = x - maxOnes; return noOfZeroes; } // Driver Code public static void Main () { int []a = {1, 0, 1, 0, 1}; int n = a.Length; Console.WriteLine( minSwaps(a, n)); }} // This code is contributed by vt_m.", "e": 33023, "s": 31274, "text": null }, { "code": "<?php// PHP program to find minimum swaps// required to group all 1's together // Function to find minimum swaps// to group all 1's togetherfunction minSwaps($arr, $n){ $noOfOnes = 0; // find total number of // all in the array for($i = 0; $i < $n; $i++) { if ($arr[$i] == 1) $noOfOnes++; } // length of subarray // to check for $x = $noOfOnes; $maxOnes = PHP_INT_MIN; // array to store number of // 1's upto ith index $preCompute = array(); // calculate number of 1's // upto ith index and store // in the array preCompute[] if ($arr[0] == 1) $preCompute[0] = 1; for($i = 1; $i < $n; $i++) { if ($arr[$i] == 1) { $preCompute[$i] = $preCompute[$i - 1] + 1; } else $preCompute[$i] = $preCompute[$i - 1]; } // using sliding window // technique to find // max number of ones in // subarray of length x for ( $i = $x - 1; $i < $n; $i++) { if ($i == ($x - 1)) $noOfOnes = $preCompute[$i]; else $noOfOnes = $preCompute[$i] - $preCompute[$i - $x]; if ($maxOnes < $noOfOnes) $maxOnes = $noOfOnes; } // calculate number of zeros in subarray // of length x with maximum number of 1's $noOfZeroes = $x - $maxOnes; return $noOfZeroes;} // Driver Code$a = array(1, 0, 1, 0, 10);$n = count($a);echo minSwaps($a, $n); // This code is contributed by anuj_67.?>", "e": 34783, "s": 33023, "text": null }, { "code": "<script> // Javascript program to find minimum swaps // required to group all 1's together // Function to find minimum swaps // to group all 1's together function minSwaps(arr, n) { let noOfOnes = 0; // find total number of all in the array for (let i = 0; i < n; i++) { if (arr[i] == 1) noOfOnes++; } // length of subarray to check for let x = noOfOnes; let maxOnes = Number.MIN_VALUE; // array to store number of 1's upto // ith index let preCompute = new Array(n); preCompute.fill(0); // calculate number of 1's upto ith // index and store in the array preCompute[] if (arr[0] == 1) preCompute[0] = 1; for (let i = 1; i < n; i++) { if (arr[i] == 1) { preCompute[i] = preCompute[i - 1] + 1; } else preCompute[i] = preCompute[i - 1]; } // using sliding window technique to find // max number of ones in subarray of length x for (let i = x - 1; i < n; i++) { if (i == (x - 1)) noOfOnes = preCompute[i]; else noOfOnes = preCompute[i] - preCompute[i - x]; if (maxOnes < noOfOnes) maxOnes = noOfOnes; } // calculate number of zeros in subarray // of length x with maximum number of 1's let noOfZeroes = x - maxOnes; return noOfZeroes; } let a = [1, 0, 1, 0, 1]; let n = a.length; document.write( minSwaps(a, n)); </script>", "e": 36483, "s": 34783, "text": null }, { "code": null, "e": 36485, "s": 36483, "text": "1" }, { "code": null, "e": 36529, "s": 36485, "text": "Time Complexity: O(n) Auxiliary Space: O(n)" }, { "code": null, "e": 36949, "s": 36529, "text": "Another efficient approach : First count total number of 1’s in the array. Suppose this count is x, now find the subarray of length x of this array with maximum number of 1’s using the concept of window-sliding technique. Maintain a variable to find number of 1’s present in a subarray in O(1) extra space and for each sub array maintain maxOnes Variable and at last Return numberOfZeros (numberOfZeroes = x – maxOnes)." }, { "code": null, "e": 36953, "s": 36949, "text": "C++" }, { "code": null, "e": 36958, "s": 36953, "text": "Java" }, { "code": null, "e": 36966, "s": 36958, "text": "Python3" }, { "code": null, "e": 36969, "s": 36966, "text": "C#" }, { "code": null, "e": 36973, "s": 36969, "text": "PHP" }, { "code": null, "e": 36984, "s": 36973, "text": "Javascript" }, { "code": "// C++ code for minimum swaps// required to group all 1's together#include <iostream>#include <limits.h> using namespace std; // Function to find minimum swaps// to group all 1's togetherint minSwaps(int arr[], int n){ int numberOfOnes = 0; // find total number of all 1's in the arrayfor (int i = 0; i < n; i++) { if (arr[i] == 1) numberOfOnes++;} // length of subarray to check forint x = numberOfOnes; int count_ones = 0, maxOnes; // Find 1's for first subarray of length xfor(int i = 0; i < x; i++){ if(arr[i] == 1) count_ones++;} maxOnes = count_ones; // using sliding window technique to find// max number of ones in subarray of length xfor (int i = 1; i <= n-x; i++) { // first remove leading element and check // if it is equal to 1 then decrement the // value of count_ones by 1 if (arr[i-1] == 1) count_ones--; // Now add trailing element and check // if it is equal to 1 Then increment // the value of count_ones by 1 if(arr[i+x-1] == 1) count_ones++; if (maxOnes < count_ones) maxOnes = count_ones;} // calculate number of zeros in subarray// of length x with maximum number of 1'sint numberOfZeroes = x - maxOnes; return numberOfZeroes;} // Driver Codeint main() { int a[] = {0, 0, 1, 0, 1, 1, 0, 0, 1};int n = sizeof(a) / sizeof(a[0]); cout << minSwaps(a, n); return 0; }", "e": 38345, "s": 36984, "text": null }, { "code": "// java program to find largest number// smaller than equal to n with m set// bits then m-1 0 bits.public class GFG { // Function to find minimum swaps // to group all 1's together static int minSwaps(int arr[], int n) { int numberOfOnes = 0; // find total number of all 1's // in the array for (int i = 0; i < n; i++) { if (arr[i] == 1) numberOfOnes++; } // length of subarray to check for int x = numberOfOnes; int count_ones = 0, maxOnes; // Find 1's for first subarray // of length x for(int i = 0; i < x; i++){ if(arr[i] == 1) count_ones++; } maxOnes = count_ones; // using sliding window technique // to find max number of ones in // subarray of length x for (int i = 1; i <= n-x; i++) { // first remove leading element // and check if it is equal to // 1 then decrement the // value of count_ones by 1 if (arr[i - 1] == 1) count_ones--; // Now add trailing element // and check if it is equal // to 1 Then increment the // value of count_ones by 1 if(arr[i + x - 1] == 1) count_ones++; if (maxOnes < count_ones) maxOnes = count_ones; } // calculate number of zeros in // subarray of length x with // maximum number of 1's int numberOfZeroes = x - maxOnes; return numberOfZeroes; } // Driver code public static void main(String args[]) { int a[] = new int[]{0, 0, 1, 0, 1, 1, 0, 0, 1}; int n = a.length; System.out.println(minSwaps(a, n)); }} // This code is contributed by Sam007", "e": 40325, "s": 38345, "text": null }, { "code": "# Python code for minimum# swaps required to group# all 1's together # Function to find minimum# swaps to group all 1's# togetherdef minSwaps(arr, n) : numberOfOnes = 0 # find total number of # all 1's in the array for i in range(0, n) : if (arr[i] == 1) : numberOfOnes = numberOfOnes + 1 # length of subarray # to check for x = numberOfOnes count_ones = 0 maxOnes = 0 # Find 1's for first # subarray of length x for i in range(0, x) : if(arr[i] == 1) : count_ones = count_ones + 1 maxOnes = count_ones # using sliding window # technique to find # max number of ones in # subarray of length x for i in range(1, (n - x + 1)) : # first remove leading # element and check # if it is equal to 1 # then decrement the # value of count_ones by 1 if (arr[i - 1] == 1) : count_ones = count_ones - 1 # Now add trailing # element and check # if it is equal to 1 # Then increment # the value of count_ones by 1 if(arr[i + x - 1] == 1) : count_ones = count_ones + 1 if (maxOnes < count_ones) : maxOnes = count_ones # calculate number of # zeros in subarray # of length x with # maximum number of 1's numberOfZeroes = x - maxOnes return numberOfZeroes # Driver Codea = [0, 0, 1, 0, 1, 1, 0, 0, 1]n = 9print (minSwaps(a, n)) # This code is contributed# by Manish Shaw(manishshaw1)", "e": 41905, "s": 40325, "text": null }, { "code": "// C# code for minimum swaps// required to group all 1's togetherusing System; class GFG{ // Function to find minimum swaps // to group all 1's together static int minSwaps(int []arr, int n) { int numberOfOnes = 0; // find total number of all 1's in the array for (int i = 0; i < n; i++) { if (arr[i] == 1) numberOfOnes++; } // length of subarray to check for int x = numberOfOnes; int count_ones = 0, maxOnes; // Find 1's for first subarray of length x for(int i = 0; i < x; i++){ if(arr[i] == 1) count_ones++; } maxOnes = count_ones; // using sliding window technique to find // max number of ones in subarray of length x for (int i = 1; i <= n-x; i++) { // first remove leading element and check // if it is equal to 1 then decrement the // value of count_ones by 1 if (arr[i - 1] == 1) count_ones--; // Now add trailing element and check // if it is equal to 1 Then increment // the value of count_ones by 1 if(arr[i + x - 1] == 1) count_ones++; if (maxOnes < count_ones) maxOnes = count_ones; } // calculate number of zeros in subarray // of length x with maximum number of 1's int numberOfZeroes = x - maxOnes; return numberOfZeroes; } // Driver Code static public void Main () { int []a = {0, 0, 1, 0, 1, 1, 0, 0, 1}; int n = a.Length; Console.WriteLine(minSwaps(a, n)); }}// This code is contributed by vt_m.", "e": 43727, "s": 41905, "text": null }, { "code": "<?php// PHP code for minimum swaps// required to group all 1's together // Function to find minimum swaps// to group all 1's togetherfunction minSwaps($arr, $n){ $numberOfOnes = 0; // find total number of // all 1's in the array for ($i = 0; $i < $n; $i++) { if ($arr[$i] == 1) $numberOfOnes++; } // length of subarray to check for $x = $numberOfOnes; $count_ones = 0; $maxOnes; // Find 1's for first // subarray of length x for($i = 0; $i < $x; $i++) { if($arr[$i] == 1) $count_ones++; } $maxOnes = $count_ones; // using sliding window // technique to find // max number of ones in // subarray of length x for ($i = 1; $i <= $n - $x; $i++) { // first remove leading // element and check // if it is equal to 1 // then decrement the // value of count_ones by 1 if ($arr[$i - 1] === 1) $count_ones--; // Now add trailing // element and check // if it is equal to 1 // Then increment // the value of count_ones by 1 if($arr[$i + $x - 1] === 1) $count_ones++; if ($maxOnes < $count_ones) $maxOnes = $count_ones; } // calculate number of zeros in subarray // of length x with maximum number of 1's $numberOfZeroes = $x - $maxOnes; return $numberOfZeroes;} // Driver Code$a = array(0, 0, 1, 0, 1, 1, 0, 0, 1);$n = 9;echo minSwaps($a, $n); // This code is contributed by Anuj_67?>", "e": 45327, "s": 43727, "text": null }, { "code": "<script> // Javascript code for minimum swaps // required to group all 1's together // Function to find minimum swaps // to group all 1's together function minSwaps(arr, n) { let numberOfOnes = 0; // find total number of all 1's in the array for (let i = 0; i < n; i++) { if (arr[i] == 1) numberOfOnes++; } // length of subarray to check for let x = numberOfOnes; let count_ones = 0, maxOnes; // Find 1's for first subarray of length x for(let i = 0; i < x; i++){ if(arr[i] == 1) count_ones++; } maxOnes = count_ones; // using sliding window technique to find // max number of ones in subarray of length x for (let i = 1; i <= n-x; i++) { // first remove leading element and check // if it is equal to 1 then decrement the // value of count_ones by 1 if (arr[i - 1] == 1) count_ones--; // Now add trailing element and check // if it is equal to 1 Then increment // the value of count_ones by 1 if(arr[i + x - 1] == 1) count_ones++; if (maxOnes < count_ones) maxOnes = count_ones; } // calculate number of zeros in subarray // of length x with maximum number of 1's let numberOfZeroes = x - maxOnes; return numberOfZeroes; } let a = [0, 0, 1, 0, 1, 1, 0, 0, 1]; let n = a.length; document.write(minSwaps(a, n)); </script>", "e": 47049, "s": 45327, "text": null }, { "code": null, "e": 47051, "s": 47049, "text": "1" }, { "code": null, "e": 47145, "s": 47051, "text": "Time Complexity : O(n) Auxiliary Space : O(1)Thanks to Mr. Gera for suggesting this approach." }, { "code": null, "e": 47187, "s": 47145, "text": "Sliding window Easy to understand version" }, { "code": null, "e": 47198, "s": 47187, "text": "Algorithm:" }, { "code": null, "e": 47283, "s": 47198, "text": "1. Store the total no of ones in a variable say count. This will be the window size." }, { "code": null, "e": 47433, "s": 47283, "text": "2. Initialise a variable to store maximum no of ones out of all the sub arrays of size count and a variable to store count of ones in current window." }, { "code": null, "e": 47744, "s": 47433, "text": "3. Now iterate over the array and as soon as you hit the window size compare the no of ones in that window with the maximum count of ones in all the windows so far and update max count of ones if count of ones in the current window is more. If the first element of window is 1 then decrease the current count." }, { "code": null, "e": 47821, "s": 47744, "text": "4. Answer will be total count of ones – max count of ones out of all window." }, { "code": null, "e": 47825, "s": 47821, "text": "C++" }, { "code": null, "e": 47830, "s": 47825, "text": "Java" }, { "code": null, "e": 47837, "s": 47830, "text": "Python" }, { "code": null, "e": 47840, "s": 47837, "text": "C#" }, { "code": null, "e": 47851, "s": 47840, "text": "Javascript" }, { "code": "#include <bits/stdc++.h> using namespace std; int minSwaps(int arr[], int n){ int totalCount = 0; // To store total number of ones // count total no of ones for (int i = 0; i < n; i++) totalCount += arr[i]; int currCount = 0; // To store count of ones in current window int maxCount = 0; // To store maximum count ones out of all windows int i = 0; // start of window int j = 0; // end of window while (j < n) { currCount += arr[j]; // update maxCount when reach window size i.e. total count of ones in array if ((j - i + 1) == totalCount) { maxCount = max(maxCount, currCount); if (arr[i] == 1) currCount--; // decrease current count if first element of window is 1 i++; // slide window } j++; } return totalCount - maxCount; // return total no of ones in array - maximum count of ones out of all windows} // Driver Codeint main(){ int a[] = {1, 0, 1, 0, 1, 1}; int n = sizeof(a) / sizeof(a[0]); cout << minSwaps(a, n); return 0;}", "e": 48875, "s": 47851, "text": null }, { "code": "import java.io.*;import java.util.*; class GFG{ static int minSwaps(int[] arr, int n){ // To store total number of ones int totalCount = 0; // Count total no of ones int i; for(i = 0; i < n; i++) totalCount += arr[i]; int currCount = 0; // To store count of ones in current window int maxCount = 0; // To store maximum count ones out // of all windows // start of window i = 0; // end of window int j = 0; while (j < n) { currCount += arr[j]; // update maxCount when reach window size i.e. // total count of ones in array if ((j - i + 1) == totalCount) { maxCount = Math.max(maxCount, currCount); if (arr[i] == 1) currCount--; // decrease current count // if first element of // window is 1 // slide window i++; } j++; } return totalCount - maxCount; // return total no of ones in array // - maximum count of ones out of // all windows} // Driver Codepublic static void main(String args[]) { int[] a = { 1, 0, 1, 0, 1, 1 }; int n = a.length; System.out.println(minSwaps(a, n));}} // This code is contributed by shivanisinghss2110", "e": 50299, "s": 48875, "text": null }, { "code": "def minSwaps(arr, n): # To store total number of ones totalCount = 0 # count total no of ones for i in range(0,n): totalCount += arr[i] currCount = 0 # To store count of ones in current window maxCount = 0 # To store maximum count ones out of all windows i = 0 # start of window j = 0 # end of window while (j < n): currCount += arr[j] # update maxCount when reach window size i.e. total count of ones in array if ((j - i + 1) == totalCount): maxCount = max(maxCount, currCount) if (arr[i] == 1): currCount -= 1 # decrease current count if first element of window is 1 i += 1 # slide window j += 1 return totalCount - maxCount # return total no of ones in array - maximum count of ones out of all windows # Driver Codea = [1, 0, 1, 0, 1, 1]n = len(a)print(minSwaps(a, n)) # this code is contributed by shivanisighss2110", "e": 51327, "s": 50299, "text": null }, { "code": "using System; class GFG{ static int minSwaps(int[] arr, int n){ // To store total number of ones int totalCount = 0; // Count total no of ones int i; for(i = 0; i < n; i++) totalCount += arr[i]; int currCount = 0; // To store count of ones in current window int maxCount = 0; // To store maximum count ones out // of all windows // start of window i = 0; // end of window int j = 0; while (j < n) { currCount += arr[j]; // update maxCount when reach window size i.e. // total count of ones in array if ((j - i + 1) == totalCount) { maxCount = Math.Max(maxCount, currCount); if (arr[i] == 1) currCount--; // decrease current count // if first element of // window is 1 // slide window i++; } j++; } return totalCount - maxCount; // return total no of ones in array // - maximum count of ones out of // all windows} // Driver Codepublic static void Main(){ int[] a = { 1, 0, 1, 0, 1, 1 }; int n = a.Length; Console.WriteLine(minSwaps(a, n));}} // This code is contributed by ukasp", "e": 52697, "s": 51327, "text": null }, { "code": "<script> function minSwaps(arr, n){ // To store total number of ones let totalCount = 0; // Count total no of ones let i; for(i = 0; i < n; i++) totalCount += arr[i]; let currCount = 0; // To store count of ones in current window let maxCount = 0; // To store maximum count ones out // of all windows // start of window i = 0; // end of window let j = 0; while (j < n) { currCount += arr[j]; // update maxCount when reach window size i.e. // total count of ones in array if ((j - i + 1) == totalCount) { maxCount = Math.max(maxCount, currCount); if (arr[i] == 1) currCount--; // decrease current count // if first element of // window is 1 // slide window i++; } j++; } return totalCount - maxCount; // return total no of ones in array // - maximum count of ones out of // all windows} // Driver Code let a = [ 1, 0, 1, 0, 1, 1 ]; let n = a.length; document.write(minSwaps(a, n)); // This code is contributed by shivanisinghss2110 </script>", "e": 54030, "s": 52697, "text": null }, { "code": null, "e": 54032, "s": 54030, "text": "1" }, { "code": null, "e": 54047, "s": 54032, "text": "Complexities: " }, { "code": null, "e": 54058, "s": 54047, "text": "Time: O(n)" }, { "code": null, "e": 54070, "s": 54058, "text": "Space: O(1)" }, { "code": null, "e": 54077, "s": 54070, "text": "Sam007" }, { "code": null, "e": 54082, "s": 54077, "text": "vt_m" }, { "code": null, "e": 54094, "s": 54082, "text": "manishshaw1" }, { "code": null, "e": 54108, "s": 54094, "text": "shubham_singh" }, { "code": null, "e": 54124, "s": 54108, "text": "priyanka dahiya" }, { "code": null, "e": 54133, "s": 54124, "text": "mukesh07" }, { "code": null, "e": 54142, "s": 54133, "text": "suresh07" }, { "code": null, "e": 54148, "s": 54142, "text": "ukasp" }, { "code": null, "e": 54167, "s": 54148, "text": "shivanisinghss2110" }, { "code": null, "e": 54184, "s": 54167, "text": "akshaysingh98088" }, { "code": null, "e": 54195, "s": 54184, "text": "prefix-sum" }, { "code": null, "e": 54210, "s": 54195, "text": "sliding-window" }, { "code": null, "e": 54217, "s": 54210, "text": "Arrays" }, { "code": null, "e": 54228, "s": 54217, "text": "prefix-sum" }, { "code": null, "e": 54243, "s": 54228, "text": "sliding-window" }, { "code": null, "e": 54250, "s": 54243, "text": "Arrays" }, { "code": null, "e": 54348, "s": 54250, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 54416, "s": 54348, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 54460, "s": 54416, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 54508, "s": 54460, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 54531, "s": 54508, "text": "Introduction to Arrays" }, { "code": null, "e": 54563, "s": 54531, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 54577, "s": 54563, "text": "Linear Search" }, { "code": null, "e": 54598, "s": 54577, "text": "Linked List vs Array" }, { "code": null, "e": 54683, "s": 54598, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 54728, "s": 54683, "text": "Python | Using 2D arrays/lists the right way" } ]
Tryit Editor v3.7
Tryit: Text shadow with red neon glow
[]
CodeIgniter - Common Functions
CodeIgniter library functions and helper functions need to be initialized before they are used but there are some common functions, which do not need to be initialized. These common functions and their descriptions are given below. $version (string) − Version number $file (string) − File path $key (string) − Config item key $code (int) − HTTP Response status code $text (string) − A custom message to set with the status code $str (string) − Input string $url_encoded (bool) − Whether to remove URLencoded characters as well $var (mixed) − Variable to escape (string or array) $function_name (string) − Function name Given below is an example, which demonstrates all of the above functions. Here we have created only one controller in which we will use the above functions. Copy the below given code and save it at application/controller/CommonFun_Controller.php. <?php class CommonFun_Controller extends CI_Controller { public function index() { set_status_header(200); echo is_php('5.3')."<br>"; var_dump(is_really_writable('./Form.php')); echo config_item('language')."<br>"; echo remove_invisible_characters('This is a ‌test','UTF8')."<br>"; $str = '< This > is \' a " test & string'; echo html_escape($str)."<br>"; echo "is_https():".var_dump(is_https())."<br>"; echo "is_cli():".var_dump(is_cli())."<br>"; var_dump(function_usable('test'))."<br>"; echo "get_mimes():".print_r(get_mimes())."<br>"; } public function test() { echo "Test function"; } } ?> Change the routes.php file at application/config/routes.php to add route for the above controller and add the following line at the end of the file. $route['commonfunctions'] = 'CommonFun_Controller'; Type the following URL in the address bar of your browser to execute the example. http://yoursite.com/index.php/commonfunctions Print Add Notes Bookmark this page
[ { "code": null, "e": 2488, "s": 2319, "text": "CodeIgniter library functions and helper functions need to be initialized before they are used but there are some common functions, which do not need to be initialized." }, { "code": null, "e": 2551, "s": 2488, "text": "These common functions and their descriptions are given below." }, { "code": null, "e": 2586, "s": 2551, "text": "$version (string) − Version number" }, { "code": null, "e": 2613, "s": 2586, "text": "$file (string) − File path" }, { "code": null, "e": 2645, "s": 2613, "text": "$key (string) − Config item key" }, { "code": null, "e": 2685, "s": 2645, "text": "$code (int) − HTTP Response status code" }, { "code": null, "e": 2747, "s": 2685, "text": "$text (string) − A custom message to set with the status code" }, { "code": null, "e": 2776, "s": 2747, "text": "$str (string) − Input string" }, { "code": null, "e": 2846, "s": 2776, "text": "$url_encoded (bool) − Whether to remove URLencoded characters as well" }, { "code": null, "e": 2898, "s": 2846, "text": "$var (mixed) − Variable to escape (string or array)" }, { "code": null, "e": 2938, "s": 2898, "text": "$function_name (string) − Function name" }, { "code": null, "e": 3012, "s": 2938, "text": "Given below is an example, which demonstrates all of the above functions." }, { "code": null, "e": 3186, "s": 3012, "text": "Here we have created only one controller in which we will use the above functions. Copy the below given code and save it at application/controller/CommonFun_Controller.php." }, { "code": null, "e": 3957, "s": 3186, "text": "<?php \n class CommonFun_Controller extends CI_Controller { \n\t\n public function index() {\n set_status_header(200); \n echo is_php('5.3').\"<br>\"; \n var_dump(is_really_writable('./Form.php')); \n\t\t\t\n echo config_item('language').\"<br>\"; \n echo remove_invisible_characters('This is a ‌test','UTF8').\"<br>\"; \n\t\t\t\n $str = '< This > is \\' a \" test & string'; \n echo html_escape($str).\"<br>\"; \n echo \"is_https():\".var_dump(is_https()).\"<br>\"; \n echo \"is_cli():\".var_dump(is_cli()).\"<br>\"; \n\t\t\t\n var_dump(function_usable('test')).\"<br>\"; \n echo \"get_mimes():\".print_r(get_mimes()).\"<br>\"; \n } \n \n public function test() { \n echo \"Test function\"; \n } \n\t\t\n } \n?>" }, { "code": null, "e": 4106, "s": 3957, "text": "Change the routes.php file at application/config/routes.php to add route for the above controller and add the following line at the end of the file." }, { "code": null, "e": 4159, "s": 4106, "text": "$route['commonfunctions'] = 'CommonFun_Controller';\n" }, { "code": null, "e": 4241, "s": 4159, "text": "Type the following URL in the address bar of your browser to execute the example." }, { "code": null, "e": 4288, "s": 4241, "text": "http://yoursite.com/index.php/commonfunctions\n" }, { "code": null, "e": 4295, "s": 4288, "text": " Print" }, { "code": null, "e": 4306, "s": 4295, "text": " Add Notes" } ]
How to use NumPy where() with multiple conditions in Python ?
05 Apr, 2021 In Python, NumPy has a number of library functions to create the array and where is one of them to create an array from the satisfied conditions of another array. The numpy.where() function returns the indices of elements in an input array where the given condition is satisfied. Syntax: numpy.where(condition[, x, y]) Parameters: condition : When True, yield x, otherwise yield y. x, y : Values from which to choose. x, y and condition need to be broadcastable to some shape. Returns: [ndarray or tuple of ndarrays] If both x and y are specified, the output array contains elements of x where condition is True, and elements from y elsewhere. If the only condition is given, return the tuple condition.nonzero(), the indices where the condition is True. In the above syntax, we can see the where() function can take two arguments in which one is mandatory and another one is optional. If the value of the condition is true an array will be created based on the indices. Example 1: Numpy where() with multiple conditions using logical OR. Python3 # Import NumPy library import numpy as np # Create an array using the list np_arr1 = np.array([23, 11, 45, 43, 60, 18, 33, 71, 52, 38])print("The values of the input array :\n", np_arr1) # Create another array based on the # multiple conditions and one arraynew_arr1 = np.where((np_arr1)) # Print the new arrayprint("The filtered values of the array :\n", new_arr1) # Create an array using range valuesnp_arr2 = np.arange(40, 50) # Create another array based on the # multiple conditions and two arraysnew_arr2 = np.where((np_arr1), np_arr1, np_arr2) # Print the new arrayprint("The filtered values of the array :\n", new_arr2) Output: Example 2: Numpy where() with multiple conditions using logical AND. Python3 # Import NumPy library import numpy as np # Create two arrays of random valuesnp_arr1 = np.random.rand(10)*100np_arr2 = np.random.rand(10)*100 # Print the array valuesprint("\nThe values of the first array :\n", np_arr1)print("\nThe values of the second array :\n", np_arr2) # Create a new array based on the conditionsnew_arr = np.where((np_arr1), np_arr1, np_arr2) # Print the new arrayprint("\nThe filtered values of both arrays :\n", new_arr) Output: Example 3: Numpy where() with multiple conditions in multiple dimensional arrays. Python3 # Import NumPy library import numpy as np # Create two multidimensional arrays of # integer valuesnp_arr1 = np.array([[6, 13, 22, 7, 12], [7, 11, 16, 32, 9]])np_arr2 = np.array([[44, 20, 8, 35, 10], [98, 23, 42, 6, 13]]) # Print the array valuesprint("\nThe values of the first array :\n", np_arr1)print("\nThe values of the second array :\n", np_arr2) # Create a new array from two arrays based on# the conditionsnew_arr = np.where(((np_arr1 % 2 == 0) & (np_arr2 % 2 == 1)), np_arr1, np_arr2) # Print the new arrayprint("\nThe filtered values of both arrays :\n", new_arr) Output: Conclusion: The where() function in NumPy is used for creating a new array from the existing array with multiple numbers of conditions. Picked Python numpy-arrayCreation Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n05 Apr, 2021" }, { "code": null, "e": 334, "s": 54, "text": "In Python, NumPy has a number of library functions to create the array and where is one of them to create an array from the satisfied conditions of another array. The numpy.where() function returns the indices of elements in an input array where the given condition is satisfied." }, { "code": null, "e": 342, "s": 334, "text": "Syntax:" }, { "code": null, "e": 373, "s": 342, "text": "numpy.where(condition[, x, y])" }, { "code": null, "e": 385, "s": 373, "text": "Parameters:" }, { "code": null, "e": 436, "s": 385, "text": "condition : When True, yield x, otherwise yield y." }, { "code": null, "e": 531, "s": 436, "text": "x, y : Values from which to choose. x, y and condition need to be broadcastable to some shape." }, { "code": null, "e": 698, "s": 531, "text": "Returns: [ndarray or tuple of ndarrays] If both x and y are specified, the output array contains elements of x where condition is True, and elements from y elsewhere." }, { "code": null, "e": 1025, "s": 698, "text": "If the only condition is given, return the tuple condition.nonzero(), the indices where the condition is True. In the above syntax, we can see the where() function can take two arguments in which one is mandatory and another one is optional. If the value of the condition is true an array will be created based on the indices." }, { "code": null, "e": 1036, "s": 1025, "text": "Example 1:" }, { "code": null, "e": 1093, "s": 1036, "text": "Numpy where() with multiple conditions using logical OR." }, { "code": null, "e": 1101, "s": 1093, "text": "Python3" }, { "code": "# Import NumPy library import numpy as np # Create an array using the list np_arr1 = np.array([23, 11, 45, 43, 60, 18, 33, 71, 52, 38])print(\"The values of the input array :\\n\", np_arr1) # Create another array based on the # multiple conditions and one arraynew_arr1 = np.where((np_arr1)) # Print the new arrayprint(\"The filtered values of the array :\\n\", new_arr1) # Create an array using range valuesnp_arr2 = np.arange(40, 50) # Create another array based on the # multiple conditions and two arraysnew_arr2 = np.where((np_arr1), np_arr1, np_arr2) # Print the new arrayprint(\"The filtered values of the array :\\n\", new_arr2)", "e": 1759, "s": 1101, "text": null }, { "code": null, "e": 1767, "s": 1759, "text": "Output:" }, { "code": null, "e": 1778, "s": 1767, "text": "Example 2:" }, { "code": null, "e": 1836, "s": 1778, "text": "Numpy where() with multiple conditions using logical AND." }, { "code": null, "e": 1844, "s": 1836, "text": "Python3" }, { "code": "# Import NumPy library import numpy as np # Create two arrays of random valuesnp_arr1 = np.random.rand(10)*100np_arr2 = np.random.rand(10)*100 # Print the array valuesprint(\"\\nThe values of the first array :\\n\", np_arr1)print(\"\\nThe values of the second array :\\n\", np_arr2) # Create a new array based on the conditionsnew_arr = np.where((np_arr1), np_arr1, np_arr2) # Print the new arrayprint(\"\\nThe filtered values of both arrays :\\n\", new_arr)", "e": 2300, "s": 1844, "text": null }, { "code": null, "e": 2308, "s": 2300, "text": "Output:" }, { "code": null, "e": 2319, "s": 2308, "text": "Example 3:" }, { "code": null, "e": 2390, "s": 2319, "text": "Numpy where() with multiple conditions in multiple dimensional arrays." }, { "code": null, "e": 2398, "s": 2390, "text": "Python3" }, { "code": "# Import NumPy library import numpy as np # Create two multidimensional arrays of # integer valuesnp_arr1 = np.array([[6, 13, 22, 7, 12], [7, 11, 16, 32, 9]])np_arr2 = np.array([[44, 20, 8, 35, 10], [98, 23, 42, 6, 13]]) # Print the array valuesprint(\"\\nThe values of the first array :\\n\", np_arr1)print(\"\\nThe values of the second array :\\n\", np_arr2) # Create a new array from two arrays based on# the conditionsnew_arr = np.where(((np_arr1 % 2 == 0) & (np_arr2 % 2 == 1)), np_arr1, np_arr2) # Print the new arrayprint(\"\\nThe filtered values of both arrays :\\n\", new_arr)", "e": 3038, "s": 2398, "text": null }, { "code": null, "e": 3046, "s": 3038, "text": "Output:" }, { "code": null, "e": 3058, "s": 3046, "text": "Conclusion:" }, { "code": null, "e": 3182, "s": 3058, "text": "The where() function in NumPy is used for creating a new array from the existing array with multiple numbers of conditions." }, { "code": null, "e": 3189, "s": 3182, "text": "Picked" }, { "code": null, "e": 3216, "s": 3189, "text": "Python numpy-arrayCreation" }, { "code": null, "e": 3229, "s": 3216, "text": "Python-numpy" }, { "code": null, "e": 3236, "s": 3229, "text": "Python" } ]
list erase() function in C++ STL
24 Jun, 2022 The list::erase() is a built-in function in C++ STL which is used to delete elements from a list container. This function can be used to remove a single element or a range of elements from the specified list container. Syntax: iterator list_name.erase(iterator position) or, iterator list_name.erase(iterator first, iterator last) Parameters: This function can accepts different parameters based on whether it is used to erase a single element or a range of element from the list container. position: This parameter is used when the function is used to delete a single element. This parameter refers to an iterator which points to the element which is need to be erased from the list container. first, last: These two parameters are used when the list is used to erase elements from a range. The parameter first refers to the iterator pointing to the first element in the range and the parameter last refers to the iterator pointing to the last element in the range which is needed to be erased. This erases all the elements in the range including the element pointed by the iterator first but excluding the element pointed by the iterator last. Return Value: This function returns an iterator pointing to the element in the list container which followed the last element erased from the list container. Below programs illustrates the list::erase() function. Program 1: Erasing a single element. CPP // CPP program to illustrate the// list::erase() function#include <bits/stdc++.h>using namespace std; int main(){ // Creating a list list<int> demoList; // Add elements to the List demoList.push_back(10); demoList.push_back(20); demoList.push_back(30); demoList.push_back(40); demoList.push_back(50); // Printing elements of list before deleting // first element cout << "List before deleting first element: "; for (auto itr = demoList.begin(); itr != demoList.end(); itr++) { cout << *itr << " "; } // Creating iterator to point to first // element in the list list<int>::iterator itr = demoList.begin(); // deleting the first element demoList.erase(itr); // Printing elements of list after deleting // first element cout << "\nList after deleting first element:"; for (auto itr = demoList.begin(); itr != demoList.end(); itr++) { cout << *itr << " "; } return 0;} List before deleting first element: 10 20 30 40 50 List after deleting first element:20 30 40 50 Time complexity: O(n) Space complexity: O(1) Program 2: Erasing a range of elements. CPP // CPP program to illustrate the// list::erase() function#include <bits/stdc++.h>using namespace std; int main(){ // Creating a list list<int> demoList; // Add elements to the List demoList.push_back(10); demoList.push_back(20); demoList.push_back(30); demoList.push_back(40); demoList.push_back(50); // Printing elements of list before deleting // any element cout << "List before deleting any element: "; for (auto itr = demoList.begin(); itr != demoList.end(); itr++) { cout << *itr << " "; } // Creating iterators of the list list<int>::iterator itr1, itr2; itr1 = demoList.begin(); itr2 = demoList.begin(); // Incrementing itr2 by 3 positions advance(itr2, 3); // deleting range of elements from index [0, 3) demoList.erase(itr1, itr2); // Printing elements of list after deleting // range of elements from [0, 3) cout << "\nList after deleting first three elements: "; for (auto itr = demoList.begin(); itr != demoList.end(); itr++) { cout << *itr << " "; } return 0;} List before deleting any element: 10 20 30 40 50 List after deleting first three elements: 40 50 Note: This function works in linear time complexity, that is the number of elements erased from the list container. Time complexity: O(n) Space complexity: O(1) polymatir3j CPP-Functions cpp-list STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n24 Jun, 2022" }, { "code": null, "e": 281, "s": 53, "text": "The list::erase() is a built-in function in C++ STL which is used to delete elements from a list container. This function can be used to remove a single element or a range of elements from the specified list container. Syntax: " }, { "code": null, "e": 387, "s": 281, "text": "iterator list_name.erase(iterator position)\n\nor,\n\niterator list_name.erase(iterator first, iterator last)" }, { "code": null, "e": 547, "s": 387, "text": "Parameters: This function can accepts different parameters based on whether it is used to erase a single element or a range of element from the list container." }, { "code": null, "e": 751, "s": 547, "text": "position: This parameter is used when the function is used to delete a single element. This parameter refers to an iterator which points to the element which is need to be erased from the list container." }, { "code": null, "e": 1202, "s": 751, "text": "first, last: These two parameters are used when the list is used to erase elements from a range. The parameter first refers to the iterator pointing to the first element in the range and the parameter last refers to the iterator pointing to the last element in the range which is needed to be erased. This erases all the elements in the range including the element pointed by the iterator first but excluding the element pointed by the iterator last." }, { "code": null, "e": 1453, "s": 1202, "text": "Return Value: This function returns an iterator pointing to the element in the list container which followed the last element erased from the list container. Below programs illustrates the list::erase() function. Program 1: Erasing a single element. " }, { "code": null, "e": 1457, "s": 1453, "text": "CPP" }, { "code": "// CPP program to illustrate the// list::erase() function#include <bits/stdc++.h>using namespace std; int main(){ // Creating a list list<int> demoList; // Add elements to the List demoList.push_back(10); demoList.push_back(20); demoList.push_back(30); demoList.push_back(40); demoList.push_back(50); // Printing elements of list before deleting // first element cout << \"List before deleting first element: \"; for (auto itr = demoList.begin(); itr != demoList.end(); itr++) { cout << *itr << \" \"; } // Creating iterator to point to first // element in the list list<int>::iterator itr = demoList.begin(); // deleting the first element demoList.erase(itr); // Printing elements of list after deleting // first element cout << \"\\nList after deleting first element:\"; for (auto itr = demoList.begin(); itr != demoList.end(); itr++) { cout << *itr << \" \"; } return 0;}", "e": 2429, "s": 1457, "text": null }, { "code": null, "e": 2527, "s": 2429, "text": "List before deleting first element: 10 20 30 40 50 \nList after deleting first element:20 30 40 50" }, { "code": null, "e": 2550, "s": 2527, "text": "Time complexity: O(n) " }, { "code": null, "e": 2573, "s": 2550, "text": "Space complexity: O(1)" }, { "code": null, "e": 2614, "s": 2573, "text": "Program 2: Erasing a range of elements. " }, { "code": null, "e": 2618, "s": 2614, "text": "CPP" }, { "code": "// CPP program to illustrate the// list::erase() function#include <bits/stdc++.h>using namespace std; int main(){ // Creating a list list<int> demoList; // Add elements to the List demoList.push_back(10); demoList.push_back(20); demoList.push_back(30); demoList.push_back(40); demoList.push_back(50); // Printing elements of list before deleting // any element cout << \"List before deleting any element: \"; for (auto itr = demoList.begin(); itr != demoList.end(); itr++) { cout << *itr << \" \"; } // Creating iterators of the list list<int>::iterator itr1, itr2; itr1 = demoList.begin(); itr2 = demoList.begin(); // Incrementing itr2 by 3 positions advance(itr2, 3); // deleting range of elements from index [0, 3) demoList.erase(itr1, itr2); // Printing elements of list after deleting // range of elements from [0, 3) cout << \"\\nList after deleting first three elements: \"; for (auto itr = demoList.begin(); itr != demoList.end(); itr++) { cout << *itr << \" \"; } return 0;}", "e": 3709, "s": 2618, "text": null }, { "code": null, "e": 3807, "s": 3709, "text": "List before deleting any element: 10 20 30 40 50 \nList after deleting first three elements: 40 50" }, { "code": null, "e": 3923, "s": 3807, "text": "Note: This function works in linear time complexity, that is the number of elements erased from the list container." }, { "code": null, "e": 3946, "s": 3923, "text": "Time complexity: O(n) " }, { "code": null, "e": 3969, "s": 3946, "text": "Space complexity: O(1)" }, { "code": null, "e": 3981, "s": 3969, "text": "polymatir3j" }, { "code": null, "e": 3995, "s": 3981, "text": "CPP-Functions" }, { "code": null, "e": 4004, "s": 3995, "text": "cpp-list" }, { "code": null, "e": 4008, "s": 4004, "text": "STL" }, { "code": null, "e": 4012, "s": 4008, "text": "C++" }, { "code": null, "e": 4016, "s": 4012, "text": "STL" }, { "code": null, "e": 4020, "s": 4016, "text": "CPP" } ]
Readonly in C#
28 Nov, 2019 In C#, a readonly keyword is a modifier which is used in the following ways: 1. Readonly Fields: In C#, you are allowed to declare a field using readonly modifier. It indicates that the assignment to the fields is only the part of the declaration or in a constructor to the same class. Such types of fields can only be assigned or reassigned multiple times only at the declaration or in a constructor. They are not assigned after the constructor exit. If the readonly modifier is used with a value type field, then the field is immutable. And if the readonly modifier is used with a reference type field, then the readonly modifier prevents the field from replaced by the different instances of the reference type, here the readonly modifier does not stop the instance data of the field from being modified through the read-only field. In static and instance constructors, you are allowed to pass a readonly field as an out or ref parameter. Example: // C# program to illustrate// how to create a readonly fieldusing System; class GFG { // readonly variables public readonly string str1; public readonly string str2; // Readonly variable // This variable is // initialized at declaration time public readonly string str3 = "gfg"; // The values of the readonly // variables are assigned // Using constructor public GFG(string a, string b) { str1 = a; str2 = b; Console.WriteLine("Display value of string 1 {0}, " + "and string 2 {1}", str1, str2); } // Main method static public void Main() { GFG ob = new GFG("GeeksforGeeks", "GFG"); }} Output: Display value of string 1 GeeksforGeeks, and string 2 GFG Here, the value of the str1 and str2 is assigned in the constructor. 2. Readonly Structure: In the readonly structure, readonly modifier indicates that the given structure is immutable. When you create a readonly structure, it is necessary to use a readonly modifier with its fields, if you do not do this, then the compiler will give an error. Example: // C# program to illustrate how // to create a readonly structureusing System; // Readonly structurepublic readonly struct Author{ public readonly string Name { get; } public readonly int Article { get; } public readonly string Branch { get; } public Author(string name, int article, string branch) { this.Name = name; this.Article = article; this.Branch = branch; }} class GFG { // Main method static public void Main() { Author a = new Author("Rohit", 67, "CSE"); Console.WriteLine("Author name: " + a.Name); Console.WriteLine("Total articles: " + a.Article); Console.WriteLine("Branch name: " + a.Branch); }} Output: Author name: Rohit Total articles: 67 Branch name: CSE 3. Readonly Members: This feature is introduced in C# 8.0. In this feature, you are allowed to use a readonly modifier to any member of the structure. This readonly modifier specifies that the member is not allowed to modify. It is better than applying the whole structure readonly. Example: // C# program to illustrate how // to create a readonly memberusing System; public struct Customer{ public string Name { get; } public int Price { get; } // Readonly member public readonly string Product { get; } public Customer(string name, string product, int price) { this.Name = name; this.Product = product; this.Price = price; }} class GFG { // Main method static public void Main() { Customer a = new Customer("Sumit", "Mobile Phone", 2398); Console.WriteLine("Customer name: " + a.Name); Console.WriteLine("Product: " + a.Product); Console.WriteLine("Price: " + a.Price); }} Output: Customer name: Sumit Product: Mobile Phone Price: 2398 CSharp-keyword C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n28 Nov, 2019" }, { "code": null, "e": 131, "s": 54, "text": "In C#, a readonly keyword is a modifier which is used in the following ways:" }, { "code": null, "e": 996, "s": 131, "text": "1. Readonly Fields: In C#, you are allowed to declare a field using readonly modifier. It indicates that the assignment to the fields is only the part of the declaration or in a constructor to the same class. Such types of fields can only be assigned or reassigned multiple times only at the declaration or in a constructor. They are not assigned after the constructor exit. If the readonly modifier is used with a value type field, then the field is immutable. And if the readonly modifier is used with a reference type field, then the readonly modifier prevents the field from replaced by the different instances of the reference type, here the readonly modifier does not stop the instance data of the field from being modified through the read-only field. In static and instance constructors, you are allowed to pass a readonly field as an out or ref parameter." }, { "code": null, "e": 1005, "s": 996, "text": "Example:" }, { "code": "// C# program to illustrate// how to create a readonly fieldusing System; class GFG { // readonly variables public readonly string str1; public readonly string str2; // Readonly variable // This variable is // initialized at declaration time public readonly string str3 = \"gfg\"; // The values of the readonly // variables are assigned // Using constructor public GFG(string a, string b) { str1 = a; str2 = b; Console.WriteLine(\"Display value of string 1 {0}, \" + \"and string 2 {1}\", str1, str2); } // Main method static public void Main() { GFG ob = new GFG(\"GeeksforGeeks\", \"GFG\"); }}", "e": 1706, "s": 1005, "text": null }, { "code": null, "e": 1714, "s": 1706, "text": "Output:" }, { "code": null, "e": 1772, "s": 1714, "text": "Display value of string 1 GeeksforGeeks, and string 2 GFG" }, { "code": null, "e": 1841, "s": 1772, "text": "Here, the value of the str1 and str2 is assigned in the constructor." }, { "code": null, "e": 2117, "s": 1841, "text": "2. Readonly Structure: In the readonly structure, readonly modifier indicates that the given structure is immutable. When you create a readonly structure, it is necessary to use a readonly modifier with its fields, if you do not do this, then the compiler will give an error." }, { "code": null, "e": 2126, "s": 2117, "text": "Example:" }, { "code": "// C# program to illustrate how // to create a readonly structureusing System; // Readonly structurepublic readonly struct Author{ public readonly string Name { get; } public readonly int Article { get; } public readonly string Branch { get; } public Author(string name, int article, string branch) { this.Name = name; this.Article = article; this.Branch = branch; }} class GFG { // Main method static public void Main() { Author a = new Author(\"Rohit\", 67, \"CSE\"); Console.WriteLine(\"Author name: \" + a.Name); Console.WriteLine(\"Total articles: \" + a.Article); Console.WriteLine(\"Branch name: \" + a.Branch); }}", "e": 2825, "s": 2126, "text": null }, { "code": null, "e": 2833, "s": 2825, "text": "Output:" }, { "code": null, "e": 2889, "s": 2833, "text": "Author name: Rohit\nTotal articles: 67\nBranch name: CSE\n" }, { "code": null, "e": 3172, "s": 2889, "text": "3. Readonly Members: This feature is introduced in C# 8.0. In this feature, you are allowed to use a readonly modifier to any member of the structure. This readonly modifier specifies that the member is not allowed to modify. It is better than applying the whole structure readonly." }, { "code": null, "e": 3181, "s": 3172, "text": "Example:" }, { "code": "// C# program to illustrate how // to create a readonly memberusing System; public struct Customer{ public string Name { get; } public int Price { get; } // Readonly member public readonly string Product { get; } public Customer(string name, string product, int price) { this.Name = name; this.Product = product; this.Price = price; }} class GFG { // Main method static public void Main() { Customer a = new Customer(\"Sumit\", \"Mobile Phone\", 2398); Console.WriteLine(\"Customer name: \" + a.Name); Console.WriteLine(\"Product: \" + a.Product); Console.WriteLine(\"Price: \" + a.Price); }}", "e": 3858, "s": 3181, "text": null }, { "code": null, "e": 3866, "s": 3858, "text": "Output:" }, { "code": null, "e": 3922, "s": 3866, "text": "Customer name: Sumit\nProduct: Mobile Phone\nPrice: 2398\n" }, { "code": null, "e": 3937, "s": 3922, "text": "CSharp-keyword" }, { "code": null, "e": 3940, "s": 3937, "text": "C#" } ]
How to configure XAMPP to send mail from localhost using PHP ?
15 Jul, 2019 To configure XAMPP server to send mail from localhost we have to make changes to two files sendmail.ini and php.ini. Open the xampp folder. By the name of “sendmail.ini” is present in sendmail file and “php.ini” is present in php file in the xampp folder. Step 1: Go to C:\xampp\sendmail: open sendmail.ini file in notepad or any text editor and make the changes as follows.change smtp_server=mail.yourdomain.com to smtp_server=smtp.gmail.com change smtp_port to smtp_port=587 change smtp_ssl=auto to smtp_ssl=tlsuncomment ;error_logfile=error.log to error_logfile=error.log uncomment ;debug_logfile=debug.log to debug_logfile=debug.log write your gmail id in auth_username: auth_username=*****@gmail.com write your gmail assword in auth_password: auth_password=*****write your gmail id in force_sender: *****@gmail.com change hostname to hostname=localhost change smtp_server=mail.yourdomain.com to smtp_server=smtp.gmail.com change smtp_port to smtp_port=587 change smtp_ssl=auto to smtp_ssl=tls uncomment ;error_logfile=error.log to error_logfile=error.log uncomment ;debug_logfile=debug.log to debug_logfile=debug.log write your gmail id in auth_username: auth_username=*****@gmail.com write your gmail assword in auth_password: auth_password=***** write your gmail id in force_sender: *****@gmail.com change hostname to hostname=localhost Step:2 Go to C:\xampp\php: open php.ini file in notepad or any text editor goto [mail function] part and make the changes as follows.comment SMTP=localhost by putting semicolon infront=>;SMTP=localhost comment smtp_port=25 by putting semicolon infront=>;smtp_port=25 comment sendmail_from= by putting semicolon infront=>;sendmail_from=specify path of file in sendmail_path to sendmail_path=C:\xampp\sendmail\sendmail.exe check if extension=php_openssl.dll is enabled=>If there is semicolon in front then un-comment it by removing that semicolon After following the given steps if the mail is not sent by calling the mail function, then goto C:\xampp\sendmail open error.log to see thee error occurred. comment SMTP=localhost by putting semicolon infront=>;SMTP=localhost comment smtp_port=25 by putting semicolon infront=>;smtp_port=25 comment sendmail_from= by putting semicolon infront=>;sendmail_from=specify path of file in sendmail_path to sendmail_path=C:\xampp\sendmail\sendmail.exe check if extension=php_openssl.dll is enabled=>If there is semicolon in front then un-comment it by removing that semicolon After following the given steps if the mail is not sent by calling the mail function, then goto C:\xampp\sendmail open error.log to see thee error occurred. Note: Here the procedure is shown for gmail, but it can be extended to other mails by changing the smtp server, port number. When using gmail take care to enable the option to allow access to less secure webapp. Picked Technical Scripter 2018 PHP PHP Programs Web Technologies Web technologies Questions PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n15 Jul, 2019" }, { "code": null, "e": 308, "s": 52, "text": "To configure XAMPP server to send mail from localhost we have to make changes to two files sendmail.ini and php.ini. Open the xampp folder. By the name of “sendmail.ini” is present in sendmail file and “php.ini” is present in php file in the xampp folder." }, { "code": null, "e": 316, "s": 308, "text": "Step 1:" }, { "code": null, "e": 910, "s": 316, "text": "Go to C:\\xampp\\sendmail: open sendmail.ini file in notepad or any text editor and make the changes as follows.change smtp_server=mail.yourdomain.com to smtp_server=smtp.gmail.com\nchange smtp_port to smtp_port=587\nchange smtp_ssl=auto to smtp_ssl=tlsuncomment ;error_logfile=error.log to error_logfile=error.log\nuncomment ;debug_logfile=debug.log to debug_logfile=debug.log\nwrite your gmail id in auth_username: auth_username=*****@gmail.com\nwrite your gmail assword in auth_password: auth_password=*****write your gmail id in force_sender: *****@gmail.com\nchange hostname to hostname=localhost" }, { "code": null, "e": 1050, "s": 910, "text": "change smtp_server=mail.yourdomain.com to smtp_server=smtp.gmail.com\nchange smtp_port to smtp_port=587\nchange smtp_ssl=auto to smtp_ssl=tls" }, { "code": null, "e": 1305, "s": 1050, "text": "uncomment ;error_logfile=error.log to error_logfile=error.log\nuncomment ;debug_logfile=debug.log to debug_logfile=debug.log\nwrite your gmail id in auth_username: auth_username=*****@gmail.com\nwrite your gmail assword in auth_password: auth_password=*****" }, { "code": null, "e": 1396, "s": 1305, "text": "write your gmail id in force_sender: *****@gmail.com\nchange hostname to hostname=localhost" }, { "code": null, "e": 1403, "s": 1396, "text": "Step:2" }, { "code": null, "e": 2101, "s": 1403, "text": "Go to C:\\xampp\\php: open php.ini file in notepad or any text editor goto [mail function] part and make the changes as follows.comment SMTP=localhost by putting semicolon infront=>;SMTP=localhost\ncomment smtp_port=25 by putting semicolon infront=>;smtp_port=25\ncomment sendmail_from= by putting semicolon infront=>;sendmail_from=specify path of\n file in sendmail_path to sendmail_path=C:\\xampp\\sendmail\\sendmail.exe\n\ncheck if extension=php_openssl.dll is enabled=>If there is semicolon in front then\n un-comment it by removing that semicolon\nAfter following the given steps if the mail is not sent by calling the mail function, then goto C:\\xampp\\sendmail open error.log to see thee error occurred." }, { "code": null, "e": 2517, "s": 2101, "text": "comment SMTP=localhost by putting semicolon infront=>;SMTP=localhost\ncomment smtp_port=25 by putting semicolon infront=>;smtp_port=25\ncomment sendmail_from= by putting semicolon infront=>;sendmail_from=specify path of\n file in sendmail_path to sendmail_path=C:\\xampp\\sendmail\\sendmail.exe\n\ncheck if extension=php_openssl.dll is enabled=>If there is semicolon in front then\n un-comment it by removing that semicolon\n" }, { "code": null, "e": 2674, "s": 2517, "text": "After following the given steps if the mail is not sent by calling the mail function, then goto C:\\xampp\\sendmail open error.log to see thee error occurred." }, { "code": null, "e": 2886, "s": 2674, "text": "Note: Here the procedure is shown for gmail, but it can be extended to other mails by changing the smtp server, port number. When using gmail take care to enable the option to allow access to less secure webapp." }, { "code": null, "e": 2893, "s": 2886, "text": "Picked" }, { "code": null, "e": 2917, "s": 2893, "text": "Technical Scripter 2018" }, { "code": null, "e": 2921, "s": 2917, "text": "PHP" }, { "code": null, "e": 2934, "s": 2921, "text": "PHP Programs" }, { "code": null, "e": 2951, "s": 2934, "text": "Web Technologies" }, { "code": null, "e": 2978, "s": 2951, "text": "Web technologies Questions" }, { "code": null, "e": 2982, "s": 2978, "text": "PHP" } ]
Scope Resolution Operator vs this pointer in C++
28 Nov, 2021 Scope resolution operator is for accessing static or class members and this pointer is for accessing object members when there is a local variable with the same name. Consider below C++ program: CPP // C++ program to show that local parameters hide// class members#include <iostream>using namespace std; class Test { int a; public: Test() { a = 1; } // Local parameter 'a' hides class member 'a' void func(int a) { cout << a; }}; // Driver Codeint main(){ Test obj; int k = 3; obj.func(k); return 0;} 3 Explanation: The output for the above program is 3 since the “a” passed as an argument to the func shadows the “a” of the class .i.e 1 Then how to output the class’s ‘a’. This is where this pointer comes in handy. A statement like cout <<this->a instead of cout << a can simply output the value 1 as this pointer points to the object from where func is called. CPP // C++ program to show use of this to access member when// there is a local variable with same name#include <iostream>using namespace std;class Test { int a; public: Test() { a = 1; } // Local parameter 'a' hides object's member // 'a', but we can access it using this. void func(int a) { cout << this->a; }}; // Driver codeint main(){ Test obj; int k = 3; obj.func(k); return 0;} 1 How about Scope Resolution Operator? We cannot use the scope resolution operator in the above example to print the object’s member ‘a’ because the scope resolution operator can only be used for a static data member (or class members). If we use the scope resolution operator in the above program we get compiler error and if we use this pointer in the below program, then also we get a compiler error. CPP // C++ program to show that scope resolution operator can be// used to access static members when there is a local// variable with same name#include <iostream>using namespace std; class Test { static int a; public: // Local parameter 'a' hides class member // 'a', but we can access it using :: void func(int a) { cout << Test::a; }}; // In C++, static members must be explicitly defined// like thisint Test::a = 1; // Driver codeint main(){ Test obj; int k = 3; obj.func(k); return 0;} 1 This article is contributed by Aakash Sachdeva. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Prateek Tamrakar siva117 23620uday2021 anshikajain26 cpp-operator cpp-pointer C Language C++ cpp-operator CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Nov, 2021" }, { "code": null, "e": 219, "s": 52, "text": "Scope resolution operator is for accessing static or class members and this pointer is for accessing object members when there is a local variable with the same name." }, { "code": null, "e": 249, "s": 219, "text": "Consider below C++ program: " }, { "code": null, "e": 253, "s": 249, "text": "CPP" }, { "code": "// C++ program to show that local parameters hide// class members#include <iostream>using namespace std; class Test { int a; public: Test() { a = 1; } // Local parameter 'a' hides class member 'a' void func(int a) { cout << a; }}; // Driver Codeint main(){ Test obj; int k = 3; obj.func(k); return 0;}", "e": 584, "s": 253, "text": null }, { "code": null, "e": 586, "s": 584, "text": "3" }, { "code": null, "e": 722, "s": 586, "text": "Explanation: The output for the above program is 3 since the “a” passed as an argument to the func shadows the “a” of the class .i.e 1 " }, { "code": null, "e": 948, "s": 722, "text": "Then how to output the class’s ‘a’. This is where this pointer comes in handy. A statement like cout <<this->a instead of cout << a can simply output the value 1 as this pointer points to the object from where func is called." }, { "code": null, "e": 952, "s": 948, "text": "CPP" }, { "code": "// C++ program to show use of this to access member when// there is a local variable with same name#include <iostream>using namespace std;class Test { int a; public: Test() { a = 1; } // Local parameter 'a' hides object's member // 'a', but we can access it using this. void func(int a) { cout << this->a; }}; // Driver codeint main(){ Test obj; int k = 3; obj.func(k); return 0;}", "e": 1364, "s": 952, "text": null }, { "code": null, "e": 1366, "s": 1364, "text": "1" }, { "code": null, "e": 1404, "s": 1366, "text": "How about Scope Resolution Operator? " }, { "code": null, "e": 1769, "s": 1404, "text": "We cannot use the scope resolution operator in the above example to print the object’s member ‘a’ because the scope resolution operator can only be used for a static data member (or class members). If we use the scope resolution operator in the above program we get compiler error and if we use this pointer in the below program, then also we get a compiler error." }, { "code": null, "e": 1773, "s": 1769, "text": "CPP" }, { "code": "// C++ program to show that scope resolution operator can be// used to access static members when there is a local// variable with same name#include <iostream>using namespace std; class Test { static int a; public: // Local parameter 'a' hides class member // 'a', but we can access it using :: void func(int a) { cout << Test::a; }}; // In C++, static members must be explicitly defined// like thisint Test::a = 1; // Driver codeint main(){ Test obj; int k = 3; obj.func(k); return 0;}", "e": 2288, "s": 1773, "text": null }, { "code": null, "e": 2290, "s": 2288, "text": "1" }, { "code": null, "e": 2685, "s": 2290, "text": "This article is contributed by Aakash Sachdeva. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 2702, "s": 2685, "text": "Prateek Tamrakar" }, { "code": null, "e": 2710, "s": 2702, "text": "siva117" }, { "code": null, "e": 2724, "s": 2710, "text": "23620uday2021" }, { "code": null, "e": 2738, "s": 2724, "text": "anshikajain26" }, { "code": null, "e": 2751, "s": 2738, "text": "cpp-operator" }, { "code": null, "e": 2763, "s": 2751, "text": "cpp-pointer" }, { "code": null, "e": 2774, "s": 2763, "text": "C Language" }, { "code": null, "e": 2778, "s": 2774, "text": "C++" }, { "code": null, "e": 2791, "s": 2778, "text": "cpp-operator" }, { "code": null, "e": 2795, "s": 2791, "text": "CPP" } ]
Iterators in C++ STL
06 Jul, 2022 Prerequisite : Introduction to IteratorsIterators are used to point at the memory addresses of STL containers. They are primarily used in sequences of numbers, characters etc. They reduce the complexity and execution time of the program. Operations of iterators :- Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. 1. begin() :- This function is used to return the beginning position of the container. 2. end() :- This function is used to return the after end position of the container. // C++ code to demonstrate the working of// iterator, begin() and end()#include<iostream>#include<iterator> // for iterators#include<vector> // for vectorsusing namespace std;int main(){ vector<int> ar = { 1, 2, 3, 4, 5 }; // Declaring iterator to a vector vector<int>::iterator ptr; // Displaying vector elements using begin() and end() cout << "The vector elements are : "; for (ptr = ar.begin(); ptr < ar.end(); ptr++) cout << *ptr << " "; return 0; } Output: The vector elements are : 1 2 3 4 5 3. advance() :- This function is used to increment the iterator position till the specified number mentioned in its arguments. // C++ code to demonstrate the working of// advance()#include<iostream>#include<iterator> // for iterators#include<vector> // for vectorsusing namespace std;int main(){ vector<int> ar = { 1, 2, 3, 4, 5 }; // Declaring iterator to a vector vector<int>::iterator ptr = ar.begin(); // Using advance() to increment iterator position // points to 4 advance(ptr, 3); // Displaying iterator position cout << "The position of iterator after advancing is : "; cout << *ptr << " "; return 0; } Output: The position of iterator after advancing is : 4 4. next() :- This function returns the new iterator that the iterator would point after advancing the positions mentioned in its arguments. 5. prev() :- This function returns the new iterator that the iterator would point after decrementing the positions mentioned in its arguments. // C++ code to demonstrate the working of// next() and prev() #include<iostream>#include<iterator> // for iterators#include<vector> // for vectorsusing namespace std;int main(){ vector<int> ar = { 1, 2, 3, 4, 5 }; // Declaring iterators to a vector vector<int>::iterator ptr = ar.begin(); vector<int>::iterator ftr = ar.end(); // Using next() to return new iterator // points to 4 auto it = next(ptr, 3); // Using prev() to return new iterator // points to 3 auto it1 = prev(ftr, 3); // Displaying iterator position cout << "The position of new iterator using next() is : "; cout << *it << " "; cout << endl; // Displaying iterator position cout << "The position of new iterator using prev() is : "; cout << *it1 << " "; cout << endl; return 0; } Output: The position of new iterator using next() is : 4 The position of new iterator using prev() is : 3 6. inserter() :- This function is used to insert the elements at any position in the container. It accepts 2 arguments, the container and iterator to position where the elements have to be inserted. // C++ code to demonstrate the working of// inserter()#include<iostream>#include<iterator> // for iterators#include<vector> // for vectorsusing namespace std;int main(){ vector<int> ar = { 1, 2, 3, 4, 5 }; vector<int> ar1 = {10, 20, 30}; // Declaring iterator to a vector vector<int>::iterator ptr = ar.begin(); // Using advance to set position advance(ptr, 3); // copying 1 vector elements in other using inserter() // inserts ar1 after 3rd position in ar copy(ar1.begin(), ar1.end(), inserter(ar,ptr)); // Displaying new vector elements cout << "The new vector after inserting elements is : "; for (int &x : ar) cout << x << " "; return 0; } Output: The new vector after inserting elements is : 1 2 3 10 20 30 4 5 Types of Iterators : Input IteratorsOutput IteratorsForward IteratorBidirectional IteratorsRandom-Access Iterators Input Iterators Output Iterators Forward Iterator Bidirectional Iterators Random-Access Iterators C++ Programming Language Tutorial | Iterators in C++ STL | GeeksforGeeks - YouTubeGeeksforGeeks532K subscribersC++ Programming Language Tutorial | Iterators in C++ STL | GeeksforGeeksWatch laterShareCopy link20/45InfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:58•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=krzOq7dFWUU" 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 Manjeet Singh .If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. IkamaruEnauki cpp-iterator CPP-Library 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 Jul, 2022" }, { "code": null, "e": 290, "s": 52, "text": "Prerequisite : Introduction to IteratorsIterators are used to point at the memory addresses of STL containers. They are primarily used in sequences of numbers, characters etc. They reduce the complexity and execution time of the program." }, { "code": null, "e": 317, "s": 290, "text": "Operations of iterators :-" }, { "code": null, "e": 326, "s": 317, "text": "Chapters" }, { "code": null, "e": 353, "s": 326, "text": "descriptions off, selected" }, { "code": null, "e": 403, "s": 353, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 426, "s": 403, "text": "captions off, selected" }, { "code": null, "e": 434, "s": 426, "text": "English" }, { "code": null, "e": 458, "s": 434, "text": "This is a modal window." }, { "code": null, "e": 527, "s": 458, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 549, "s": 527, "text": "End of dialog window." }, { "code": null, "e": 636, "s": 549, "text": "1. begin() :- This function is used to return the beginning position of the container." }, { "code": null, "e": 721, "s": 636, "text": "2. end() :- This function is used to return the after end position of the container." }, { "code": "// C++ code to demonstrate the working of// iterator, begin() and end()#include<iostream>#include<iterator> // for iterators#include<vector> // for vectorsusing namespace std;int main(){ vector<int> ar = { 1, 2, 3, 4, 5 }; // Declaring iterator to a vector vector<int>::iterator ptr; // Displaying vector elements using begin() and end() cout << \"The vector elements are : \"; for (ptr = ar.begin(); ptr < ar.end(); ptr++) cout << *ptr << \" \"; return 0; }", "e": 1225, "s": 721, "text": null }, { "code": null, "e": 1233, "s": 1225, "text": "Output:" }, { "code": null, "e": 1271, "s": 1233, "text": "The vector elements are : 1 2 3 4 5 \n" }, { "code": null, "e": 1398, "s": 1271, "text": "3. advance() :- This function is used to increment the iterator position till the specified number mentioned in its arguments." }, { "code": "// C++ code to demonstrate the working of// advance()#include<iostream>#include<iterator> // for iterators#include<vector> // for vectorsusing namespace std;int main(){ vector<int> ar = { 1, 2, 3, 4, 5 }; // Declaring iterator to a vector vector<int>::iterator ptr = ar.begin(); // Using advance() to increment iterator position // points to 4 advance(ptr, 3); // Displaying iterator position cout << \"The position of iterator after advancing is : \"; cout << *ptr << \" \"; return 0; }", "e": 1941, "s": 1398, "text": null }, { "code": null, "e": 1949, "s": 1941, "text": "Output:" }, { "code": null, "e": 1999, "s": 1949, "text": "The position of iterator after advancing is : 4 \n" }, { "code": null, "e": 2139, "s": 1999, "text": "4. next() :- This function returns the new iterator that the iterator would point after advancing the positions mentioned in its arguments." }, { "code": null, "e": 2282, "s": 2139, "text": "5. prev() :- This function returns the new iterator that the iterator would point after decrementing the positions mentioned in its arguments." }, { "code": "// C++ code to demonstrate the working of// next() and prev() #include<iostream>#include<iterator> // for iterators#include<vector> // for vectorsusing namespace std;int main(){ vector<int> ar = { 1, 2, 3, 4, 5 }; // Declaring iterators to a vector vector<int>::iterator ptr = ar.begin(); vector<int>::iterator ftr = ar.end(); // Using next() to return new iterator // points to 4 auto it = next(ptr, 3); // Using prev() to return new iterator // points to 3 auto it1 = prev(ftr, 3); // Displaying iterator position cout << \"The position of new iterator using next() is : \"; cout << *it << \" \"; cout << endl; // Displaying iterator position cout << \"The position of new iterator using prev() is : \"; cout << *it1 << \" \"; cout << endl; return 0; }", "e": 3127, "s": 2282, "text": null }, { "code": null, "e": 3135, "s": 3127, "text": "Output:" }, { "code": null, "e": 3237, "s": 3135, "text": "The position of new iterator using next() is : 4 \nThe position of new iterator using prev() is : 3 \n" }, { "code": null, "e": 3436, "s": 3237, "text": "6. inserter() :- This function is used to insert the elements at any position in the container. It accepts 2 arguments, the container and iterator to position where the elements have to be inserted." }, { "code": "// C++ code to demonstrate the working of// inserter()#include<iostream>#include<iterator> // for iterators#include<vector> // for vectorsusing namespace std;int main(){ vector<int> ar = { 1, 2, 3, 4, 5 }; vector<int> ar1 = {10, 20, 30}; // Declaring iterator to a vector vector<int>::iterator ptr = ar.begin(); // Using advance to set position advance(ptr, 3); // copying 1 vector elements in other using inserter() // inserts ar1 after 3rd position in ar copy(ar1.begin(), ar1.end(), inserter(ar,ptr)); // Displaying new vector elements cout << \"The new vector after inserting elements is : \"; for (int &x : ar) cout << x << \" \"; return 0; }", "e": 4160, "s": 3436, "text": null }, { "code": null, "e": 4168, "s": 4160, "text": "Output:" }, { "code": null, "e": 4234, "s": 4168, "text": "The new vector after inserting elements is : 1 2 3 10 20 30 4 5 \n" }, { "code": null, "e": 4255, "s": 4234, "text": "Types of Iterators :" }, { "code": null, "e": 4349, "s": 4255, "text": "Input IteratorsOutput IteratorsForward IteratorBidirectional IteratorsRandom-Access Iterators" }, { "code": null, "e": 4365, "s": 4349, "text": "Input Iterators" }, { "code": null, "e": 4382, "s": 4365, "text": "Output Iterators" }, { "code": null, "e": 4399, "s": 4382, "text": "Forward Iterator" }, { "code": null, "e": 4423, "s": 4399, "text": "Bidirectional Iterators" }, { "code": null, "e": 4447, "s": 4423, "text": "Random-Access Iterators" }, { "code": null, "e": 5382, "s": 4447, "text": "C++ Programming Language Tutorial | Iterators in C++ STL | GeeksforGeeks - YouTubeGeeksforGeeks532K subscribersC++ Programming Language Tutorial | Iterators in C++ STL | GeeksforGeeksWatch laterShareCopy link20/45InfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:58•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=krzOq7dFWUU\" 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": 5679, "s": 5382, "text": "This article is contributed by Manjeet Singh .If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 5804, "s": 5679, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 5818, "s": 5804, "text": "IkamaruEnauki" }, { "code": null, "e": 5831, "s": 5818, "text": "cpp-iterator" }, { "code": null, "e": 5843, "s": 5831, "text": "CPP-Library" }, { "code": null, "e": 5847, "s": 5843, "text": "STL" }, { "code": null, "e": 5851, "s": 5847, "text": "C++" }, { "code": null, "e": 5855, "s": 5851, "text": "STL" }, { "code": null, "e": 5859, "s": 5855, "text": "CPP" } ]
How to convert the character values in an R data frame column to lower case?
The character values can be stored in uppercase, lowercase, or a mixture of the two. If we have values that are either in uppercase or the mixture of lower and upper then we can convert those character values to only lowercase by using tolower function. We simply need to pass the vector or column of the data frame inside the tolower function as shown in the below examples. Consider the below data frame − Live Demo > x1<-sample(LETTERS[1:4],20,replace=TRUE) > y1<-rnorm(20) > df1<-data.frame(x1,y1) > df1 x1 y1 1 C -0.1036851 2 C -0.6176530 3 B 0.5763786 4 A 0.1943794 5 C 1.1196470 6 D -1.4202033 7 A -1.9147143 8 D -1.6492836 9 B 0.2806705 10 D -1.0246326 11 B -0.1584948 12 A 0.8301300 13 C -1.1100439 14 C 0.4864598 15 C 1.3461719 16 D -2.3021691 17 D -0.8527835 18 A -0.0160726 19 A -1.3944416 20 D 1.5769472 Changing the character values in x1 to lowercase − > df1$x1<-tolower(df1$x1) > df1 x1 y1 1 c -0.1036851 2 c -0.6176530 3 b 0.5763786 4 a 0.1943794 5 c 1.1196470 6 d -1.4202033 7 a -1.9147143 8 d -1.6492836 9 b 0.2806705 10 d -1.0246326 11 b -0.1584948 12 a 0.8301300 13 c -1.1100439 14 c 0.4864598 15 c 1.3461719 16 d -2.3021691 17 d -0.8527835 18 a -0.0160726 19 a -1.3944416 20 d 1.5769472 Live Demo > x2<-sample(LETTERS[1:10],20,replace=TRUE) > y2<-rpois(20,5) > df2<-data.frame(x2,y2) > df2 x2 y2 1 G 4 2 D 3 3 G 2 4 E 3 5 B 6 6 I 2 7 A 8 8 F 6 9 A 7 10 F 5 11 C 10 12 G 5 13 I 4 14 H 7 15 F 4 16 A 3 17 J 3 18 I 3 19 D 6 20 F 8 Changing the character values in x2 to lowercase − > df2$x2<-tolower(df2$x2) > df2 x2 y2 1 g 4 2 d 3 3 g 2 4 e 3 5 b 6 6 i 2 7 a 8 8 f 6 9 a 7 10 f 5 11 c 10 12 g 5 13 i 4 14 h 7 15 f 4 16 a 3 17 j 3 18 i 3 19 d 6 20 f 8 Live Demo > x3<-sample(LETTERS[1:2],20,replace=TRUE) > y3<-runif(20,2,5) > df3<-data.frame(x3,y3) > df3 x3 y3 1 A 2.144779 2 A 4.020497 3 A 4.152795 4 A 4.579962 5 A 4.151587 6 B 3.668675 7 B 3.918459 8 B 2.326660 9 B 4.826448 10 A 4.159623 11 B 4.966475 12 B 4.159850 13 B 4.478584 14 A 2.585765 15 B 3.661653 16 B 2.836051 17 B 3.947854 18 B 3.650995 19 A 3.333785 20 A 2.147321 Changing the character values in x3 to lowercase − > df3$x3<-tolower(df3$x3) > df3 x3 y3 1 a 2.144779 2 a 4.020497 3 a 4.152795 4 a 4.579962 5 a 4.151587 6 b 3.668675 7 b 3.918459 8 b 2.326660 9 b 4.826448 10 a 4.159623 11 b 4.966475 12 b 4.159850 13 b 4.478584 14 a 2.585765 15 b 3.661653 16 b 2.836051 17 b 3.947854 18 b 3.650995 19 a 3.333785 20 a 2.147321
[ { "code": null, "e": 1438, "s": 1062, "text": "The character values can be stored in uppercase, lowercase, or a mixture of the two. If we have values that are either in uppercase or the mixture of lower and upper then we can convert those character values to only lowercase by using tolower function. We simply need to pass the vector or column of the data frame inside the tolower function as shown in the below examples." }, { "code": null, "e": 1470, "s": 1438, "text": "Consider the below data frame −" }, { "code": null, "e": 1480, "s": 1470, "text": "Live Demo" }, { "code": null, "e": 1570, "s": 1480, "text": "> x1<-sample(LETTERS[1:4],20,replace=TRUE)\n> y1<-rnorm(20)\n> df1<-data.frame(x1,y1)\n> df1" }, { "code": null, "e": 1923, "s": 1570, "text": " x1 y1\n1 C -0.1036851\n2 C -0.6176530\n3 B 0.5763786\n4 A 0.1943794\n5 C 1.1196470\n6 D -1.4202033\n7 A -1.9147143\n8 D -1.6492836\n9 B 0.2806705\n10 D -1.0246326\n11 B -0.1584948\n12 A 0.8301300\n13 C -1.1100439\n14 C 0.4864598\n15 C 1.3461719\n16 D -2.3021691\n17 D -0.8527835\n18 A -0.0160726\n19 A -1.3944416\n20 D 1.5769472" }, { "code": null, "e": 1974, "s": 1923, "text": "Changing the character values in x1 to lowercase −" }, { "code": null, "e": 2006, "s": 1974, "text": "> df1$x1<-tolower(df1$x1)\n> df1" }, { "code": null, "e": 2358, "s": 2006, "text": " x1 y1\n1 c -0.1036851\n2 c -0.6176530\n3 b 0.5763786\n4 a 0.1943794\n5 c 1.1196470\n6 d -1.4202033\n7 a -1.9147143\n8 d -1.6492836\n9 b 0.2806705\n10 d -1.0246326\n11 b -0.1584948\n12 a 0.8301300\n13 c -1.1100439\n14 c 0.4864598\n15 c 1.3461719\n16 d -2.3021691\n17 d -0.8527835\n18 a -0.0160726\n19 a -1.3944416\n20 d 1.5769472" }, { "code": null, "e": 2368, "s": 2358, "text": "Live Demo" }, { "code": null, "e": 2461, "s": 2368, "text": "> x2<-sample(LETTERS[1:10],20,replace=TRUE)\n> y2<-rpois(20,5)\n> df2<-data.frame(x2,y2)\n> df2" }, { "code": null, "e": 2631, "s": 2461, "text": " x2 y2\n1 G 4\n2 D 3\n3 G 2\n4 E 3\n5 B 6\n6 I 2\n7 A 8\n8 F 6\n9 A 7\n10 F 5\n11 C 10\n12 G 5\n13 I 4\n14 H 7\n15 F 4\n16 A 3\n17 J 3\n18 I 3\n19 D 6\n20 F 8" }, { "code": null, "e": 2682, "s": 2631, "text": "Changing the character values in x2 to lowercase −" }, { "code": null, "e": 2714, "s": 2682, "text": "> df2$x2<-tolower(df2$x2)\n> df2" }, { "code": null, "e": 2884, "s": 2714, "text": " x2 y2\n1 g 4\n2 d 3\n3 g 2\n4 e 3\n5 b 6\n6 i 2\n7 a 8\n8 f 6\n9 a 7\n10 f 5\n11 c 10\n12 g 5\n13 i 4\n14 h 7\n15 f 4\n16 a 3\n17 j 3\n18 i 3\n19 d 6\n20 f 8" }, { "code": null, "e": 2894, "s": 2884, "text": "Live Demo" }, { "code": null, "e": 2988, "s": 2894, "text": "> x3<-sample(LETTERS[1:2],20,replace=TRUE)\n> y3<-runif(20,2,5)\n> df3<-data.frame(x3,y3)\n> df3" }, { "code": null, "e": 3299, "s": 2988, "text": " x3 y3\n1 A 2.144779\n2 A 4.020497\n3 A 4.152795\n4 A 4.579962\n5 A 4.151587\n6 B 3.668675\n7 B 3.918459\n8 B 2.326660\n9 B 4.826448\n10 A 4.159623\n11 B 4.966475\n12 B 4.159850\n13 B 4.478584\n14 A 2.585765\n15 B 3.661653\n16 B 2.836051\n17 B 3.947854\n18 B 3.650995\n19 A 3.333785\n20 A 2.147321" }, { "code": null, "e": 3350, "s": 3299, "text": "Changing the character values in x3 to lowercase −" }, { "code": null, "e": 3382, "s": 3350, "text": "> df3$x3<-tolower(df3$x3)\n> df3" }, { "code": null, "e": 3692, "s": 3382, "text": " x3 y3\n1 a 2.144779\n2 a 4.020497\n3 a 4.152795\n4 a 4.579962\n5 a 4.151587\n6 b 3.668675\n7 b 3.918459\n8 b 2.326660\n9 b 4.826448\n10 a 4.159623\n11 b 4.966475\n12 b 4.159850\n13 b 4.478584\n14 a 2.585765\n15 b 3.661653\n16 b 2.836051\n17 b 3.947854\n18 b 3.650995\n19 a 3.333785\n20 a 2.147321" } ]
HTML - div Tag
The HTML <div> tag is used for defining a section of your document. With the div tag, you can group large sections of HTML elements together and format them with CSS. The difference between the div tag and the span tag is that the div tag is used with blocklevel elements whilst the span tag is used with inline elements. <!DOCTYPE html> <html> <head> <title>HTML div Tag</title> <link rel = "stylesheet" href = "style2.css"> </head> <body> <div id = "contentinfo"> <p>Welcome to our website. We provide tutorials on various subjects.</p> </div> </body> </html> Here is the csss file style2.css #contentinfo p { line-height: 20px; margin: 30px; padding-bottom: 20px; text-align: justify; width: 140px; color: red; } This will produce the following result − Welcome to our website. We provide tutorials on various subjects. This tag supports all the global attributes described in HTML Attribute Reference The HTML <div> tag also supports the following additional attributes − This tag supports all the event attributes described in HTML Events Reference 19 Lectures 2 hours Anadi Sharma 16 Lectures 1.5 hours Anadi Sharma 18 Lectures 1.5 hours Frahaan Hussain 57 Lectures 5.5 hours DigiFisk (Programming Is Fun) 54 Lectures 6 hours DigiFisk (Programming Is Fun) 45 Lectures 5.5 hours DigiFisk (Programming Is Fun) Print Add Notes Bookmark this page
[ { "code": null, "e": 2541, "s": 2374, "text": "The HTML <div> tag is used for defining a section of your document. With the div tag, you can group large sections of HTML elements together and format them with CSS." }, { "code": null, "e": 2696, "s": 2541, "text": "The difference between the div tag and the span tag is that the div tag is used with blocklevel elements whilst the span tag is used with inline elements." }, { "code": null, "e": 2984, "s": 2696, "text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML div Tag</title>\n <link rel = \"stylesheet\" href = \"style2.css\">\n </head>\n\n <body>\n <div id = \"contentinfo\">\n <p>Welcome to our website. We provide tutorials on various subjects.</p>\n </div>\n </body>\n\n</html>" }, { "code": null, "e": 3017, "s": 2984, "text": "Here is the csss file style2.css" }, { "code": null, "e": 3159, "s": 3017, "text": "#contentinfo p { \n line-height: 20px;\n margin: 30px;\n padding-bottom: 20px; \n text-align: justify;\n width: 140px;\n color: red; \n}" }, { "code": null, "e": 3200, "s": 3159, "text": "This will produce the following result −" }, { "code": null, "e": 3266, "s": 3200, "text": "Welcome to our website. We provide tutorials on various subjects." }, { "code": null, "e": 3348, "s": 3266, "text": "This tag supports all the global attributes described in HTML Attribute Reference" }, { "code": null, "e": 3420, "s": 3348, "text": "The HTML <div> tag also supports the following additional attributes −" }, { "code": null, "e": 3498, "s": 3420, "text": "This tag supports all the event attributes described in HTML Events Reference" }, { "code": null, "e": 3531, "s": 3498, "text": "\n 19 Lectures \n 2 hours \n" }, { "code": null, "e": 3545, "s": 3531, "text": " Anadi Sharma" }, { "code": null, "e": 3580, "s": 3545, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3594, "s": 3580, "text": " Anadi Sharma" }, { "code": null, "e": 3629, "s": 3594, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3646, "s": 3629, "text": " Frahaan Hussain" }, { "code": null, "e": 3681, "s": 3646, "text": "\n 57 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3712, "s": 3681, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3745, "s": 3712, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 3776, "s": 3745, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3811, "s": 3776, "text": "\n 45 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3842, "s": 3811, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3849, "s": 3842, "text": " Print" }, { "code": null, "e": 3860, "s": 3849, "text": " Add Notes" } ]
Python os.close() Method
Python method close() closes the associated with file descriptor fd. Following is the syntax for close() method − os.close(fd); fd − This is the file descriptor of the file. fd − This is the file descriptor of the file. This method does not return any value. The following example shows the usage of close() method. #!/usr/bin/python import os, sys # Open a file fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT ) # Write one string os.write(fd, "This is test") # Close opened file os.close( fd ) print "Closed the file successfully!!" When we run above program, it produces following result − Closed the file successfully!! 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2313, "s": 2244, "text": "Python method close() closes the associated with file descriptor fd." }, { "code": null, "e": 2358, "s": 2313, "text": "Following is the syntax for close() method −" }, { "code": null, "e": 2373, "s": 2358, "text": "os.close(fd);\n" }, { "code": null, "e": 2419, "s": 2373, "text": "fd − This is the file descriptor of the file." }, { "code": null, "e": 2465, "s": 2419, "text": "fd − This is the file descriptor of the file." }, { "code": null, "e": 2504, "s": 2465, "text": "This method does not return any value." }, { "code": null, "e": 2561, "s": 2504, "text": "The following example shows the usage of close() method." }, { "code": null, "e": 2783, "s": 2561, "text": "#!/usr/bin/python\n\nimport os, sys\n\n# Open a file\nfd = os.open( \"foo.txt\", os.O_RDWR|os.O_CREAT )\n\n# Write one string\nos.write(fd, \"This is test\")\n\n# Close opened file\nos.close( fd )\n\nprint \"Closed the file successfully!!\"" }, { "code": null, "e": 2841, "s": 2783, "text": "When we run above program, it produces following result −" }, { "code": null, "e": 2873, "s": 2841, "text": "Closed the file successfully!!\n" }, { "code": null, "e": 2910, "s": 2873, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 2926, "s": 2910, "text": " Malhar Lathkar" }, { "code": null, "e": 2959, "s": 2926, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 2978, "s": 2959, "text": " Arnab Chakraborty" }, { "code": null, "e": 3013, "s": 2978, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3035, "s": 3013, "text": " In28Minutes Official" }, { "code": null, "e": 3069, "s": 3035, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3097, "s": 3069, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3132, "s": 3097, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3146, "s": 3132, "text": " Lets Kode It" }, { "code": null, "e": 3179, "s": 3146, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3196, "s": 3179, "text": " Abhilash Nelson" }, { "code": null, "e": 3203, "s": 3196, "text": " Print" }, { "code": null, "e": 3214, "s": 3203, "text": " Add Notes" } ]
AKS Primality Test - GeeksforGeeks
22 Apr, 2021 There are several primality test available to check whether the number is prime or not like Fermat’s Theorem, Miller-Rabin Primality test and alot more. But problem with all of them is that they all are probabilistic in nature. So, here comes one another method i.e AKS primality test (Agrawal–Kayal–Saxena primality test) and it is deterministically correct for any general number.Features of AKS primality test : 1. The AKS algorithm can be used to verify the primality of any general number given. 2. The maximum running time of the algorithm can be expressed as a polynomial over the number of digits in the target number. 3. The algorithm is guaranteed to distinguish deterministically whether the target number is prime or composite. 4. The correctness of AKS is not conditional on any subsidiary unproven hypothesis.The AKS primality test is based upon the following theorem: An integer n greater than 2 is prime if and only if the polynomial congruence relation holds for some a coprime to n. Here x is just a formal symbol .The AKS test evaluates the equality by making complexity dependent on the size of r . This is expressed as which can be expressed in simpler term as for some polynomials f and g . This congruence can be checked in polynomial time when r is polynomial to the digits of n. The AKS algorithm evaluates this congruence for a large set of a values, whose size is polynomial to the digits of n. The proof of validity of the AKS algorithm shows that one can find r and a set of a values with the above properties such that if the congruences hold then n is a power of a prime. The brute force approach would require the expansion of the (x – a)^n polynomial and a reduction (mod n) of the resulting n + 1 coefficients .As a should be co-prime to n. So, to implement this algorithm we can check by taking a = 1, but for large values of n we should take large values of a. The algorithm is based on the condition that if n is any number, then it is prime if, ( x – 1 )^n – ( x^n – 1) is divisible by n.Checking for n = 3 :(x-1)^3 – (x^3 – 1) = (x^3 – 3x^2 + 3x – 1) – (x^3 – 1) = -3x^2 + 3xAs all the coefficients are divisible by n i.e. 3, so 3 (n) is prime. As the number increases, size increases. The code here is based on this condition and can check primes till 64 .Below is the implementation of above approach: C++ Java Python3 C# PHP Javascript // C++ code to check if number is prime. This// program demonstrates concept behind AKS// algorithm and doesn't implement the actual// algorithm (This works only till n = 64)#include <bits/stdc++.h>using namespace std; // array used to store coefficients .long long c[100]; // function to calculate the coefficients// of (x - 1)^n - (x^n - 1) with the help// of Pascal's triangle .void coef(int n){ c[0] = 1; for (int i = 0; i < n; c[0] = -c[0], i++) { c[1 + i] = 1; for (int j = i; j > 0; j--) c[j] = c[j - 1] - c[j]; }} // function to check whether// the number is prime or notbool isPrime(int n){ // Calculating all the coefficients by // the function coef and storing all // the coefficients in c array . coef(n); // subtracting c[n] and adding c[0] by 1 // as ( x - 1 )^n - ( x^n - 1), here we // are subtracting c[n] by 1 and adding // 1 in expression. c[0]++, c[n]--; // checking all the coefficients whether // they are divisible by n or not. // if n is not prime, then loop breaks // and (i > 0). int i = n; while (i-- && c[i] % n == 0) ; // Return true if all coefficients are // divisible by n. return i < 0;} // driver programint main(){ int n = 37; if (isPrime(n)) cout << "Prime" << endl; else cout << "Not Prime" << endl; return 0;} // Java code to check if number is prime. This// program demonstrates concept behind AKS// algorithm and doesn't implement the actual// algorithm (This works only till n = 64) class GFG { // array used to store coefficients . static long c[] = new long[100]; // function to calculate the coefficients // of (x - 1)^n - (x^n - 1) with the help // of Pascal's triangle . static void coef(int n) { c[0] = 1; for (int i = 0; i < n; c[0] = -c[0], i++) { c[1 + i] = 1; for (int j = i; j > 0; j--) c[j] = c[j - 1] - c[j]; } } // function to check whether // the number is prime or not static boolean isPrime(int n) { // Calculating all the coefficients by // the function coef and storing all // the coefficients in c array . coef(n); // subtracting c[n] and adding c[0] by 1 // as ( x - 1 )^n - ( x^n - 1), here we // are subtracting c[n] by 1 and adding // 1 in expression. c[0]++; c[n]--; // checking all the coefficients whether // they are divisible by n or not. // if n is not prime, then loop breaks // and (i > 0). int i = n; while ((i--) > 0 && c[i] % n == 0) ; // Return true if all coefficients are // divisible by n. return i < 0; } // Driver code public static void main(String[] args) { int n = 37; if (isPrime(n)) System.out.println("Prime"); else System.out.println("Not Prime"); }} // This code is contributed by Anant Agarwal. # Python3 code to check if# number is prime. This# program demonstrates concept# behind AKS algorithm and# doesn't implement the actual# algorithm (This works only# till n = 64) # array used to# store coefficients .c = [0] * 100; # function to calculate the# coefficients of (x - 1)^n -# (x^n - 1) with the help# of Pascal's triangle .def coef(n): c[0] = 1; for i in range(n): c[1 + i] = 1; for j in range(i, 0, -1): c[j] = c[j - 1] - c[j]; c[0] = -c[0]; # function to check whether# the number is prime or notdef isPrime(n): # Calculating all the coefficients # by the function coef and storing # all the coefficients in c array . coef(n); # subtracting c[n] and adding # c[0] by 1 as ( x - 1 )^n - # ( x^n - 1), here we are # subtracting c[n] by 1 and # adding 1 in expression. c[0] = c[0] + 1; c[n] = c[n] - 1; # checking all the coefficients # whether they are divisible by # n or not. if n is not prime, # then loop breaks and (i > 0). i = n; while (i > -1 and c[i] % n == 0): i = i - 1; # Return true if all coefficients # are divisible by n. return True if i < 0 else False; # Driver Coden = 37;if (isPrime(n)): print("Prime");else: print("Not Prime"); # This code is contributed by mits // C# code to check if number is prime. This// program demonstrates concept behind AKS// algorithm and doesn't implement the actual// algorithm (This works only till n = 64)using System; class GFG { // array used to store coefficients . static long []c = new long[100]; // function to calculate the coefficients // of (x - 1)^n - (x^n - 1) with the help // of Pascal's triangle . static void coef(int n) { c[0] = 1; for (int i = 0; i < n; c[0] = -c[0], i++) { c[1 + i] = 1; for (int j = i; j > 0; j--) c[j] = c[j - 1] - c[j]; } } // function to check whether // the number is prime or not static bool isPrime(int n) { // Calculating all the coefficients by // the function coef and storing all // the coefficients in c array . coef(n); // subtracting c[n] and adding c[0] by 1 // as ( x - 1 )^n - ( x^n - 1), here we // are subtracting c[n] by 1 and adding // 1 in expression. c[0]++; c[n]--; // checking all the coefficients whether // they are divisible by n or not. // if n is not prime, then loop breaks // and (i > 0). int i = n; while ((i--) > 0 && c[i] % n == 0) ; // Return true if all coefficients are // divisible by n. return i < 0; } // Driver code public static void Main() { int n = 37; if (isPrime(n)) Console.WriteLine("Prime"); else Console.WriteLine("Not Prime"); }} // This code is contributed by anuj_67. <?php// PHP code to check if number// is prime. This program// demonstrates concept behind// AKS algorithm and doesn't// implement the actual// algorithm (This works only// till n = 64) // array used to// store coefficients .global $c; // function to calculate// the coefficients// of (x - 1)^n -// (x^n - 1) with the help// of Pascal's triangle .function coef($n){ $c[0] = 1; for ($i = 0; $i < $n; $c[0] = -$c[0], $i++) { $c[1 + $i] = 1; for ($j = $i; $j > 0; $j--) $c[$j] = $c[$j - 1] - $c[$j]; }} // function to check whether// the number is prime or notfunction isPrime($n){ global $c; // Calculating all the // coefficients by the // function coef and // storing all the // coefficients in c array . coef($n); // subtracting c[n] and // adding c[0] by 1 as // ( x - 1 )^n - ( x^n - 1), // here we are subtracting c[n] // by 1 and adding 1 in expression. // $c[0]++; $c[$n]--; // checking all the coefficients whether // they are divisible by n or not. // if n is not prime, then loop breaks // and (i > 0). $i = $n; while ($i-- && $c[$i] % $n == 0) // Return true if all // coefficients are // divisible by n. return $i < 0;} // Driver Code $n = 37; if (isPrime($n)) echo "Not Prime", "\n"; else echo "Prime", "\n"; // This code is contributed by aj_36?> <script> // Javascript program to check if number is prime.// This program demonstrates concept behind AKS// algorithm and doesn't implement the actual// algorithm (This works only till n = 64) // array used to store coefficients . let c = []; // function to calculate the coefficients // of (x - 1)^n - (x^n - 1) with the help // of Pascal's triangle . function coef(n) { c[0] = 1; for (let i = 0; i < n; c[0] = -c[0], i++) { c[1 + i] = 1; for (let j = i; j > 0; j--) c[j] = c[j - 1] - c[j]; } } // function to check whether // the number is prime or not function isPrime(n) { // Calculating all the coefficients by // the function coef and storing all // the coefficients in c array . coef(n); // subtracting c[n] and adding c[0] by 1 // as ( x - 1 )^n - ( x^n - 1), here we // are subtracting c[n] by 1 and adding // 1 in expression. c[0]++; c[n]--; // checking all the coefficients whether // they are divisible by n or not. // if n is not prime, then loop breaks // and (i > 0). let i = n; while ((i--) > 0 && c[i] % n == 0) ; // Return true if all coefficients are // divisible by n. return i < 0; } // Driver code let n = 37; if (isPrime(n)) document.write("Prime"); else document.write("Not Prime"); </script> Output: Prime References: https://en.wikipedia.org/wiki/AKS_primality_test https://rosettacode.org/wiki/AKS_test_for_primes#C https://www.youtube.com/watch?v=HvMSRWTE2mI jit_t vt_m Mithun Kumar sanskar27jain susmitakundugoaldanga number-theory Prime Number Competitive Programming Mathematical Technical Scripter number-theory Mathematical Prime Number Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Modulo 10^9+7 (1000000007) Prefix Sum Array - Implementation and Applications in Competitive Programming Bits manipulation (Important tactics) Formatted output in Java Algorithm Library | C++ Magicians STL Algorithm Program for Fibonacci numbers C++ Data Types Write a program to print all permutations of a given string Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 24840, "s": 24812, "text": "\n22 Apr, 2021" }, { "code": null, "e": 27185, "s": 24840, "text": "There are several primality test available to check whether the number is prime or not like Fermat’s Theorem, Miller-Rabin Primality test and alot more. But problem with all of them is that they all are probabilistic in nature. So, here comes one another method i.e AKS primality test (Agrawal–Kayal–Saxena primality test) and it is deterministically correct for any general number.Features of AKS primality test : 1. The AKS algorithm can be used to verify the primality of any general number given. 2. The maximum running time of the algorithm can be expressed as a polynomial over the number of digits in the target number. 3. The algorithm is guaranteed to distinguish deterministically whether the target number is prime or composite. 4. The correctness of AKS is not conditional on any subsidiary unproven hypothesis.The AKS primality test is based upon the following theorem: An integer n greater than 2 is prime if and only if the polynomial congruence relation holds for some a coprime to n. Here x is just a formal symbol .The AKS test evaluates the equality by making complexity dependent on the size of r . This is expressed as which can be expressed in simpler term as for some polynomials f and g . This congruence can be checked in polynomial time when r is polynomial to the digits of n. The AKS algorithm evaluates this congruence for a large set of a values, whose size is polynomial to the digits of n. The proof of validity of the AKS algorithm shows that one can find r and a set of a values with the above properties such that if the congruences hold then n is a power of a prime. The brute force approach would require the expansion of the (x – a)^n polynomial and a reduction (mod n) of the resulting n + 1 coefficients .As a should be co-prime to n. So, to implement this algorithm we can check by taking a = 1, but for large values of n we should take large values of a. The algorithm is based on the condition that if n is any number, then it is prime if, ( x – 1 )^n – ( x^n – 1) is divisible by n.Checking for n = 3 :(x-1)^3 – (x^3 – 1) = (x^3 – 3x^2 + 3x – 1) – (x^3 – 1) = -3x^2 + 3xAs all the coefficients are divisible by n i.e. 3, so 3 (n) is prime. As the number increases, size increases. The code here is based on this condition and can check primes till 64 .Below is the implementation of above approach: " }, { "code": null, "e": 27189, "s": 27185, "text": "C++" }, { "code": null, "e": 27194, "s": 27189, "text": "Java" }, { "code": null, "e": 27202, "s": 27194, "text": "Python3" }, { "code": null, "e": 27205, "s": 27202, "text": "C#" }, { "code": null, "e": 27209, "s": 27205, "text": "PHP" }, { "code": null, "e": 27220, "s": 27209, "text": "Javascript" }, { "code": "// C++ code to check if number is prime. This// program demonstrates concept behind AKS// algorithm and doesn't implement the actual// algorithm (This works only till n = 64)#include <bits/stdc++.h>using namespace std; // array used to store coefficients .long long c[100]; // function to calculate the coefficients// of (x - 1)^n - (x^n - 1) with the help// of Pascal's triangle .void coef(int n){ c[0] = 1; for (int i = 0; i < n; c[0] = -c[0], i++) { c[1 + i] = 1; for (int j = i; j > 0; j--) c[j] = c[j - 1] - c[j]; }} // function to check whether// the number is prime or notbool isPrime(int n){ // Calculating all the coefficients by // the function coef and storing all // the coefficients in c array . coef(n); // subtracting c[n] and adding c[0] by 1 // as ( x - 1 )^n - ( x^n - 1), here we // are subtracting c[n] by 1 and adding // 1 in expression. c[0]++, c[n]--; // checking all the coefficients whether // they are divisible by n or not. // if n is not prime, then loop breaks // and (i > 0). int i = n; while (i-- && c[i] % n == 0) ; // Return true if all coefficients are // divisible by n. return i < 0;} // driver programint main(){ int n = 37; if (isPrime(n)) cout << \"Prime\" << endl; else cout << \"Not Prime\" << endl; return 0;}", "e": 28593, "s": 27220, "text": null }, { "code": "// Java code to check if number is prime. This// program demonstrates concept behind AKS// algorithm and doesn't implement the actual// algorithm (This works only till n = 64) class GFG { // array used to store coefficients . static long c[] = new long[100]; // function to calculate the coefficients // of (x - 1)^n - (x^n - 1) with the help // of Pascal's triangle . static void coef(int n) { c[0] = 1; for (int i = 0; i < n; c[0] = -c[0], i++) { c[1 + i] = 1; for (int j = i; j > 0; j--) c[j] = c[j - 1] - c[j]; } } // function to check whether // the number is prime or not static boolean isPrime(int n) { // Calculating all the coefficients by // the function coef and storing all // the coefficients in c array . coef(n); // subtracting c[n] and adding c[0] by 1 // as ( x - 1 )^n - ( x^n - 1), here we // are subtracting c[n] by 1 and adding // 1 in expression. c[0]++; c[n]--; // checking all the coefficients whether // they are divisible by n or not. // if n is not prime, then loop breaks // and (i > 0). int i = n; while ((i--) > 0 && c[i] % n == 0) ; // Return true if all coefficients are // divisible by n. return i < 0; } // Driver code public static void main(String[] args) { int n = 37; if (isPrime(n)) System.out.println(\"Prime\"); else System.out.println(\"Not Prime\"); }} // This code is contributed by Anant Agarwal.", "e": 30233, "s": 28593, "text": null }, { "code": "# Python3 code to check if# number is prime. This# program demonstrates concept# behind AKS algorithm and# doesn't implement the actual# algorithm (This works only# till n = 64) # array used to# store coefficients .c = [0] * 100; # function to calculate the# coefficients of (x - 1)^n -# (x^n - 1) with the help# of Pascal's triangle .def coef(n): c[0] = 1; for i in range(n): c[1 + i] = 1; for j in range(i, 0, -1): c[j] = c[j - 1] - c[j]; c[0] = -c[0]; # function to check whether# the number is prime or notdef isPrime(n): # Calculating all the coefficients # by the function coef and storing # all the coefficients in c array . coef(n); # subtracting c[n] and adding # c[0] by 1 as ( x - 1 )^n - # ( x^n - 1), here we are # subtracting c[n] by 1 and # adding 1 in expression. c[0] = c[0] + 1; c[n] = c[n] - 1; # checking all the coefficients # whether they are divisible by # n or not. if n is not prime, # then loop breaks and (i > 0). i = n; while (i > -1 and c[i] % n == 0): i = i - 1; # Return true if all coefficients # are divisible by n. return True if i < 0 else False; # Driver Coden = 37;if (isPrime(n)): print(\"Prime\");else: print(\"Not Prime\"); # This code is contributed by mits", "e": 31571, "s": 30233, "text": null }, { "code": "// C# code to check if number is prime. This// program demonstrates concept behind AKS// algorithm and doesn't implement the actual// algorithm (This works only till n = 64)using System; class GFG { // array used to store coefficients . static long []c = new long[100]; // function to calculate the coefficients // of (x - 1)^n - (x^n - 1) with the help // of Pascal's triangle . static void coef(int n) { c[0] = 1; for (int i = 0; i < n; c[0] = -c[0], i++) { c[1 + i] = 1; for (int j = i; j > 0; j--) c[j] = c[j - 1] - c[j]; } } // function to check whether // the number is prime or not static bool isPrime(int n) { // Calculating all the coefficients by // the function coef and storing all // the coefficients in c array . coef(n); // subtracting c[n] and adding c[0] by 1 // as ( x - 1 )^n - ( x^n - 1), here we // are subtracting c[n] by 1 and adding // 1 in expression. c[0]++; c[n]--; // checking all the coefficients whether // they are divisible by n or not. // if n is not prime, then loop breaks // and (i > 0). int i = n; while ((i--) > 0 && c[i] % n == 0) ; // Return true if all coefficients are // divisible by n. return i < 0; } // Driver code public static void Main() { int n = 37; if (isPrime(n)) Console.WriteLine(\"Prime\"); else Console.WriteLine(\"Not Prime\"); }} // This code is contributed by anuj_67.", "e": 33233, "s": 31571, "text": null }, { "code": "<?php// PHP code to check if number// is prime. This program// demonstrates concept behind// AKS algorithm and doesn't// implement the actual// algorithm (This works only// till n = 64) // array used to// store coefficients .global $c; // function to calculate// the coefficients// of (x - 1)^n -// (x^n - 1) with the help// of Pascal's triangle .function coef($n){ $c[0] = 1; for ($i = 0; $i < $n; $c[0] = -$c[0], $i++) { $c[1 + $i] = 1; for ($j = $i; $j > 0; $j--) $c[$j] = $c[$j - 1] - $c[$j]; }} // function to check whether// the number is prime or notfunction isPrime($n){ global $c; // Calculating all the // coefficients by the // function coef and // storing all the // coefficients in c array . coef($n); // subtracting c[n] and // adding c[0] by 1 as // ( x - 1 )^n - ( x^n - 1), // here we are subtracting c[n] // by 1 and adding 1 in expression. // $c[0]++; $c[$n]--; // checking all the coefficients whether // they are divisible by n or not. // if n is not prime, then loop breaks // and (i > 0). $i = $n; while ($i-- && $c[$i] % $n == 0) // Return true if all // coefficients are // divisible by n. return $i < 0;} // Driver Code $n = 37; if (isPrime($n)) echo \"Not Prime\", \"\\n\"; else echo \"Prime\", \"\\n\"; // This code is contributed by aj_36?>", "e": 34639, "s": 33233, "text": null }, { "code": "<script> // Javascript program to check if number is prime.// This program demonstrates concept behind AKS// algorithm and doesn't implement the actual// algorithm (This works only till n = 64) // array used to store coefficients . let c = []; // function to calculate the coefficients // of (x - 1)^n - (x^n - 1) with the help // of Pascal's triangle . function coef(n) { c[0] = 1; for (let i = 0; i < n; c[0] = -c[0], i++) { c[1 + i] = 1; for (let j = i; j > 0; j--) c[j] = c[j - 1] - c[j]; } } // function to check whether // the number is prime or not function isPrime(n) { // Calculating all the coefficients by // the function coef and storing all // the coefficients in c array . coef(n); // subtracting c[n] and adding c[0] by 1 // as ( x - 1 )^n - ( x^n - 1), here we // are subtracting c[n] by 1 and adding // 1 in expression. c[0]++; c[n]--; // checking all the coefficients whether // they are divisible by n or not. // if n is not prime, then loop breaks // and (i > 0). let i = n; while ((i--) > 0 && c[i] % n == 0) ; // Return true if all coefficients are // divisible by n. return i < 0; } // Driver code let n = 37; if (isPrime(n)) document.write(\"Prime\"); else document.write(\"Not Prime\"); </script>", "e": 36161, "s": 34639, "text": null }, { "code": null, "e": 36170, "s": 36161, "text": "Output: " }, { "code": null, "e": 36176, "s": 36170, "text": "Prime" }, { "code": null, "e": 36333, "s": 36176, "text": "References: https://en.wikipedia.org/wiki/AKS_primality_test https://rosettacode.org/wiki/AKS_test_for_primes#C https://www.youtube.com/watch?v=HvMSRWTE2mI " }, { "code": null, "e": 36339, "s": 36333, "text": "jit_t" }, { "code": null, "e": 36344, "s": 36339, "text": "vt_m" }, { "code": null, "e": 36357, "s": 36344, "text": "Mithun Kumar" }, { "code": null, "e": 36371, "s": 36357, "text": "sanskar27jain" }, { "code": null, "e": 36393, "s": 36371, "text": "susmitakundugoaldanga" }, { "code": null, "e": 36407, "s": 36393, "text": "number-theory" }, { "code": null, "e": 36420, "s": 36407, "text": "Prime Number" }, { "code": null, "e": 36444, "s": 36420, "text": "Competitive Programming" }, { "code": null, "e": 36457, "s": 36444, "text": "Mathematical" }, { "code": null, "e": 36476, "s": 36457, "text": "Technical Scripter" }, { "code": null, "e": 36490, "s": 36476, "text": "number-theory" }, { "code": null, "e": 36503, "s": 36490, "text": "Mathematical" }, { "code": null, "e": 36516, "s": 36503, "text": "Prime Number" }, { "code": null, "e": 36614, "s": 36516, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36623, "s": 36614, "text": "Comments" }, { "code": null, "e": 36636, "s": 36623, "text": "Old Comments" }, { "code": null, "e": 36663, "s": 36636, "text": "Modulo 10^9+7 (1000000007)" }, { "code": null, "e": 36741, "s": 36663, "text": "Prefix Sum Array - Implementation and Applications in Competitive Programming" }, { "code": null, "e": 36779, "s": 36741, "text": "Bits manipulation (Important tactics)" }, { "code": null, "e": 36804, "s": 36779, "text": "Formatted output in Java" }, { "code": null, "e": 36852, "s": 36804, "text": "Algorithm Library | C++ Magicians STL Algorithm" }, { "code": null, "e": 36882, "s": 36852, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 36897, "s": 36882, "text": "C++ Data Types" }, { "code": null, "e": 36957, "s": 36897, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 37000, "s": 36957, "text": "Set in C++ Standard Template Library (STL)" } ]
How to Prune Decision Trees to Make the Most Out of Them | by Soner Yıldırım | Towards Data Science
Decision trees are supervised machine learning algorithms that work by iteratively partitioning the dataset into smaller parts. The partitioning process is the most critical part of building decision trees. The partitions are not random. The aim is to increase the predictiveness of the model as much as possible at each partitioning so that the model keeps gaining information about the dataset. For instance, the following is a decision tree with a depth of 3. The first partition is based on feature 6 (X[6]) and able to put all data instances that belong to the first class (59) on the right side of the tree. This clearly shows that partitions that maximize the information gain are prioritized. The information gain can be quantified by Entropy or Gini impurity. In general, the information gain is proportional to the increase in purity (or decrease in impurity). The purity of a node is inversely proportional to the distribution of different classes in that node. Consider a case where you pick a data instance and randomly label it. Gini impurity measures how often your random label would be incorrect. If all data points had the same label, then the label would always be correct and Gini impurity would be zero. On the other hand, if data points were equally distributed among multiple labels, the random labels would often be incorrect. Thus, Gini impurity increases with randomness. Entropy is another measure of uncertainty or randomness. The more randomness a variable has, the higher the entropy is. Partitions that result in more pure nodes are chosen. Thus, when selecting a feature to partition the dataset, the decision tree algorithm tries to achieve: More predictiveness Less impurity Lower entropy The decision trees need to be carefully tuned to make the most out of them. Too deep trees are likely to result in overfitting. Scikit-learn provides several hyperparameters to control the growth of a tree. We will see how these hyperparameters achieve using the plot_tree function of the tree module of scikit-learn. I will use the wine dataset available under the datasets module of scikit-learn. Let’s first import the libraries and load the dataset. import numpy as npimport pandas as pdfrom sklearn import treefrom sklearn.datasets import load_wineimport matplotlib.pyplot as plt%matplotlib inlineX, y = load_wine(return_X_y=True) The dataset 178 observations that belong to 3 different classes. There are 13 features that describe the observations. X.shape(178,13)np.unique(y, return_counts=True)(array([0, 1, 2]), array([59, 71, 48])) We can now start building decision trees with different hyperparameter values. The obvious one is the max_depth which stops tree growth at the specified depth level. clf = tree.DecisionTreeClassifier(criterion='gini', max_depth=2)\.fit(X, y)plt.figure(figsize=(16,8))tree.plot_tree(clf, filled=True, fontsize=16) The partitions are selected based on Gini impurity and the depth of the tree is 2. Max_depth provides a simple way to control tree growth which may not be enough in more complex cases. The min_samples_split specifies the minimum number of samples in a node to be further split. clf = tree.DecisionTreeClassifier(criterion='gini', min_samples_split=10).fit(X, y)plt.figure(figsize=(20,8))tree.plot_tree(clf, filled=True, fontsize=16) I only put a part of the visualization where we see the effect of the current hyperparameter. The node at the right is not further split because there are only 5 samples in it. Without min_samples_split=10, it’d be further split as follows. Another hyperparameter to control tree growth is min_impurity_decrease which sets a threshold on the impurity decrease to consider a partition. It is a more educated way than the max depth because it takes into account the quality of a partition. clf = tree.DecisionTreeClassifier(criterion='gini', min_impurity_decrease=0.1).fit(X, y)plt.figure(figsize=(10, 6))tree.plot_tree(clf, filled=True, fontsize=16) All the partitions achieved a decrease of more than 0.1 on the impurity. When setting this value, we should also consider the criterion because Gini impurity and Entropy have different values. The max_leaf_nodes can also be used to control tree growth. It limits the number of leaf nodes a decision tree can have. The leaf nodes are the nodes at the end of a decision tree. The tree keeps growing in the best-first fashion until the maximum number of leaf nodes is reached. The best partitions are chosen based on the decrease in impurity. clf = tree.DecisionTreeClassifier(criterion='gini', max_leaf_nodes=5).fit(X, y)plt.figure(figsize=(14, 8))tree.plot_tree(clf, filled=True, fontsize=16) We have covered 5 different hyperparameters that can be used to control tree growth. Criterion Max_depth Min_samples_split Min_impurity_decrease Max_leaf_nodes We have adjusted them one by one to see the individual effects. However, in real-life cases, these hyperparameters need to be tuned together in order to create a robust and accurate model. If we grow a tree more than we should, we are likely to end up having an overfit model. Overfitting occurs when a tree fits the training set too well. Having very different accuracies on training and test sets is a strong indication of overfitting. In such cases, we should control the tree growth to obtain a well-generalized model. Thank you for reading. Please let me know if you have any feedback.
[ { "code": null, "e": 378, "s": 171, "text": "Decision trees are supervised machine learning algorithms that work by iteratively partitioning the dataset into smaller parts. The partitioning process is the most critical part of building decision trees." }, { "code": null, "e": 568, "s": 378, "text": "The partitions are not random. The aim is to increase the predictiveness of the model as much as possible at each partitioning so that the model keeps gaining information about the dataset." }, { "code": null, "e": 634, "s": 568, "text": "For instance, the following is a decision tree with a depth of 3." }, { "code": null, "e": 785, "s": 634, "text": "The first partition is based on feature 6 (X[6]) and able to put all data instances that belong to the first class (59) on the right side of the tree." }, { "code": null, "e": 1042, "s": 785, "text": "This clearly shows that partitions that maximize the information gain are prioritized. The information gain can be quantified by Entropy or Gini impurity. In general, the information gain is proportional to the increase in purity (or decrease in impurity)." }, { "code": null, "e": 1144, "s": 1042, "text": "The purity of a node is inversely proportional to the distribution of different classes in that node." }, { "code": null, "e": 1569, "s": 1144, "text": "Consider a case where you pick a data instance and randomly label it. Gini impurity measures how often your random label would be incorrect. If all data points had the same label, then the label would always be correct and Gini impurity would be zero. On the other hand, if data points were equally distributed among multiple labels, the random labels would often be incorrect. Thus, Gini impurity increases with randomness." }, { "code": null, "e": 1689, "s": 1569, "text": "Entropy is another measure of uncertainty or randomness. The more randomness a variable has, the higher the entropy is." }, { "code": null, "e": 1846, "s": 1689, "text": "Partitions that result in more pure nodes are chosen. Thus, when selecting a feature to partition the dataset, the decision tree algorithm tries to achieve:" }, { "code": null, "e": 1866, "s": 1846, "text": "More predictiveness" }, { "code": null, "e": 1880, "s": 1866, "text": "Less impurity" }, { "code": null, "e": 1894, "s": 1880, "text": "Lower entropy" }, { "code": null, "e": 2101, "s": 1894, "text": "The decision trees need to be carefully tuned to make the most out of them. Too deep trees are likely to result in overfitting. Scikit-learn provides several hyperparameters to control the growth of a tree." }, { "code": null, "e": 2212, "s": 2101, "text": "We will see how these hyperparameters achieve using the plot_tree function of the tree module of scikit-learn." }, { "code": null, "e": 2348, "s": 2212, "text": "I will use the wine dataset available under the datasets module of scikit-learn. Let’s first import the libraries and load the dataset." }, { "code": null, "e": 2530, "s": 2348, "text": "import numpy as npimport pandas as pdfrom sklearn import treefrom sklearn.datasets import load_wineimport matplotlib.pyplot as plt%matplotlib inlineX, y = load_wine(return_X_y=True)" }, { "code": null, "e": 2649, "s": 2530, "text": "The dataset 178 observations that belong to 3 different classes. There are 13 features that describe the observations." }, { "code": null, "e": 2736, "s": 2649, "text": "X.shape(178,13)np.unique(y, return_counts=True)(array([0, 1, 2]), array([59, 71, 48]))" }, { "code": null, "e": 2902, "s": 2736, "text": "We can now start building decision trees with different hyperparameter values. The obvious one is the max_depth which stops tree growth at the specified depth level." }, { "code": null, "e": 3049, "s": 2902, "text": "clf = tree.DecisionTreeClassifier(criterion='gini', max_depth=2)\\.fit(X, y)plt.figure(figsize=(16,8))tree.plot_tree(clf, filled=True, fontsize=16)" }, { "code": null, "e": 3234, "s": 3049, "text": "The partitions are selected based on Gini impurity and the depth of the tree is 2. Max_depth provides a simple way to control tree growth which may not be enough in more complex cases." }, { "code": null, "e": 3327, "s": 3234, "text": "The min_samples_split specifies the minimum number of samples in a node to be further split." }, { "code": null, "e": 3482, "s": 3327, "text": "clf = tree.DecisionTreeClassifier(criterion='gini', min_samples_split=10).fit(X, y)plt.figure(figsize=(20,8))tree.plot_tree(clf, filled=True, fontsize=16)" }, { "code": null, "e": 3723, "s": 3482, "text": "I only put a part of the visualization where we see the effect of the current hyperparameter. The node at the right is not further split because there are only 5 samples in it. Without min_samples_split=10, it’d be further split as follows." }, { "code": null, "e": 3970, "s": 3723, "text": "Another hyperparameter to control tree growth is min_impurity_decrease which sets a threshold on the impurity decrease to consider a partition. It is a more educated way than the max depth because it takes into account the quality of a partition." }, { "code": null, "e": 4131, "s": 3970, "text": "clf = tree.DecisionTreeClassifier(criterion='gini', min_impurity_decrease=0.1).fit(X, y)plt.figure(figsize=(10, 6))tree.plot_tree(clf, filled=True, fontsize=16)" }, { "code": null, "e": 4324, "s": 4131, "text": "All the partitions achieved a decrease of more than 0.1 on the impurity. When setting this value, we should also consider the criterion because Gini impurity and Entropy have different values." }, { "code": null, "e": 4505, "s": 4324, "text": "The max_leaf_nodes can also be used to control tree growth. It limits the number of leaf nodes a decision tree can have. The leaf nodes are the nodes at the end of a decision tree." }, { "code": null, "e": 4671, "s": 4505, "text": "The tree keeps growing in the best-first fashion until the maximum number of leaf nodes is reached. The best partitions are chosen based on the decrease in impurity." }, { "code": null, "e": 4823, "s": 4671, "text": "clf = tree.DecisionTreeClassifier(criterion='gini', max_leaf_nodes=5).fit(X, y)plt.figure(figsize=(14, 8))tree.plot_tree(clf, filled=True, fontsize=16)" }, { "code": null, "e": 4908, "s": 4823, "text": "We have covered 5 different hyperparameters that can be used to control tree growth." }, { "code": null, "e": 4918, "s": 4908, "text": "Criterion" }, { "code": null, "e": 4928, "s": 4918, "text": "Max_depth" }, { "code": null, "e": 4946, "s": 4928, "text": "Min_samples_split" }, { "code": null, "e": 4968, "s": 4946, "text": "Min_impurity_decrease" }, { "code": null, "e": 4983, "s": 4968, "text": "Max_leaf_nodes" }, { "code": null, "e": 5172, "s": 4983, "text": "We have adjusted them one by one to see the individual effects. However, in real-life cases, these hyperparameters need to be tuned together in order to create a robust and accurate model." }, { "code": null, "e": 5506, "s": 5172, "text": "If we grow a tree more than we should, we are likely to end up having an overfit model. Overfitting occurs when a tree fits the training set too well. Having very different accuracies on training and test sets is a strong indication of overfitting. In such cases, we should control the tree growth to obtain a well-generalized model." } ]
Find sum of integers in a file which contains any characters - GeeksforGeeks
06 Sep, 2017 You are given a text file which contains any type of characters. You have to find the sum of integer values. Examples: Input : text.txt Let contents of test.txt be : :-,,$%^5313&^*1)(*( 464sz29>>///11!!! (*HB%$#)(*0900 Output : 6727 Input : text1.txt Let contents of test.txt be : 234***3r3r() ()(0)34 Output : 274 Steps :1. To open the file in only read mode we can use ifstream library2. Iterate through all rows of the file and find all integers3. If integer found then store it in temp variable because there is a chance that next character can be an integer4. Add temp value in final result if any character found except integers and set temp = 0 again5. If last element is an integer then we have to add temp after loop if it isn’t then the value of temp will already be zero. So sum will not affected. // C++ implementation of given text file which// contains any type of characters. We have to// find the sum of integer value.#include <bits/stdc++.h>using namespace std; // a function which return sum of all integers// find in input text fileint findSumOfIntegers(){ ifstream f; // to open the text file in read mode f.open("text.txt"); int sum = 0, num = 0; // One by one read strings from file. Note that // f >> text works same as cin >> text. string text; while (f >> text) { // Move in row and find all integers for (int i = 0; text[i] != '\0'; i++) { // Find value of current integer if (isdigit(text[i])) num = 10 * num + (text[i] - '0'); // If other character, add it to the // result else { sum += num; num = 0; // and now replace // previous number with 0 } } } sum += num; return sum;} // Driver program to test above functionsint main(){ cout << findSumOfIntegers(); return 0;} Output: 6727 (for Input 1) This article is contributed by Harshit Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. cpp-file-handling C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Operator Overloading in C++ Iterators in C++ STL Polymorphism in C++ Friend class and function in C++ Sorting a vector in C++ Convert string to char array in C++ Inline Functions in C++ List in C++ Standard Template Library (STL) new and delete operators in C++ for dynamic memory std::string class in C++
[ { "code": null, "e": 24124, "s": 24096, "text": "\n06 Sep, 2017" }, { "code": null, "e": 24233, "s": 24124, "text": "You are given a text file which contains any type of characters. You have to find the sum of integer values." }, { "code": null, "e": 24243, "s": 24233, "text": "Examples:" }, { "code": null, "e": 24447, "s": 24243, "text": "Input : text.txt \nLet contents of test.txt be : \n:-,,$%^5313&^*1)(*(\n464sz29>>///11!!!\n(*HB%$#)(*0900\n\nOutput : 6727\n\nInput : text1.txt \nLet contents of test.txt be : \n234***3r3r()\n()(0)34\n\nOutput : 274\n" }, { "code": null, "e": 24941, "s": 24447, "text": "Steps :1. To open the file in only read mode we can use ifstream library2. Iterate through all rows of the file and find all integers3. If integer found then store it in temp variable because there is a chance that next character can be an integer4. Add temp value in final result if any character found except integers and set temp = 0 again5. If last element is an integer then we have to add temp after loop if it isn’t then the value of temp will already be zero. So sum will not affected." }, { "code": "// C++ implementation of given text file which// contains any type of characters. We have to// find the sum of integer value.#include <bits/stdc++.h>using namespace std; // a function which return sum of all integers// find in input text fileint findSumOfIntegers(){ ifstream f; // to open the text file in read mode f.open(\"text.txt\"); int sum = 0, num = 0; // One by one read strings from file. Note that // f >> text works same as cin >> text. string text; while (f >> text) { // Move in row and find all integers for (int i = 0; text[i] != '\\0'; i++) { // Find value of current integer if (isdigit(text[i])) num = 10 * num + (text[i] - '0'); // If other character, add it to the // result else { sum += num; num = 0; // and now replace // previous number with 0 } } } sum += num; return sum;} // Driver program to test above functionsint main(){ cout << findSumOfIntegers(); return 0;}", "e": 26052, "s": 24941, "text": null }, { "code": null, "e": 26060, "s": 26052, "text": "Output:" }, { "code": null, "e": 26080, "s": 26060, "text": "6727 (for Input 1)\n" }, { "code": null, "e": 26383, "s": 26080, "text": "This article is contributed by Harshit Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 26508, "s": 26383, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 26526, "s": 26508, "text": "cpp-file-handling" }, { "code": null, "e": 26530, "s": 26526, "text": "C++" }, { "code": null, "e": 26534, "s": 26530, "text": "CPP" }, { "code": null, "e": 26632, "s": 26534, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26641, "s": 26632, "text": "Comments" }, { "code": null, "e": 26654, "s": 26641, "text": "Old Comments" }, { "code": null, "e": 26682, "s": 26654, "text": "Operator Overloading in C++" }, { "code": null, "e": 26703, "s": 26682, "text": "Iterators in C++ STL" }, { "code": null, "e": 26723, "s": 26703, "text": "Polymorphism in C++" }, { "code": null, "e": 26756, "s": 26723, "text": "Friend class and function in C++" }, { "code": null, "e": 26780, "s": 26756, "text": "Sorting a vector in C++" }, { "code": null, "e": 26816, "s": 26780, "text": "Convert string to char array in C++" }, { "code": null, "e": 26840, "s": 26816, "text": "Inline Functions in C++" }, { "code": null, "e": 26884, "s": 26840, "text": "List in C++ Standard Template Library (STL)" }, { "code": null, "e": 26935, "s": 26884, "text": "new and delete operators in C++ for dynamic memory" } ]
VBA - For Each Loops
A For Each loop is used to execute a statement or a group of statements for each element in an array or collection. A For Each loop is similar to For Loop; however, the loop is executed for each element in an array or group. Hence, the step counter won't exist in this type of loop. It is mostly used with arrays or used in context of the File system objects in order to operate recursively. Following is the syntax of a For Each loop in VBA. For Each element In Group [statement 1] [statement 2] .... [statement n] [Exit For] [statement 11] [statement 22] Next Private Sub Constant_demo_Click() 'fruits is an array fruits = Array("apple", "orange", "cherries") Dim fruitnames As Variant 'iterating using For each loop. For Each Item In fruits fruitnames = fruitnames & Item & Chr(10) Next MsgBox fruitnames End Sub When the above code is executed, it prints all the fruit names with one item in each line. apple orange cherries 101 Lectures 6 hours Pavan Lalwani 41 Lectures 3 hours Arnold Higuit 80 Lectures 5.5 hours Prashant Panchal 25 Lectures 2 hours Prashant Panchal 26 Lectures 2 hours Arnold Higuit 92 Lectures 10.5 hours Vijay Kumar Parvatha Reddy Print Add Notes Bookmark this page
[ { "code": null, "e": 2051, "s": 1935, "text": "A For Each loop is used to execute a statement or a group of statements for each element in an array or collection." }, { "code": null, "e": 2327, "s": 2051, "text": "A For Each loop is similar to For Loop; however, the loop is executed for each element in an array or group. Hence, the step counter won't exist in this type of loop. It is mostly used with arrays or used in context of the File system objects in order to operate recursively." }, { "code": null, "e": 2378, "s": 2327, "text": "Following is the syntax of a For Each loop in VBA." }, { "code": null, "e": 2519, "s": 2378, "text": "For Each element In Group\n [statement 1]\n [statement 2]\n ....\n [statement n]\n [Exit For]\n [statement 11]\n [statement 22]\nNext\n" }, { "code": null, "e": 2808, "s": 2519, "text": "Private Sub Constant_demo_Click() \n 'fruits is an array\n fruits = Array(\"apple\", \"orange\", \"cherries\")\n Dim fruitnames As Variant\n \n 'iterating using For each loop.\n For Each Item In fruits\n fruitnames = fruitnames & Item & Chr(10)\n Next\n \n MsgBox fruitnames\nEnd Sub" }, { "code": null, "e": 2899, "s": 2808, "text": "When the above code is executed, it prints all the fruit names with one item in each line." }, { "code": null, "e": 2922, "s": 2899, "text": "apple\norange\ncherries\n" }, { "code": null, "e": 2956, "s": 2922, "text": "\n 101 Lectures \n 6 hours \n" }, { "code": null, "e": 2971, "s": 2956, "text": " Pavan Lalwani" }, { "code": null, "e": 3004, "s": 2971, "text": "\n 41 Lectures \n 3 hours \n" }, { "code": null, "e": 3019, "s": 3004, "text": " Arnold Higuit" }, { "code": null, "e": 3054, "s": 3019, "text": "\n 80 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3072, "s": 3054, "text": " Prashant Panchal" }, { "code": null, "e": 3105, "s": 3072, "text": "\n 25 Lectures \n 2 hours \n" }, { "code": null, "e": 3123, "s": 3105, "text": " Prashant Panchal" }, { "code": null, "e": 3156, "s": 3123, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 3171, "s": 3156, "text": " Arnold Higuit" }, { "code": null, "e": 3207, "s": 3171, "text": "\n 92 Lectures \n 10.5 hours \n" }, { "code": null, "e": 3235, "s": 3207, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 3242, "s": 3235, "text": " Print" }, { "code": null, "e": 3253, "s": 3242, "text": " Add Notes" } ]
Adding multiple constraints in a single table - GeeksforGeeks
17 Dec, 2020 Prerequisite – SQL Constraints We can create a table with more than one constraint in its columns. Following example shows how we can define different constraints on a table. Adding constraints in Create command : Sr_no is a Primary Key. Branch_no is the foreign key referencing Branch table. Company type will hold either of the values : ‘1C’, ’2C’, ’3C’ Syntax : Create table Fd_master(Sr_no varchar2(10), Branch_no varchar2(10), account_no varchar2(20), company_type varchar2(20), constraint pk primary key(Sr_no), constraint fk foreign key (Branch_no) references Branch, constraint chk check(company_type in (‘1C’, ’2C’, ’3C’))); Primary Key constraint –Sr_no in Fd_master where pk is userdefined name given to Primary key.Foreign Key constraint –Branch_no in Fd_master where fk is name of foreign key that references branch table.Check constraint –company_type in Fd_master where chk is name that will check the given values i.e ‘1C’, ‘2C’, ‘3C’ Primary Key constraint –Sr_no in Fd_master where pk is userdefined name given to Primary key. Foreign Key constraint –Branch_no in Fd_master where fk is name of foreign key that references branch table. Check constraint –company_type in Fd_master where chk is name that will check the given values i.e ‘1C’, ‘2C’, ‘3C’ Adding constraints in Alter command :Multiple columns level constraints can be added via alter command. It can be added in parent-child table in a serial order. Constraint 1 (Default) :Create two tables – Parent having default constraint on ID with the default value 1. Name given to constraint is DF_ParentTable. Foreign table with ID column. ID in both the table is made ‘NOT NULL’. Syntax : CREATE TABLE ParentTable (ID int not null constraint DF_ParentTable default (1), name varchar2(5)); CREATE TABLE ForeignTable (ID int not null, Col2 VARCHAR(5)); Constraint 2 (Check) : ALTER TABLE ParentTable ADD CONSTRAINT CK_ParentTable_ID CHECK(ID<100); Constraint 3 (Foreign Key) :Foreign Key ALTER TABLE ParentTable ADD CONSTRAINT FK_parent_foreign FOREIGN KEY (ID) REFERENCES ForeignTable(ID); 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? What is Temporary Table in SQL? SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL using Python SQL | Subquery SQL Query to Convert VARCHAR to INT How to Write a SQL Query For a Specific Date Range and Date Time? How to Select Data Between Two Dates and Times in SQL Server? SQL - SELECT from Multiple Tables with MS SQL Server SQL Query to Delete Duplicate Rows
[ { "code": null, "e": 24268, "s": 24240, "text": "\n17 Dec, 2020" }, { "code": null, "e": 24299, "s": 24268, "text": "Prerequisite – SQL Constraints" }, { "code": null, "e": 24443, "s": 24299, "text": "We can create a table with more than one constraint in its columns. Following example shows how we can define different constraints on a table." }, { "code": null, "e": 24482, "s": 24443, "text": "Adding constraints in Create command :" }, { "code": null, "e": 24506, "s": 24482, "text": "Sr_no is a Primary Key." }, { "code": null, "e": 24561, "s": 24506, "text": "Branch_no is the foreign key referencing Branch table." }, { "code": null, "e": 24624, "s": 24561, "text": "Company type will hold either of the values : ‘1C’, ’2C’, ’3C’" }, { "code": null, "e": 24633, "s": 24624, "text": "Syntax :" }, { "code": null, "e": 24905, "s": 24633, "text": "Create table Fd_master(Sr_no varchar2(10), \nBranch_no varchar2(10), account_no varchar2(20),\ncompany_type varchar2(20), constraint pk primary key(Sr_no), \nconstraint fk foreign key (Branch_no) references Branch,\nconstraint chk check(company_type in (‘1C’, ’2C’, ’3C’)));" }, { "code": null, "e": 25222, "s": 24905, "text": "Primary Key constraint –Sr_no in Fd_master where pk is userdefined name given to Primary key.Foreign Key constraint –Branch_no in Fd_master where fk is name of foreign key that references branch table.Check constraint –company_type in Fd_master where chk is name that will check the given values i.e ‘1C’, ‘2C’, ‘3C’" }, { "code": null, "e": 25316, "s": 25222, "text": "Primary Key constraint –Sr_no in Fd_master where pk is userdefined name given to Primary key." }, { "code": null, "e": 25425, "s": 25316, "text": "Foreign Key constraint –Branch_no in Fd_master where fk is name of foreign key that references branch table." }, { "code": null, "e": 25541, "s": 25425, "text": "Check constraint –company_type in Fd_master where chk is name that will check the given values i.e ‘1C’, ‘2C’, ‘3C’" }, { "code": null, "e": 25702, "s": 25541, "text": "Adding constraints in Alter command :Multiple columns level constraints can be added via alter command. It can be added in parent-child table in a serial order." }, { "code": null, "e": 25746, "s": 25702, "text": "Constraint 1 (Default) :Create two tables –" }, { "code": null, "e": 25855, "s": 25746, "text": "Parent having default constraint on ID with the default value 1. Name given to constraint is DF_ParentTable." }, { "code": null, "e": 25885, "s": 25855, "text": "Foreign table with ID column." }, { "code": null, "e": 25926, "s": 25885, "text": "ID in both the table is made ‘NOT NULL’." }, { "code": null, "e": 25935, "s": 25926, "text": "Syntax :" }, { "code": null, "e": 26036, "s": 25935, "text": "CREATE TABLE ParentTable (ID int not null constraint DF_ParentTable default (1), \nname varchar2(5));" }, { "code": null, "e": 26098, "s": 26036, "text": "CREATE TABLE ForeignTable (ID int not null, Col2 VARCHAR(5));" }, { "code": null, "e": 26121, "s": 26098, "text": "Constraint 2 (Check) :" }, { "code": null, "e": 26193, "s": 26121, "text": "ALTER TABLE ParentTable ADD CONSTRAINT CK_ParentTable_ID CHECK(ID<100);" }, { "code": null, "e": 26233, "s": 26193, "text": "Constraint 3 (Foreign Key) :Foreign Key" }, { "code": null, "e": 26337, "s": 26233, "text": "ALTER TABLE ParentTable \nADD CONSTRAINT FK_parent_foreign FOREIGN KEY (ID) REFERENCES ForeignTable(ID);" }, { "code": null, "e": 26346, "s": 26337, "text": "DBMS-SQL" }, { "code": null, "e": 26350, "s": 26346, "text": "SQL" }, { "code": null, "e": 26354, "s": 26350, "text": "SQL" }, { "code": null, "e": 26452, "s": 26354, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26518, "s": 26452, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 26550, "s": 26518, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 26628, "s": 26550, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 26645, "s": 26628, "text": "SQL using Python" }, { "code": null, "e": 26660, "s": 26645, "text": "SQL | Subquery" }, { "code": null, "e": 26696, "s": 26660, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 26762, "s": 26696, "text": "How to Write a SQL Query For a Specific Date Range and Date Time?" }, { "code": null, "e": 26824, "s": 26762, "text": "How to Select Data Between Two Dates and Times in SQL Server?" }, { "code": null, "e": 26877, "s": 26824, "text": "SQL - SELECT from Multiple Tables with MS SQL Server" } ]
Java constructor return a value but, what?
No. Java constructor cannot return a value. If required, just create a method which calls the required constructor and returns the required value. See the example below. public class Tester { public Tester(){} public static Tester getInstance(){ Tester tester = new Tester(); return tester; } }
[ { "code": null, "e": 1232, "s": 1062, "text": "No. Java constructor cannot return a value. If required, just create a method which calls the required constructor and returns the required value. See the example below." }, { "code": null, "e": 1379, "s": 1232, "text": "public class Tester {\n public Tester(){}\n public static Tester getInstance(){\n Tester tester = new Tester();\n return tester;\n }\n}" } ]
How to find the sum based on a categorical variable in an R data frame?
Finding group-wise mean is a common thing but if we go for step-by-step analysis then sum of values are also required when we have a categorical variable in our data set. This can be easily done with the help of group_by and summarise_each function of dplyr package. Consider the below data frame: Live Demo > Group<-sample(LETTERS[1:4],20,replace=TRUE) > Salary<-sample(21000:50000,20) > Emp<-data.frame(Group,Salary) > Emp Group Salary 1 D 28256 2 B 31092 3 A 23147 4 C 28209 5 B 37676 6 C 33374 7 D 44864 8 B 40152 9 A 25843 10 A 40946 11 D 23321 12 A 42854 13 C 36960 14 A 35285 15 B 44478 16 B 36173 17 C 35077 18 A 39319 19 D 49204 20 A 41597 Loading dplyr package: > library(dplyr) Finding the sum of salaries in each group: > Emp %>% group_by(Group) %>% summarise_each(funs(sum)) # A tibble: 4 x 2 Group Salary 1 A 248991 2 B 189571 3 C 133620 4 D 145645 Warning message: `...` is not empty. We detected these problematic arguments: * `needs_dots` These dots only exist to allow future extensions and should be empty. Did you misspecify an argument? Do not worry about the warning message here, it occurred due to the version of dplyr. Our output is correct. If you want to ignore this warning then we need to install the latest version of tibble from CRAN. We are showing this here because you are likely to face the same problem but not necessarily. Let’s have a look at another example: Live Demo > x<-sample(c("India","USA","China","Canada"),20,replace=TRUE) > y<-rpois(20,5) > df<-data.frame(x,y) > df x y 1 India 5 2 India 3 3 India 4 4 China 5 5 Canada 3 6 USA 5 7 Canada 7 8 China 6 9 China 4 10 USA 7 11 China 5 12 India 8 13 Canada 3 14 India 6 15 Canada 5 16 Canada 3 17 Canada 7 18 USA 12 19 China 2 20 India 5 > df %>% group_by(x) %>% summarise_each(funs(sum)) # A tibble: 4 x 2 x y 1 Canada 28 2 China 22 3 India 31 4 USA 24 Warning message: `...` is not empty. We detected these problematic arguments: * `needs_dots` These dots only exist to allow future extensions and should be empty. Did you misspecify an argument?
[ { "code": null, "e": 1329, "s": 1062, "text": "Finding group-wise mean is a common thing but if we go for step-by-step analysis then sum of values are also required when we have a categorical variable in our data set. This can be easily done with the help of group_by and summarise_each function of dplyr package." }, { "code": null, "e": 1360, "s": 1329, "text": "Consider the below data frame:" }, { "code": null, "e": 1370, "s": 1360, "text": "Live Demo" }, { "code": null, "e": 1487, "s": 1370, "text": "> Group<-sample(LETTERS[1:4],20,replace=TRUE)\n> Salary<-sample(21000:50000,20)\n> Emp<-data.frame(Group,Salary)\n> Emp" }, { "code": null, "e": 1711, "s": 1487, "text": "Group Salary\n1 D 28256\n2 B 31092\n3 A 23147\n4 C 28209\n5 B 37676\n6 C 33374\n7 D 44864\n8 B 40152\n9 A 25843\n10 A 40946\n11 D 23321\n12 A 42854\n13 C 36960\n14 A 35285\n15 B 44478\n16 B 36173\n17 C 35077\n18 A 39319\n19 D 49204\n20 A 41597" }, { "code": null, "e": 1734, "s": 1711, "text": "Loading dplyr package:" }, { "code": null, "e": 1751, "s": 1734, "text": "> library(dplyr)" }, { "code": null, "e": 1794, "s": 1751, "text": "Finding the sum of salaries in each group:" }, { "code": null, "e": 1868, "s": 1794, "text": "> Emp %>% group_by(Group) %>% summarise_each(funs(sum))\n# A tibble: 4 x 2" }, { "code": null, "e": 1962, "s": 1868, "text": "Group Salary\n1 A 248991\n2 B 189571\n3 C 133620\n4 D 145645\nWarning message:\n`...` is not empty." }, { "code": null, "e": 2003, "s": 1962, "text": "We detected these problematic arguments:" }, { "code": null, "e": 2018, "s": 2003, "text": "* `needs_dots`" }, { "code": null, "e": 2088, "s": 2018, "text": "These dots only exist to allow future extensions and should be empty." }, { "code": null, "e": 2120, "s": 2088, "text": "Did you misspecify an argument?" }, { "code": null, "e": 2422, "s": 2120, "text": "Do not worry about the warning message here, it occurred due to the version of dplyr. Our output is correct. If you want to ignore this warning then we need to install the latest version of tibble from CRAN. We are showing this here because you are likely to face the same problem but not necessarily." }, { "code": null, "e": 2460, "s": 2422, "text": "Let’s have a look at another example:" }, { "code": null, "e": 2470, "s": 2460, "text": "Live Demo" }, { "code": null, "e": 2577, "s": 2470, "text": "> x<-sample(c(\"India\",\"USA\",\"China\",\"Canada\"),20,replace=TRUE)\n> y<-rpois(20,5)\n> df<-data.frame(x,y)\n> df" }, { "code": null, "e": 2793, "s": 2577, "text": "x y\n1 India 5\n2 India 3\n3 India 4\n4 China 5\n5 Canada 3\n6 USA 5\n7 Canada 7\n8 China 6\n9 China 4\n10 USA 7\n11 China 5\n12 India 8\n13 Canada 3\n14 India 6\n15 Canada 5\n16 Canada 3\n17 Canada 7\n18 USA 12\n19 China 2\n20 India 5" }, { "code": null, "e": 2862, "s": 2793, "text": "> df %>% group_by(x) %>% summarise_each(funs(sum))\n# A tibble: 4 x 2" }, { "code": null, "e": 2946, "s": 2862, "text": "x y\n1 Canada 28\n2 China 22\n3 India 31\n4 USA 24\nWarning message:\n`...` is not empty." }, { "code": null, "e": 2987, "s": 2946, "text": "We detected these problematic arguments:" }, { "code": null, "e": 3002, "s": 2987, "text": "* `needs_dots`" }, { "code": null, "e": 3072, "s": 3002, "text": "These dots only exist to allow future extensions and should be empty." }, { "code": null, "e": 3104, "s": 3072, "text": "Did you misspecify an argument?" } ]
Pascal - Operators Precedence
Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator. For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7. Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first. The following table expresses the Pascal operator precedence − Try the following example to understand the operator precedence available in Pascal − program opPrecedence; var a, b, c, d : integer; e: real; begin a := 20; b := 10; c := 15; d := 5; e := (a + b) * c / d; (* ( 30 * 15 ) / 5 *) writeln('Value of (a + b) * c / d is : ', e:3:1 ); e := ((a + b) * c) / d; (* (30 * 15 ) / 5 *) writeln('Value of ((a + b) * c) / d is : ' , e:3:1 ); e := (a + b) * (c / d); (* (30) * (15/5) *) writeln('Value of (a + b) * (c / d) is : ', e:3:1); e := a + (b * c) / d; (* 20 + (150/5) *) writeln('Value of a + (b * c) / d is : ' , e:3:1 ); end. When the above code is compiled and executed, it produces the following result: Value of (a + b) * c / d is : 90.0 Value of ((a + b) * c) / d is : 90.0 Value of (a + b) * (c / d) is : 90.0 Value of a + (b * c) / d is : 50.0 94 Lectures 8.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2344, "s": 2083, "text": "Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator." }, { "code": null, "e": 2510, "s": 2344, "text": "For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7." }, { "code": null, "e": 2768, "s": 2510, "text": "Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first. The following table expresses the Pascal operator precedence −" }, { "code": null, "e": 2854, "s": 2768, "text": "Try the following example to understand the operator precedence available in Pascal −" }, { "code": null, "e": 3406, "s": 2854, "text": "program opPrecedence;\nvar\na, b, c, d : integer;\ne: real;\n\nbegin\n a := 20;\n b := 10;\n c := 15;\n d := 5;\n e := (a + b) * c / d; (* ( 30 * 15 ) / 5 *)\n writeln('Value of (a + b) * c / d is : ', e:3:1 );\n\n e := ((a + b) * c) / d; (* (30 * 15 ) / 5 *)\n writeln('Value of ((a + b) * c) / d is : ' , e:3:1 );\n\n e := (a + b) * (c / d); (* (30) * (15/5) *)\n writeln('Value of (a + b) * (c / d) is : ', e:3:1);\n\n e := a + (b * c) / d; (* 20 + (150/5) *)\n writeln('Value of a + (b * c) / d is : ' , e:3:1 );\nend." }, { "code": null, "e": 3486, "s": 3406, "text": "When the above code is compiled and executed, it produces the following result:" }, { "code": null, "e": 3634, "s": 3486, "text": "Value of (a + b) * c / d is : 90.0\nValue of ((a + b) * c) / d is : 90.0\nValue of (a + b) * (c / d) is : 90.0\nValue of a + (b * c) / d is : 50.0\n" }, { "code": null, "e": 3669, "s": 3634, "text": "\n 94 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3692, "s": 3669, "text": " Stone River ELearning" }, { "code": null, "e": 3699, "s": 3692, "text": " Print" }, { "code": null, "e": 3710, "s": 3699, "text": " Add Notes" } ]
An introduction to NLP and 5 tips for raising your game | by Gonzalo Ferreiro Volpi | Towards Data Science
For those working around Data Science, Machine Learning and/or Artificial Intelligence, NLP is probably one of the most exciting fields to work in. NLP stands for Natural Language Processing and it’s about the interactions between computers and human languages. Programming algorithms capable of processing and analyzing large amounts of natural language data. The underlying objective may vary, but the overall goal is to get to conclusions about human behaviour...our intentions when writing something, what we were thinking or feeling when we do it, the category of an item we were writing about, and some other stuff like chatbots, market segmentation of customers, find duplicates and similarities in between elements, virtual assistants (like Siri or Alexa) and much more stuff. Nonetheless, NLP as a subject didn’t appear much time ago, it was just in 1960 when Alan Turing published an article called “Computing Machinery and Intelligence” which proposed what is now called the ‘Turing test’. The paper introduced the question ‘Can machines think?’ and the test proves a machine’s ability to exhibit intelligent behaviour equivalent to, or indistinguishable from, that of a human. Three participants are necessary for running the test, where a player C, the evaluator, is given the task of trying to determine which player — A or B — is a computer and which is a human. The evaluator would then judge natural language conversations between a human and a machine designed to generate human-like responses, knowing that one of the two partners in conversation is a machine. The conversation would be limited to a text-only channel and the results do not depend on the machine’s ability to give correct answers to questions, only how closely its answers resemble those a human would give. If at the end of the test the evaluator cannot reliably tell the machine from the human, the machine is said to have passed the test. Starting from there, in the past years, the field has evolved exponentially, going from hand-coded systems using a set of rules, to a more sophisticated statistical NLP. And in this context, some companies are doing some pretty exciting stuff in the field. For example, if you’re an Android user you’re probably familiar with Swiftkey, a startup using text prediction designed to boost the accuracy, fluency and speed of users’ writing. Swiftkey learns from our writing, predicting favourite words, emojis and even expressions. Another startup, SignAll, converts sign language into text. Helping individuals who are deaf communicate with those who don’t know sign language. And the fact is that nowadays the expansion of some open source libraries using Python, Tensorflow, Keras and others, has made NLP accessible and each day more and more businesses are using it. Some of them hiring other companies specifically specialized in the subject, but some others are hiring Data Scientists and Data Analyst in order to build their own solutions. If any of these is your case, whether you are the company or the data specialist, in the next lines I will introduce some of my learning while working with NLP. Lucky for you, all of them are mistake-based tips! So hopefully, you will be able to avoid them in advance, not as it happened to me :) In NLP usually, after lots and lots and lots (and probably lots more) of data cleaning, the magic starts with something called vectorization. This tool, technique, or however you want to call it, take a bunch of text, usually called documents, and transforms them in vectors according to the words appearing within each document. Take the following example: Example created by the author using images from https://www.oreilly.com In the example above we are using a tool known as Count Vectorizer or Bag of Words. This kind of vectorization usually discards grammar, order, and structure in the text. It is a great option since it keeps track of all words appearing within the documents and their simple way of processing them by just counting it’s easily understandable and gives us a clear picture of the most important words overall. However, it presents two main problems: Data sparsity: when counting all appearances throughout documents, we can easily end with a matrix composed of vectors full of zeros since of course, each document will only contain a small amount of all the possible words. We’ll talk more about this later. The future itself: a Count Vectorizer outputs a fixed-sized matrix with all words (or those of certain frequencies) appearing in our current documents. This could be a problem if we receive further documents in the future and we don’t know the words we might find. Tricky documents: what happens if we have a document in which a specific word appears so many times, that it ends looking as it is the most common word throughout all the documents instead of just a word appearing lots of time in just one document? To solve the first problem and the second problem we could use a Hashing Vectorize, which converts a collection of text documents to a matrix of occurrences calculated with the hashing trick. Each word is mapped to a feature with the use of a hash function that converts it to a number. If we encounter that word again in the text, it will be converted to the same hash, allowing us to count word occurrences without retaining a dictionary in memory. The main drawback of this trick is that it’s not possible to compute the inverse transform, and thus we lose information on what words the important features correspond to. To solve the third problem mentioned above, we could use term frequency-inverse document frequency (tf-idf) vectorizer. A tf-idf score tells us which words are most discriminating between documents. Words that occur a lot in one document but don’t occur in many documents contain a great deal of discriminating power. The inverse document frequency is a measure of how much information the word provides, that is, whether the term is common or rare across all documents. Enhancing terms highly specific of a particular document while suppressing terms that are common to most documents. Sklearn has implementations for all these three types of vectorization: Countvectorizer Hashingvectorizer Tfidfvectorizer Using stop words when doing any kind of vectorization is a key step for getting reliable results. Passing a list of stop words to our algorithm we’re telling to it: ‘please ignore all these words if you find any...I don’t want to have them in my output matrix’. Skelarn does include a default list of stop words for us to use, just by passing the word ‘english’ to the ‘stop_words’ hyperparameter. However, there are several limitations: It only includes basic words like “and”, “the”, “him”, which are presumed to be uninformative in representing the content of a text and which may be removed to avoid them being construed as a signal for prediction. However, if for example, you were processing descriptions of houses scraped from rental agencies websites, you would probably want to remove all words that d not make to the description of the property itself. Words as ‘opportunity’, ‘offer’, ‘amazing’, ‘great’, ‘now’ and stuff like that And what has been for me the greatest drawback being a Spanish speaker and working with machine learning problems in that language: It’s only available in English So whether you want to enrich the default list of words in English to improve your output matrix, or you want to use a list in some other language, you can pass Sklearn’s algorithm a personalized list of stop words by using the hyperparameter ‘stop_words’. By the way, here’s a GitHub repository with an impressive number of lists in several languages. Before jumping into the next point, just have in mind that sometimes you won’t want to use any stop words at all. For example, if you’re dealing with numbers, even the default English list of stop words within Sklearn includes all single numbers from 0 to 9. So it’s important for you to ask yourself whether or not you’re working on an NLP problem that needs stop words. Text normalization is the process of converting slightly different versions of words with essentially equivalent meaning into the same features. In some cases, it might be sensible to consider all possible variants of a possible word, but whether you’re working in English or any other language, sometimes you’ll also want to do some kind of pre-processing to your document in order to represent in the same way words that underly the same meaning. For example, consultant, consulting, consult, consultative and consultants could all be expressed as just ‘consultant’. See the next table for more examples: For doing this, we could use stemming. Stemmers remove morphological affixes from words, leaving only the word stem. Luckily for us, NLTK library for Python contains several robust stemmers. And if you want to incorporate your specific-language stemmer, or other, into your vectorizer algorithm, you can just use the following bunch of code: spanish_stemmer = SpanishStemmer()classStemmedCountVectorizerSP(CountVectorizer):def build_analyzer(self):analyzer = super(StemmedCountVectorizerSP,self).build_analyzer()return lambda doc: ([spanish_stemmer.stem(w) for w in analyzer(doc)]) You can easily change this for using HashingVectorizer or TfidfVectorizer, just by changing the algorithm given to the class. This piece of advice is short and sweet: if you’e working in an NLP project with any data larger than 5–10k thousand rows, avoid using DataFrames. Just vectorizing a big number of documents using Pandas returns a massive matrix that makes handling very slow, but also, lots of times, Natural Language Processing projects involve stuff like measuring distances, what tends to be very slow since it needs to compare elements against each other. And even though I’m myself a heavy user of Pandas’ DataFrames, for this kind of stuff I would recommend using Numpy Arrays or Sparse Matrices. Also. mind that you can always get your sparse matrix to an array just by using the ‘.toarray()’ function and vice-versa, from array to sparse matrix using: from scipy import sparsemy_sparse_matrix = sparse.csr_matrix(my_array) By the way, if your dealing with time issues, remember you can time your code using the following: start = time.time()whatever_you_want_to_timeend = time.time()print(end — start) As said before, one of the biggest problems while working with NLP is the issue of data sparsity...ending with matrices of dozens of thousands of columns full of zeros, that make it impossible for us to apply certain stuff afterwards. Here are a couple of tips of things I have used in the past for dealing with this problem: When using TfidfVectorizer or CountVectorizer using the hyperparameter ‘max_features’. For example, you could print out the words frequencies across documents and then set a certain threshold for them. Imagine you have set a threshold of 50, and your data corpus consists of 100 words. After looking at the words frequencies 20 words occur less than 50 times. Thus, you set max_features=80 and you are good to go. If max_features is set to None, then the whole corpus is considered during the transformation. Otherwise, if you pass, say, 5 to max_features, that would mean creating a feature matrix out of the most 5 frequent words across text documents. Setting up a number of ‘n_features’ in HashingVectorizer. This hyperparameter sets the number of features/columns in the output matrix. Small numbers of features are likely to cause hash collisions, but large numbers will cause larger coefficient dimensions in linear learners. The number is up to you and what you need. Using dimensionality reduction. Techniques as Principal Component Analysis take an output matrix with dozens of thousands of columns into a much smaller set capturing the variance on the original matrix could be a great idea. Just mind analyzing how much this dimensionality reduction affects your final results, to check if it’s actually useful and also to select the number of dimensions to be used. I really really hope all these learnings I have had might help in your NLP project. More stories about NLP will come in the future, but if you enjoy this story don’t forget to check out some of my last articles, like how to divide your data into train and test set assuring representativeness, survivorship bias in Data Science and using a cluster in the cloud for Data Science projects in 4 simple steps. All of them and more available within my Medium profile. And if you want to receive my latest articles directly on your email, just subscribe to my newsletter :) Thanks for reading! — — — — — — — — — — — — And a special mention to the following sources I used throughout the story:
[ { "code": null, "e": 320, "s": 172, "text": "For those working around Data Science, Machine Learning and/or Artificial Intelligence, NLP is probably one of the most exciting fields to work in." }, { "code": null, "e": 533, "s": 320, "text": "NLP stands for Natural Language Processing and it’s about the interactions between computers and human languages. Programming algorithms capable of processing and analyzing large amounts of natural language data." }, { "code": null, "e": 957, "s": 533, "text": "The underlying objective may vary, but the overall goal is to get to conclusions about human behaviour...our intentions when writing something, what we were thinking or feeling when we do it, the category of an item we were writing about, and some other stuff like chatbots, market segmentation of customers, find duplicates and similarities in between elements, virtual assistants (like Siri or Alexa) and much more stuff." }, { "code": null, "e": 1550, "s": 957, "text": "Nonetheless, NLP as a subject didn’t appear much time ago, it was just in 1960 when Alan Turing published an article called “Computing Machinery and Intelligence” which proposed what is now called the ‘Turing test’. The paper introduced the question ‘Can machines think?’ and the test proves a machine’s ability to exhibit intelligent behaviour equivalent to, or indistinguishable from, that of a human. Three participants are necessary for running the test, where a player C, the evaluator, is given the task of trying to determine which player — A or B — is a computer and which is a human." }, { "code": null, "e": 2100, "s": 1550, "text": "The evaluator would then judge natural language conversations between a human and a machine designed to generate human-like responses, knowing that one of the two partners in conversation is a machine. The conversation would be limited to a text-only channel and the results do not depend on the machine’s ability to give correct answers to questions, only how closely its answers resemble those a human would give. If at the end of the test the evaluator cannot reliably tell the machine from the human, the machine is said to have passed the test." }, { "code": null, "e": 2774, "s": 2100, "text": "Starting from there, in the past years, the field has evolved exponentially, going from hand-coded systems using a set of rules, to a more sophisticated statistical NLP. And in this context, some companies are doing some pretty exciting stuff in the field. For example, if you’re an Android user you’re probably familiar with Swiftkey, a startup using text prediction designed to boost the accuracy, fluency and speed of users’ writing. Swiftkey learns from our writing, predicting favourite words, emojis and even expressions. Another startup, SignAll, converts sign language into text. Helping individuals who are deaf communicate with those who don’t know sign language." }, { "code": null, "e": 3144, "s": 2774, "text": "And the fact is that nowadays the expansion of some open source libraries using Python, Tensorflow, Keras and others, has made NLP accessible and each day more and more businesses are using it. Some of them hiring other companies specifically specialized in the subject, but some others are hiring Data Scientists and Data Analyst in order to build their own solutions." }, { "code": null, "e": 3441, "s": 3144, "text": "If any of these is your case, whether you are the company or the data specialist, in the next lines I will introduce some of my learning while working with NLP. Lucky for you, all of them are mistake-based tips! So hopefully, you will be able to avoid them in advance, not as it happened to me :)" }, { "code": null, "e": 3799, "s": 3441, "text": "In NLP usually, after lots and lots and lots (and probably lots more) of data cleaning, the magic starts with something called vectorization. This tool, technique, or however you want to call it, take a bunch of text, usually called documents, and transforms them in vectors according to the words appearing within each document. Take the following example:" }, { "code": null, "e": 3871, "s": 3799, "text": "Example created by the author using images from https://www.oreilly.com" }, { "code": null, "e": 4318, "s": 3871, "text": "In the example above we are using a tool known as Count Vectorizer or Bag of Words. This kind of vectorization usually discards grammar, order, and structure in the text. It is a great option since it keeps track of all words appearing within the documents and their simple way of processing them by just counting it’s easily understandable and gives us a clear picture of the most important words overall. However, it presents two main problems:" }, { "code": null, "e": 4576, "s": 4318, "text": "Data sparsity: when counting all appearances throughout documents, we can easily end with a matrix composed of vectors full of zeros since of course, each document will only contain a small amount of all the possible words. We’ll talk more about this later." }, { "code": null, "e": 4841, "s": 4576, "text": "The future itself: a Count Vectorizer outputs a fixed-sized matrix with all words (or those of certain frequencies) appearing in our current documents. This could be a problem if we receive further documents in the future and we don’t know the words we might find." }, { "code": null, "e": 5090, "s": 4841, "text": "Tricky documents: what happens if we have a document in which a specific word appears so many times, that it ends looking as it is the most common word throughout all the documents instead of just a word appearing lots of time in just one document?" }, { "code": null, "e": 5714, "s": 5090, "text": "To solve the first problem and the second problem we could use a Hashing Vectorize, which converts a collection of text documents to a matrix of occurrences calculated with the hashing trick. Each word is mapped to a feature with the use of a hash function that converts it to a number. If we encounter that word again in the text, it will be converted to the same hash, allowing us to count word occurrences without retaining a dictionary in memory. The main drawback of this trick is that it’s not possible to compute the inverse transform, and thus we lose information on what words the important features correspond to." }, { "code": null, "e": 6301, "s": 5714, "text": "To solve the third problem mentioned above, we could use term frequency-inverse document frequency (tf-idf) vectorizer. A tf-idf score tells us which words are most discriminating between documents. Words that occur a lot in one document but don’t occur in many documents contain a great deal of discriminating power. The inverse document frequency is a measure of how much information the word provides, that is, whether the term is common or rare across all documents. Enhancing terms highly specific of a particular document while suppressing terms that are common to most documents." }, { "code": null, "e": 6373, "s": 6301, "text": "Sklearn has implementations for all these three types of vectorization:" }, { "code": null, "e": 6389, "s": 6373, "text": "Countvectorizer" }, { "code": null, "e": 6407, "s": 6389, "text": "Hashingvectorizer" }, { "code": null, "e": 6423, "s": 6407, "text": "Tfidfvectorizer" }, { "code": null, "e": 6861, "s": 6423, "text": "Using stop words when doing any kind of vectorization is a key step for getting reliable results. Passing a list of stop words to our algorithm we’re telling to it: ‘please ignore all these words if you find any...I don’t want to have them in my output matrix’. Skelarn does include a default list of stop words for us to use, just by passing the word ‘english’ to the ‘stop_words’ hyperparameter. However, there are several limitations:" }, { "code": null, "e": 7365, "s": 6861, "text": "It only includes basic words like “and”, “the”, “him”, which are presumed to be uninformative in representing the content of a text and which may be removed to avoid them being construed as a signal for prediction. However, if for example, you were processing descriptions of houses scraped from rental agencies websites, you would probably want to remove all words that d not make to the description of the property itself. Words as ‘opportunity’, ‘offer’, ‘amazing’, ‘great’, ‘now’ and stuff like that" }, { "code": null, "e": 7528, "s": 7365, "text": "And what has been for me the greatest drawback being a Spanish speaker and working with machine learning problems in that language: It’s only available in English" }, { "code": null, "e": 7881, "s": 7528, "text": "So whether you want to enrich the default list of words in English to improve your output matrix, or you want to use a list in some other language, you can pass Sklearn’s algorithm a personalized list of stop words by using the hyperparameter ‘stop_words’. By the way, here’s a GitHub repository with an impressive number of lists in several languages." }, { "code": null, "e": 8253, "s": 7881, "text": "Before jumping into the next point, just have in mind that sometimes you won’t want to use any stop words at all. For example, if you’re dealing with numbers, even the default English list of stop words within Sklearn includes all single numbers from 0 to 9. So it’s important for you to ask yourself whether or not you’re working on an NLP problem that needs stop words." }, { "code": null, "e": 8860, "s": 8253, "text": "Text normalization is the process of converting slightly different versions of words with essentially equivalent meaning into the same features. In some cases, it might be sensible to consider all possible variants of a possible word, but whether you’re working in English or any other language, sometimes you’ll also want to do some kind of pre-processing to your document in order to represent in the same way words that underly the same meaning. For example, consultant, consulting, consult, consultative and consultants could all be expressed as just ‘consultant’. See the next table for more examples:" }, { "code": null, "e": 9202, "s": 8860, "text": "For doing this, we could use stemming. Stemmers remove morphological affixes from words, leaving only the word stem. Luckily for us, NLTK library for Python contains several robust stemmers. And if you want to incorporate your specific-language stemmer, or other, into your vectorizer algorithm, you can just use the following bunch of code:" }, { "code": null, "e": 9442, "s": 9202, "text": "spanish_stemmer = SpanishStemmer()classStemmedCountVectorizerSP(CountVectorizer):def build_analyzer(self):analyzer = super(StemmedCountVectorizerSP,self).build_analyzer()return lambda doc: ([spanish_stemmer.stem(w) for w in analyzer(doc)])" }, { "code": null, "e": 9568, "s": 9442, "text": "You can easily change this for using HashingVectorizer or TfidfVectorizer, just by changing the algorithm given to the class." }, { "code": null, "e": 10154, "s": 9568, "text": "This piece of advice is short and sweet: if you’e working in an NLP project with any data larger than 5–10k thousand rows, avoid using DataFrames. Just vectorizing a big number of documents using Pandas returns a massive matrix that makes handling very slow, but also, lots of times, Natural Language Processing projects involve stuff like measuring distances, what tends to be very slow since it needs to compare elements against each other. And even though I’m myself a heavy user of Pandas’ DataFrames, for this kind of stuff I would recommend using Numpy Arrays or Sparse Matrices." }, { "code": null, "e": 10311, "s": 10154, "text": "Also. mind that you can always get your sparse matrix to an array just by using the ‘.toarray()’ function and vice-versa, from array to sparse matrix using:" }, { "code": null, "e": 10382, "s": 10311, "text": "from scipy import sparsemy_sparse_matrix = sparse.csr_matrix(my_array)" }, { "code": null, "e": 10481, "s": 10382, "text": "By the way, if your dealing with time issues, remember you can time your code using the following:" }, { "code": null, "e": 10561, "s": 10481, "text": "start = time.time()whatever_you_want_to_timeend = time.time()print(end — start)" }, { "code": null, "e": 10887, "s": 10561, "text": "As said before, one of the biggest problems while working with NLP is the issue of data sparsity...ending with matrices of dozens of thousands of columns full of zeros, that make it impossible for us to apply certain stuff afterwards. Here are a couple of tips of things I have used in the past for dealing with this problem:" }, { "code": null, "e": 11542, "s": 10887, "text": "When using TfidfVectorizer or CountVectorizer using the hyperparameter ‘max_features’. For example, you could print out the words frequencies across documents and then set a certain threshold for them. Imagine you have set a threshold of 50, and your data corpus consists of 100 words. After looking at the words frequencies 20 words occur less than 50 times. Thus, you set max_features=80 and you are good to go. If max_features is set to None, then the whole corpus is considered during the transformation. Otherwise, if you pass, say, 5 to max_features, that would mean creating a feature matrix out of the most 5 frequent words across text documents." }, { "code": null, "e": 11863, "s": 11542, "text": "Setting up a number of ‘n_features’ in HashingVectorizer. This hyperparameter sets the number of features/columns in the output matrix. Small numbers of features are likely to cause hash collisions, but large numbers will cause larger coefficient dimensions in linear learners. The number is up to you and what you need." }, { "code": null, "e": 12265, "s": 11863, "text": "Using dimensionality reduction. Techniques as Principal Component Analysis take an output matrix with dozens of thousands of columns into a much smaller set capturing the variance on the original matrix could be a great idea. Just mind analyzing how much this dimensionality reduction affects your final results, to check if it’s actually useful and also to select the number of dimensions to be used." }, { "code": null, "e": 12728, "s": 12265, "text": "I really really hope all these learnings I have had might help in your NLP project. More stories about NLP will come in the future, but if you enjoy this story don’t forget to check out some of my last articles, like how to divide your data into train and test set assuring representativeness, survivorship bias in Data Science and using a cluster in the cloud for Data Science projects in 4 simple steps. All of them and more available within my Medium profile." }, { "code": null, "e": 12833, "s": 12728, "text": "And if you want to receive my latest articles directly on your email, just subscribe to my newsletter :)" }, { "code": null, "e": 12853, "s": 12833, "text": "Thanks for reading!" }, { "code": null, "e": 12877, "s": 12853, "text": "— — — — — — — — — — — —" } ]
Android Interview Questions
Dear readers, these Android Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of Android. As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer − Android is a stack of software for mobile devices which includes an Operating System, middleware and some key applications. The application executes within its own process and its own instance of Dalvik Virtual Machine. Android application architecture has the following components.They are as follows − Services − It will perform background functionalities Intent − It will perform the inter connection between activities and the data passing mechanism Resource Externalization − strings and graphics Notification − light,sound,icon,notification,dialog box,and toast Content Providers − It will share the data between applications Activity performs actions on the screen.If you want to do any operations, we can do with activity The Android packaging key is compressed with classes,UI's, supportive assets and manifest.All files are compressed to a single file is called APK. It is connected to either the external world of application or internal world of application ,Such as, opening a pdf is an intent and connect to the web browser.etc. Android Explicit intent specifies the component to be invoked from activity. In other words, we can call another activity in android by explicit intent. Implicit Intent doesn't specifiy the component. In such case, intent provides information of available components provided by the system that is to be invoked. Every application must have an AndroidManifest.xml file (with precisely that name) in its root directory. The manifest file presents essential information about your app to the Android system, information the system must have before it can run any of the app's code. Android applications has written using the java(Android SDK) and C/C++(Android NDK). ADT stands for Android development tool,This is useful to develop the applications and test the applications. Android SDK collaborated with Android Emulator,DDMS(Dalvik Debug Monitoring Services),AAPT(Android Asset Packaging tool) and ADB(Android debug bridge) View group is a collection of views and other child views, it is an invisible part and the base class for layouts. The Service is like as an activity to do background functionalities without UI interaction. A content provider component supplies data from one application to others on request. Such requests are handled by the methods of the ContentResolver class. A content provider can use different ways to store its data and the data can be stored in a database, in files, or even over a network. Toast Notification − It will show a pop up message on the surface of the window Status Bar Notification − It will show notifications on status bar Dialogue Notification − It is an activity related notification. The container holds objects,widgets,labels,fields,icons,buttons.etc. It is acts as bridge between emulator and IDE, it executes remote shell commands to run applications on an emulator ANR stands for application is not responding, basically it is a dialog box that appears when the application is not responding. The Adapter is used to create child views to represent the parent view items. Shared preferences are the simplest mechanism to store the data in XML documents. Linux Kernel Libraries Android Framework Android applications. Intent filters are filter out the intents. In The Layout folder, layouts are placed as XML files We can change bitmap images in nine sections as four corners,four edges and an axis AlertDialog, ProgressDialog,DatePickerDialog, and TimePickerDialog InflateException,Surface.OutOfResourceException,SurfaceHolder.BadSurfaceTypeException,and WindowManager.BadTokenException Positive, Neutral, Negative. Shared Preferences,Internal Storage,External Storage,SQLite Databases and Network Connection Sticky Intent is also a type of intent which allows the communication between a function and a service for example,sendStickyBroadcast() is perform the operations after completion of intent also. Android uses Google translator to translate data from one language into another language and placed as a string while development WebView is UI component that can display either remote web-pages or static HTML Android uses DVM (Dalvik Virtual Machine ) rather using JVM(Java Virtual Machine), if we want, we can get access to .jar file as a library. Android provides a Unique ID to all applications is called as Linux ID,this ID is used to track each application. It's not truly recommended to change application name after it's deployment, if we change, it will impact on all other internal components. JSON,XML bitmap.etc are application resources.You can injected these files to build process and can load them from the code. Using with intent, we can launch an activity. Intent intent = new Intent(this, MyTestActivity.class); startActivity(intent); Using with Bundle, we can pass the data to sub activities. Bundle bun = new Bundle(); bun.putString("EMAIL", "contact@tutorials.com"); A class which can create only an object, that object can be share able to all other classes. Fragment is a piece of activity, if you want to do turn your application 360 degrees, you can do this by fragment. Sleep mode mean CPU will be sleeping and it doesn't accept any commands from android device except Radio interface layer and alarm. Android is customized Linux 3.6 kernel. Use a dynamic broadcast receiver in the activity, and send a broadcast from the service. Once the dynamic receiver is triggered update UI from that receiver. AndroidManifest.xml build.xml bin/ src/ res/ assets/ App Widgets are miniature application views that can embedded in other applications (such as the Home screen) and receive periodic updates. These views has referred to as Widgets in the user interface, and you can publish one with an App Widget provider. Using with findViewById we can find view element. A compiled visual resource that can used as a backgrounds,banners, icons,splash screen etc. FLAG_ACTIVITY_NEW_TASK FLAG_ACTIVITY_CLEAR_TOP. Further you can go through your past assignments you have done with the subject and make sure you are able to speak confidently on them. If you are fresher then interviewer does not expect you will answer very complex questions, rather you have to make your basics concepts very strong. Second it really doesn't matter much if you could not answer few questions but it matters that whatever you answered, you must have answered with confidence. So just feel confident during your interview. We at tutorialspoint wish you best luck to have a good interviewer and all the very best for your future endeavor. Cheers :-) 46 Lectures 7.5 hours Aditya Dua 32 Lectures 3.5 hours Sharad Kumar 9 Lectures 1 hours Abhilash Nelson 14 Lectures 1.5 hours Abhilash Nelson 15 Lectures 1.5 hours Abhilash Nelson 10 Lectures 1 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 4046, "s": 3607, "text": "Dear readers, these Android Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of Android. As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer −" }, { "code": null, "e": 4267, "s": 4046, "text": "Android is a stack of software for mobile devices which includes an Operating System, \nmiddleware and some key applications. The application executes within its own process and its own instance of Dalvik Virtual Machine." }, { "code": null, "e": 4351, "s": 4267, "text": "Android application architecture has the following components.They are as follows −" }, { "code": null, "e": 4405, "s": 4351, "text": "Services − It will perform background functionalities" }, { "code": null, "e": 4501, "s": 4405, "text": "Intent − It will perform the inter connection between activities and the data passing mechanism" }, { "code": null, "e": 4549, "s": 4501, "text": "Resource Externalization − strings and graphics" }, { "code": null, "e": 4615, "s": 4549, "text": "Notification − light,sound,icon,notification,dialog box,and toast" }, { "code": null, "e": 4679, "s": 4615, "text": "Content Providers − It will share the data between applications" }, { "code": null, "e": 4777, "s": 4679, "text": "Activity performs actions on the screen.If you want to do any operations, we can do with activity" }, { "code": null, "e": 4924, "s": 4777, "text": "The Android packaging key is compressed with classes,UI's, supportive assets and manifest.All files are compressed to a single file is called APK." }, { "code": null, "e": 5090, "s": 4924, "text": "It is connected to either the external world of application or internal world of application ,Such as, opening a pdf is an intent and connect to the web browser.etc." }, { "code": null, "e": 5243, "s": 5090, "text": "Android Explicit intent specifies the component to be invoked from activity. In other words, we can call another activity in android by explicit intent." }, { "code": null, "e": 5403, "s": 5243, "text": "Implicit Intent doesn't specifiy the component. In such case, intent provides information of available components provided by the system that is to be invoked." }, { "code": null, "e": 5670, "s": 5403, "text": "Every application must have an AndroidManifest.xml file (with precisely that name) in its root directory. The manifest file presents essential information about your app to the Android system, information the system must have before it can run any of the app's code." }, { "code": null, "e": 5755, "s": 5670, "text": "Android applications has written using the java(Android SDK) and C/C++(Android NDK)." }, { "code": null, "e": 5865, "s": 5755, "text": "ADT stands for Android development tool,This is useful to develop the applications and test the applications." }, { "code": null, "e": 6016, "s": 5865, "text": "Android SDK collaborated with Android Emulator,DDMS(Dalvik Debug Monitoring Services),AAPT(Android Asset Packaging tool) and ADB(Android debug bridge)" }, { "code": null, "e": 6131, "s": 6016, "text": "View group is a collection of views and other child views, it is an invisible part and the base class for layouts." }, { "code": null, "e": 6223, "s": 6131, "text": "The Service is like as an activity to do background functionalities without UI interaction." }, { "code": null, "e": 6516, "s": 6223, "text": "A content provider component supplies data from one application to others on request. Such requests are handled by the methods of the ContentResolver class. A content provider can use different ways to store its data and the data can be stored in a database, in files, or even over a network." }, { "code": null, "e": 6597, "s": 6516, "text": "Toast Notification − It will show a pop up message on the surface of the window " }, { "code": null, "e": 6664, "s": 6597, "text": "Status Bar Notification − It will show notifications on status bar" }, { "code": null, "e": 6728, "s": 6664, "text": "Dialogue Notification − It is an activity related notification." }, { "code": null, "e": 6797, "s": 6728, "text": "The container holds objects,widgets,labels,fields,icons,buttons.etc." }, { "code": null, "e": 6913, "s": 6797, "text": "It is acts as bridge between emulator and IDE, it executes remote shell commands to run applications on an emulator" }, { "code": null, "e": 7041, "s": 6913, "text": "ANR stands for application is not responding, basically it is a dialog box that appears when the application is not responding." }, { "code": null, "e": 7119, "s": 7041, "text": "The Adapter is used to create child views to represent the parent view items." }, { "code": null, "e": 7201, "s": 7119, "text": "Shared preferences are the simplest mechanism to store the data in XML documents." }, { "code": null, "e": 7214, "s": 7201, "text": "Linux Kernel" }, { "code": null, "e": 7224, "s": 7214, "text": "Libraries" }, { "code": null, "e": 7242, "s": 7224, "text": "Android Framework" }, { "code": null, "e": 7264, "s": 7242, "text": "Android applications." }, { "code": null, "e": 7307, "s": 7264, "text": "Intent filters are filter out the intents." }, { "code": null, "e": 7361, "s": 7307, "text": "In The Layout folder, layouts are placed as XML files" }, { "code": null, "e": 7445, "s": 7361, "text": "We can change bitmap images in nine sections as four corners,four edges and an axis" }, { "code": null, "e": 7512, "s": 7445, "text": "AlertDialog, ProgressDialog,DatePickerDialog, and TimePickerDialog" }, { "code": null, "e": 7634, "s": 7512, "text": "InflateException,Surface.OutOfResourceException,SurfaceHolder.BadSurfaceTypeException,and WindowManager.BadTokenException" }, { "code": null, "e": 7663, "s": 7634, "text": "Positive, Neutral, Negative." }, { "code": null, "e": 7756, "s": 7663, "text": "Shared Preferences,Internal Storage,External Storage,SQLite Databases and Network Connection" }, { "code": null, "e": 7952, "s": 7756, "text": "Sticky Intent is also a type of intent which allows the communication between a function and a service for example,sendStickyBroadcast() is perform the operations after completion of intent also." }, { "code": null, "e": 8082, "s": 7952, "text": "Android uses Google translator to translate data from one language into another language and placed as a string while development" }, { "code": null, "e": 8162, "s": 8082, "text": "WebView is UI component that can display either remote web-pages or static HTML" }, { "code": null, "e": 8302, "s": 8162, "text": "Android uses DVM (Dalvik Virtual Machine ) rather using JVM(Java Virtual Machine), if we want, we can get access to .jar file as a library." }, { "code": null, "e": 8416, "s": 8302, "text": "Android provides a Unique ID to all applications is called as Linux ID,this ID is used to track each application." }, { "code": null, "e": 8556, "s": 8416, "text": "It's not truly recommended to change application name after it's deployment, if we change, it will impact on all other internal components." }, { "code": null, "e": 8681, "s": 8556, "text": "JSON,XML bitmap.etc are application resources.You can injected these files to build process and can load them from the code." }, { "code": null, "e": 8727, "s": 8681, "text": "Using with intent, we can launch an activity." }, { "code": null, "e": 8815, "s": 8727, "text": "Intent intent = new Intent(this, MyTestActivity.class);\n\n startActivity(intent);" }, { "code": null, "e": 8875, "s": 8815, "text": "Using with Bundle, we can pass the data to sub activities. " }, { "code": null, "e": 8960, "s": 8875, "text": "Bundle bun = new Bundle();\n\n bun.putString(\"EMAIL\", \"contact@tutorials.com\");" }, { "code": null, "e": 9053, "s": 8960, "text": "A class which can create only an object, that object can be share able to all other classes." }, { "code": null, "e": 9168, "s": 9053, "text": "Fragment is a piece of activity, if you want to do turn your application 360 degrees, you can do this by fragment." }, { "code": null, "e": 9300, "s": 9168, "text": "Sleep mode mean CPU will be sleeping and it doesn't accept any commands from android device except Radio interface layer and alarm." }, { "code": null, "e": 9341, "s": 9300, "text": "Android is customized Linux 3.6 kernel." }, { "code": null, "e": 9499, "s": 9341, "text": "Use a dynamic broadcast receiver in the activity, and send a broadcast from the service. Once the dynamic receiver is triggered update UI from that receiver." }, { "code": null, "e": 9519, "s": 9499, "text": "AndroidManifest.xml" }, { "code": null, "e": 9529, "s": 9519, "text": "build.xml" }, { "code": null, "e": 9534, "s": 9529, "text": "bin/" }, { "code": null, "e": 9539, "s": 9534, "text": "src/" }, { "code": null, "e": 9544, "s": 9539, "text": "res/" }, { "code": null, "e": 9552, "s": 9544, "text": "assets/" }, { "code": null, "e": 9808, "s": 9552, "text": "App Widgets are miniature application views that can embedded in other applications (such as the Home screen) and receive periodic updates. These views has referred to as Widgets in the user interface, and you can publish one with an App Widget provider." }, { "code": null, "e": 9858, "s": 9808, "text": "Using with findViewById we can find view element." }, { "code": null, "e": 9951, "s": 9858, "text": "A compiled visual resource that can used as a backgrounds,banners, icons,splash screen etc." }, { "code": null, "e": 9974, "s": 9951, "text": "FLAG_ACTIVITY_NEW_TASK" }, { "code": null, "e": 9999, "s": 9974, "text": "FLAG_ACTIVITY_CLEAR_TOP." }, { "code": null, "e": 10286, "s": 9999, "text": "Further you can go through your past assignments you have done with the subject and make sure you are able to speak confidently on them. If you are fresher then interviewer does not expect you will answer very complex questions, rather you have to make your basics concepts very strong." }, { "code": null, "e": 10616, "s": 10286, "text": "Second it really doesn't matter much if you could not answer few questions but it matters that whatever you answered, you must have answered with confidence. So just feel confident during your interview. We at tutorialspoint wish you best luck to have a good interviewer and all the very best for your future endeavor. Cheers :-)" }, { "code": null, "e": 10651, "s": 10616, "text": "\n 46 Lectures \n 7.5 hours \n" }, { "code": null, "e": 10663, "s": 10651, "text": " Aditya Dua" }, { "code": null, "e": 10698, "s": 10663, "text": "\n 32 Lectures \n 3.5 hours \n" }, { "code": null, "e": 10712, "s": 10698, "text": " Sharad Kumar" }, { "code": null, "e": 10744, "s": 10712, "text": "\n 9 Lectures \n 1 hours \n" }, { "code": null, "e": 10761, "s": 10744, "text": " Abhilash Nelson" }, { "code": null, "e": 10796, "s": 10761, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 10813, "s": 10796, "text": " Abhilash Nelson" }, { "code": null, "e": 10848, "s": 10813, "text": "\n 15 Lectures \n 1.5 hours \n" }, { "code": null, "e": 10865, "s": 10848, "text": " Abhilash Nelson" }, { "code": null, "e": 10898, "s": 10865, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 10915, "s": 10898, "text": " Abhilash Nelson" }, { "code": null, "e": 10922, "s": 10915, "text": " Print" }, { "code": null, "e": 10933, "s": 10922, "text": " Add Notes" } ]
Align flex items at the end of the container with CSS
Use the justify-content property with value flex-end to align the flex-items at the end. You can try to run the following code to implement the flex-end value − Live Demo <!DOCTYPE html> <html> <head> <style> .mycontainer { display: flex; background-color: red; justify-content: flex-end; } .mycontainer > div { background-color: #E6B0AA; text-align: center; line-height: 60px; font-size: 30px; width: 100px; margin: 5px; } </style> </head> <body> <h1>Score</h1> <div class = "mycontainer"> <div>20</div> <div>35</div> <div>88</div> <div>62</div> </div> </body> </html>
[ { "code": null, "e": 1151, "s": 1062, "text": "Use the justify-content property with value flex-end to align the flex-items at the end." }, { "code": null, "e": 1223, "s": 1151, "text": "You can try to run the following code to implement the flex-end value −" }, { "code": null, "e": 1233, "s": 1223, "text": "Live Demo" }, { "code": null, "e": 1854, "s": 1233, "text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n .mycontainer {\n display: flex;\n background-color: red;\n justify-content: flex-end;\n }\n .mycontainer > div {\n background-color: #E6B0AA;\n text-align: center;\n line-height: 60px;\n font-size: 30px;\n width: 100px;\n margin: 5px;\n }\n </style>\n </head>\n <body>\n <h1>Score</h1>\n <div class = \"mycontainer\">\n <div>20</div>\n <div>35</div>\n <div>88</div>\n <div>62</div>\n </div>\n </body>\n</html>" } ]