title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
CAN Bus with Arduino
Communication protocols like UART (Serial), I2C and SPI are very popular because several peripherals can be interfaced with Arduino using these protocols. CAN (Controller Area Network) is another such protocol, which isn't very widely popular in general, but find several applications in the automotive domain. While going into the details of CAN bus is beyond the scope of this article, you can find the relevant information here. However, here are a few things you should know βˆ’ CAN is a message-based protocol (i.e., the message and content are more important than the sender). A message transmitted by one device is received by all devices,including the transmitting device itself. CAN is a message-based protocol (i.e., the message and content are more important than the sender). A message transmitted by one device is received by all devices,including the transmitting device itself. If multiple devices are transmitting at the same time, the device with the highest priority continues transmission, while others back off. Note that since CAN is a message based protocol, IDs are assigned to messages and not the devices. If multiple devices are transmitting at the same time, the device with the highest priority continues transmission, while others back off. Note that since CAN is a message based protocol, IDs are assigned to messages and not the devices. It uses two lines for data transmission CAN_H and CAN_L. The differential voltage between these lines determines the signal. A positive difference above a threshold indicates a 1, while a negative voltage indicates a 0 It uses two lines for data transmission CAN_H and CAN_L. The differential voltage between these lines determines the signal. A positive difference above a threshold indicates a 1, while a negative voltage indicates a 0 The devices in the network are called nodes. CAN is very flexible in the sense that newer nodes can be added to the network, and nodes can be removed as well. All the nodes in the network only share two lines. The devices in the network are called nodes. CAN is very flexible in the sense that newer nodes can be added to the network, and nodes can be removed as well. All the nodes in the network only share two lines. Data transmission happens in frames. Each data frame contains an 11 (base frame format) or 29 (extended frame format) identifier bits and 0 to 8 data bytes. Data transmission happens in frames. Each data frame contains an 11 (base frame format) or 29 (extended frame format) identifier bits and 0 to 8 data bytes. Now, Arduino Uno doesn't support CAN directly like it supports UART, SPI and I2C. Therefore, we will use external module, MCP2515 with TJA1050 transceiver, that interfaces with Arduino via SPI, and the transmits the message using CAN. The Circuit Diagram for one node (transmitter) is shown below. As you can see above, the Vcc line of the module is connected to 5V of Arduino, GND to GND,CS to pin 10, SO to pin 12 (MISO), SI to pin 11 (MOSI) and SCK to pin 13 (SCK). On the receiving side, the connections are similar, except that the INT pin of the module is connected to pin 2 of Arduino. The two (transmitter and receiver) are be joined together by CAN_H and CAN_L lines (CAN_H to CAN_H and CAN_L to CAN_L). We will use this library from Seeed Studio. This library won't be found in the Library Manager of Arduino. The procedure for downloading a third-party library is given here βˆ’ https://www.tutorialspoint.com/using-a-third-party-library-in-arduino Once you have the library installed, you can find the send and receive_interrupt examples in File -> Examples -> CAN_BUS Shield. We will be using slightly simplified versions of these examples. The code for SEND is given below βˆ’ #include <SPI.h> #include "mcp2515_can.h" onst int SPI_CS_PIN = 10; mcp2515_can CAN(SPI_CS_PIN); // Set CS pin void setup() { Serial.begin(115200); while(!Serial){}; // init can bus : baudrate = 500k while (CAN_OK != CAN.begin(CAN_500KBPS)) { Serial.println("CAN init fail, retry..."); delay(100); } Serial.println("CAN init ok!"); } unsigned char stmp[8] = {0, 0, 0, 0, 0, 0, 0, 0}; void loop() { // send data: id = 0x00, standrad frame, data len = 8, stmp: data buf stmp[7] = stmp[7] + 1; if (stmp[7] == 100) { stmp[7] = 0; stmp[6] = stmp[6] + 1; if (stmp[6] == 100) { stmp[6] = 0; stmp[5] = stmp[5] + 1; } } CAN.sendMsgBuf(0x00, 0, 8, stmp); delay(100); // send data per 100ms Serial.println("CAN BUS sendMsgBuf ok!"); } Much of the code is self-explanatory. We will go through the implementation in brief. We initialize CAN using the Chip Select pin (Pin 10 in our case). mcp2515_can CAN(SPI_CS_PIN); // Set CS pin We set the baud rate to 500 kbps in the Setup and check if CAN began properly. CAN.begin(CAN_500KBPS)) We are transmitting 8 bytes in each frame to the received. The bytes are all 0 to begin with.Within loop, we keep incrementing the last byte, till it reaches 100, then add one to the second last byte and again keep incrementing the last byte till it reaches 100, and so on. We increment the third-last byte if the second-last byte reaches 100. This gives us several iterations to go on. The important function is βˆ’ CAN.sendMsgBuf(0x00, 0, 8, stmp); The first argument is the ID of the message (0x00), the second argument represents whether we are using the base format or the extended format (0 for base, and 1 for extended), the third argument is the length of the data (8), and the fourth is the data buffer. This will keep sending 8-byte data frames to the receiver. The code for RECEIVE is shown below βˆ’ #include <SPI.h> #include "mcp2515_can.h" const int SPI_CS_PIN = 10; const int CAN_INT_PIN = 2; mcp2515_can CAN(SPI_CS_PIN); // Set CS pin unsigned char flagRecv = 0; unsigned char len = 0; unsigned char buf[8]; char str[20]; void setup() { Serial.begin(115200); while (!Serial) { ; // wait for serial port to connect. Needed for native USB port only } // start interrupt attachInterrupt(digitalPinToInterrupt(CAN_INT_PIN), MCP2515_ISR, FALLING); // init can bus : baudrate = 500k while (CAN_OK != CAN.begin(CAN_500KBPS)) { Serial.println("CAN init fail, retry..."); delay(100); } Serial.println("CAN init ok!"); } void MCP2515_ISR() { flagRecv = 1; } void loop() { if (flagRecv) { // check if get data flagRecv = 0; // clear flag Serial.println("into loop"); // iterate over all pending messages // If either the bus is saturated or the MCU is busy, // both RX buffers may be in use and reading a single // message does not clear the IRQ conditon. while (CAN_MSGAVAIL == CAN.checkReceive()) { // read data, len: data length, buf: data buf Serial.println("checkReceive"); CAN.readMsgBuf(&len, buf); // print the data for (int i = 0; i < len; i++) { Serial.print(buf[i]); Serial.print("\t"); } Serial.println(); } } } As you can see the initial variable declarations and the setup is similar to SEND. The only difference is that an interrupt is attached to digital pin 2. Remember that the INT pin of the module goes LOW whenever a message is received. Therefore, a FALLING EDGE interrupt is attached to pin 2, which is connected to the INT pin of the module. // start interrupt attachInterrupt(digitalPinToInterrupt(CAN_INT_PIN), MCP2515_ISR, FALLING); Within the MCP2515_ISR function, we simply set the flagRecv to 1, which is checked inside the loop. When the flagRecv value is 1, the available data in the CAN buffer is checked (using CAN.checkReceive()) and read and printed on the Serial Monitor. The function to read the data is βˆ’ CAN.readMsgBuf(&len, buf); The first argument indicates the length of data available, and the second argument is the buffer to store the incoming data. I hope you enjoyed this article. You are encouraged to go through the other examples that come in with this library.
[ { "code": null, "e": 1373, "s": 1062, "text": "Communication protocols like UART (Serial), I2C and SPI are very popular because several peripherals can be interfaced with Arduino using these protocols. CAN (Controller Area Network) is another such protocol, which isn't very widely popular in general, but find several applications in the automotive domain." }, { "code": null, "e": 1543, "s": 1373, "text": "While going into the details of CAN bus is beyond the scope of this article, you can find the relevant information here. However, here are a few things you should know βˆ’" }, { "code": null, "e": 1748, "s": 1543, "text": "CAN is a message-based protocol (i.e., the message and content are more important than the sender). A message transmitted by one device is received by all devices,including the transmitting device itself." }, { "code": null, "e": 1953, "s": 1748, "text": "CAN is a message-based protocol (i.e., the message and content are more important than the sender). A message transmitted by one device is received by all devices,including the transmitting device itself." }, { "code": null, "e": 2191, "s": 1953, "text": "If multiple devices are transmitting at the same time, the device with the highest priority continues transmission, while others back off. Note that since CAN is a message based protocol, IDs are assigned to messages and not the devices." }, { "code": null, "e": 2429, "s": 2191, "text": "If multiple devices are transmitting at the same time, the device with the highest priority continues transmission, while others back off. Note that since CAN is a message based protocol, IDs are assigned to messages and not the devices." }, { "code": null, "e": 2648, "s": 2429, "text": "It uses two lines for data transmission CAN_H and CAN_L. The differential voltage between these lines determines the signal. A positive difference above a threshold indicates a 1, while a negative voltage indicates a 0" }, { "code": null, "e": 2867, "s": 2648, "text": "It uses two lines for data transmission CAN_H and CAN_L. The differential voltage between these lines determines the signal. A positive difference above a threshold indicates a 1, while a negative voltage indicates a 0" }, { "code": null, "e": 3077, "s": 2867, "text": "The devices in the network are called nodes. CAN is very flexible in the sense that newer nodes can be added to the network, and nodes can be removed as well. All the nodes in the network only share two lines." }, { "code": null, "e": 3287, "s": 3077, "text": "The devices in the network are called nodes. CAN is very flexible in the sense that newer nodes can be added to the network, and nodes can be removed as well. All the nodes in the network only share two lines." }, { "code": null, "e": 3444, "s": 3287, "text": "Data transmission happens in frames. Each data frame contains an 11 (base frame format) or 29 (extended frame format) identifier bits and 0 to 8 data bytes." }, { "code": null, "e": 3601, "s": 3444, "text": "Data transmission happens in frames. Each data frame contains an 11 (base frame format) or 29 (extended frame format) identifier bits and 0 to 8 data bytes." }, { "code": null, "e": 3836, "s": 3601, "text": "Now, Arduino Uno doesn't support CAN directly like it supports UART, SPI and I2C. Therefore, we will use external module, MCP2515 with TJA1050 transceiver, that interfaces with Arduino via SPI, and the transmits the message using CAN." }, { "code": null, "e": 3899, "s": 3836, "text": "The Circuit Diagram for one node (transmitter) is shown below." }, { "code": null, "e": 4070, "s": 3899, "text": "As you can see above, the Vcc line of the module is connected to 5V of Arduino, GND to GND,CS to pin 10, SO to pin 12 (MISO), SI to pin 11 (MOSI) and SCK to pin 13 (SCK)." }, { "code": null, "e": 4194, "s": 4070, "text": "On the receiving side, the connections are similar, except that the INT pin of the module is connected to pin 2 of Arduino." }, { "code": null, "e": 4314, "s": 4194, "text": "The two (transmitter and receiver) are be joined together by CAN_H and CAN_L lines (CAN_H to CAN_H and CAN_L to CAN_L)." }, { "code": null, "e": 4559, "s": 4314, "text": "We will use this library from Seeed Studio. This library won't be found in the Library Manager of Arduino. The procedure for downloading a third-party library is given here βˆ’ https://www.tutorialspoint.com/using-a-third-party-library-in-arduino" }, { "code": null, "e": 4688, "s": 4559, "text": "Once you have the library installed, you can find the send and receive_interrupt examples in File -> Examples -> CAN_BUS Shield." }, { "code": null, "e": 4753, "s": 4688, "text": "We will be using slightly simplified versions of these examples." }, { "code": null, "e": 4788, "s": 4753, "text": "The code for SEND is given below βˆ’" }, { "code": null, "e": 5605, "s": 4788, "text": "#include <SPI.h>\n#include \"mcp2515_can.h\"\nonst int SPI_CS_PIN = 10;\nmcp2515_can CAN(SPI_CS_PIN); // Set CS pin\nvoid setup() {\n Serial.begin(115200);\n while(!Serial){};\n // init can bus : baudrate = 500k\n while (CAN_OK != CAN.begin(CAN_500KBPS)) {\n Serial.println(\"CAN init fail, retry...\");\n delay(100);\n }\n Serial.println(\"CAN init ok!\");\n}\nunsigned char stmp[8] = {0, 0, 0, 0, 0, 0, 0, 0};\nvoid loop() {\n // send data: id = 0x00, standrad frame, data len = 8, stmp: data buf\n stmp[7] = stmp[7] + 1;\n if (stmp[7] == 100) {\n stmp[7] = 0;\n stmp[6] = stmp[6] + 1;\n if (stmp[6] == 100) {\n stmp[6] = 0;\n stmp[5] = stmp[5] + 1;\n }\n }\n CAN.sendMsgBuf(0x00, 0, 8, stmp);\n delay(100); // send data per 100ms\n Serial.println(\"CAN BUS sendMsgBuf ok!\");\n}" }, { "code": null, "e": 5691, "s": 5605, "text": "Much of the code is self-explanatory. We will go through the implementation in brief." }, { "code": null, "e": 5757, "s": 5691, "text": "We initialize CAN using the Chip Select pin (Pin 10 in our case)." }, { "code": null, "e": 5800, "s": 5757, "text": "mcp2515_can CAN(SPI_CS_PIN); // Set CS pin" }, { "code": null, "e": 5879, "s": 5800, "text": "We set the baud rate to 500 kbps in the Setup and check if CAN began properly." }, { "code": null, "e": 5903, "s": 5879, "text": "CAN.begin(CAN_500KBPS))" }, { "code": null, "e": 6290, "s": 5903, "text": "We are transmitting 8 bytes in each frame to the received. The bytes are all 0 to begin with.Within loop, we keep incrementing the last byte, till it reaches 100, then add one to the second last byte and again keep incrementing the last byte till it reaches 100, and so on. We increment the third-last byte if the second-last byte reaches 100. This gives us several iterations to go on." }, { "code": null, "e": 6318, "s": 6290, "text": "The important function is βˆ’" }, { "code": null, "e": 6352, "s": 6318, "text": "CAN.sendMsgBuf(0x00, 0, 8, stmp);" }, { "code": null, "e": 6614, "s": 6352, "text": "The first argument is the ID of the message (0x00), the second argument represents whether we are using the base format or the extended format (0 for base, and 1 for extended), the third argument is the length of the data (8), and the fourth is the data buffer." }, { "code": null, "e": 6673, "s": 6614, "text": "This will keep sending 8-byte data frames to the receiver." }, { "code": null, "e": 6711, "s": 6673, "text": "The code for RECEIVE is shown below βˆ’" }, { "code": null, "e": 8111, "s": 6711, "text": "#include <SPI.h>\n#include \"mcp2515_can.h\"\nconst int SPI_CS_PIN = 10;\nconst int CAN_INT_PIN = 2;\nmcp2515_can CAN(SPI_CS_PIN); // Set CS pin\nunsigned char flagRecv = 0;\nunsigned char len = 0;\nunsigned char buf[8];\nchar str[20];\nvoid setup() {\n Serial.begin(115200);\n while (!Serial) {\n ; // wait for serial port to connect. Needed for native USB port only\n }\n // start interrupt\n attachInterrupt(digitalPinToInterrupt(CAN_INT_PIN), MCP2515_ISR, FALLING);\n // init can bus : baudrate = 500k\n while (CAN_OK != CAN.begin(CAN_500KBPS)) {\n Serial.println(\"CAN init fail, retry...\");\n delay(100);\n }\n Serial.println(\"CAN init ok!\");\n}\nvoid MCP2515_ISR() {\n flagRecv = 1;\n}\nvoid loop() {\n if (flagRecv) {\n // check if get data\n flagRecv = 0; // clear flag\n Serial.println(\"into loop\");\n // iterate over all pending messages\n // If either the bus is saturated or the MCU is busy,\n // both RX buffers may be in use and reading a single\n // message does not clear the IRQ conditon.\n while (CAN_MSGAVAIL == CAN.checkReceive()) {\n // read data, len: data length, buf: data buf\n Serial.println(\"checkReceive\");\n CAN.readMsgBuf(&len, buf);\n // print the data\n for (int i = 0; i < len; i++) {\n Serial.print(buf[i]); Serial.print(\"\\t\");\n }\n Serial.println();\n }\n }\n}" }, { "code": null, "e": 8453, "s": 8111, "text": "As you can see the initial variable declarations and the setup is similar to SEND. The only difference is that an interrupt is attached to digital pin 2. Remember that the INT pin of the module goes LOW whenever a message is received. Therefore, a FALLING EDGE interrupt is attached to pin 2, which is connected to the INT pin of the module." }, { "code": null, "e": 8547, "s": 8453, "text": "// start interrupt\nattachInterrupt(digitalPinToInterrupt(CAN_INT_PIN), MCP2515_ISR, FALLING);" }, { "code": null, "e": 8647, "s": 8547, "text": "Within the MCP2515_ISR function, we simply set the flagRecv to 1, which is checked inside the loop." }, { "code": null, "e": 8831, "s": 8647, "text": "When the flagRecv value is 1, the available data in the CAN buffer is checked (using CAN.checkReceive()) and read and printed on the Serial Monitor. The function to read the data is βˆ’" }, { "code": null, "e": 8858, "s": 8831, "text": "CAN.readMsgBuf(&len, buf);" }, { "code": null, "e": 8983, "s": 8858, "text": "The first argument indicates the length of data available, and the second argument is the buffer to store the incoming data." }, { "code": null, "e": 9100, "s": 8983, "text": "I hope you enjoyed this article. You are encouraged to go through the other examples that come in with this library." } ]
Last duplicate element in a sorted array
12 Jun, 2022 We have a sorted array with duplicate elements and we have to find the index of last duplicate element and print index of it and also print the duplicate element. If no such element found print a message. Examples: Input : arr[] = {1, 5, 5, 6, 6, 7} Output : Last index: 4 Last duplicate item: 6 Input : arr[] = {1, 2, 3, 4, 5} Output : No duplicate found We simply iterate through the array in reverse order and compare the current and previous element. If a match is found then we print the index and duplicate element. As this is sorted array it will be the last duplicate. If no such element is found we will print the message for it. 1- for i = n-1 to 0 if (arr[i] == arr[i-1]) Print current element and its index. Return 2- If no such element found print a message of no duplicate found. C++ C Java Python3 C# PHP Javascript // To print last duplicate element and its// index in a sorted array#include <bits/stdc++.h> void dupLastIndex(int arr[], int n) { // if array is null or size is less // than equal to 0 return if (arr == NULL || n <= 0) return; // compare elements and return last // duplicate and its index for (int i = n - 1; i > 0; i--) { if (arr[i] == arr[i - 1]) { printf("Last index: %d\nLast " "duplicate item: %d\n", i, arr[i]); return; } } // If we reach here, then no duplicate // found. printf("no duplicate found");} int main() { int arr[] = {1, 5, 5, 6, 6, 7, 9}; int n = sizeof(arr) / sizeof(int); dupLastIndex(arr, n); return 0;} // C code To print last duplicate element and its// index in a sorted array#include <stdio.h> void dupLastIndex(int arr[], int n){ // if array is null or size is less // than equal to 0 return if (arr == NULL || n <= 0) return; // compare elements and return last // duplicate and its index for (int i = n - 1; i > 0; i--) { if (arr[i] == arr[i - 1]) { printf("Last index: %d\nLast " "duplicate item: %d\n", i, arr[i]); return; } } // If we reach here, then no duplicate // found. printf("no duplicate found");} int main(){ int arr[] = { 1, 5, 5, 6, 6, 7, 9 }; int n = sizeof(arr) / sizeof(int); dupLastIndex(arr, n); return 0;} // This code is contributed by muditj148. // Java code to print last duplicate element// and its index in a sorted arrayimport java.io.*; class GFG{ static void dupLastIndex(int arr[], int n) { // if array is null or size is less // than equal to 0 return if (arr == null || n <= 0) return; // compare elements and return last // duplicate and its index for (int i = n - 1; i > 0; i--) { if (arr[i] == arr[i - 1]) { System.out.println("Last index:" + i); System.out.println("Last duplicate item: " + arr[i]); return; } } // If we reach here, then no duplicate // found. System.out.print("no duplicate found"); } // Driver code public static void main (String[] args) { int arr[] = {1, 5, 5, 6, 6, 7, 9}; int n = arr.length; dupLastIndex(arr, n); }} // This code is contributed by vt_m # Python3 code to print last duplicate# element and its index in a sorted array def dupLastIndex(arr, n): # if array is null or size is less # than equal to 0 return if (arr == None or n <= 0): return # compare elements and return last # duplicate and its index for i in range(n - 1, 0, -1): if (arr[i] == arr[i - 1]): print("Last index:", i, "\nLast", "duplicate item:",arr[i]) return # If we reach here, then no duplicate # found. print("no duplicate found") arr = [1, 5, 5, 6, 6, 7, 9]n = len(arr)dupLastIndex(arr, n) # This code is contributed by# Smitha Dinesh Semwal // C# code to print last duplicate element// and its index in a sorted arrayusing System; class GFG { static void dupLastIndex(int []arr, int n) { // if array is null or size is less // than equal to 0 return if (arr == null || n <= 0) return; // compare elements and return last // duplicate and its index for (int i = n - 1; i > 0; i--) { if (arr[i] == arr[i - 1]) { Console.WriteLine("Last index:" + i); Console.WriteLine("Last duplicate item: " + arr[i]); return; } } // If we reach here, then no duplicate // found. Console.WriteLine("no duplicate found"); } // Driver code public static void Main () { int []arr = {1, 5, 5, 6, 6, 7, 9}; int n = arr.Length; dupLastIndex(arr, n); }} // This code is contributed by vt_m. <?php// PHP program to print last// duplicate element and its// index in a sorted array function dupLastIndex($arr, $n){ // if array is null or size is less // than equal to 0 return if ($arr == null or $n <= 0) return; // compare elements and return last // duplicate and its index for ( $i = $n - 1; $i > 0; $i--) { if ($arr[$i] == $arr[$i - 1]) { echo "Last index:", $i , "\n"; echo "Last duplicate item:", $arr[$i]; return; }} // If we reach here, then // no duplicate found. echo "no duplicate found";} // Driver Code$arr = array(1, 5, 5, 6, 6, 7, 9);$n = count($arr);dupLastIndex($arr, $n); // This code is contributed by anuj_67.?> <script> // JavaScript program to print last duplicate element// and its index in a sorted array function dupLastIndex(arr, n) { // if array is null or size is less // than equal to 0 return if (arr == null || n <= 0) return; // compare elements and return last // duplicate and its index for (let i = n - 1; i > 0; i--) { if (arr[i] == arr[i - 1]) { document.write("Last index:" + i + "<br/>"); document.write("Last duplicate item: " + arr[i] + "<br/>"); return; } } // If we reach here, then no duplicate // found. document.write("no duplicate found"); } // Driver code let arr = [1, 5, 5, 6, 6, 7, 9]; let n = arr.length; dupLastIndex(arr, n); </script> Last index: 4 Last duplicate item: 6 Time Complexity: O(n) Auxiliary Space: O(1), as no extra space is used vt_m sanjoy_62 muditj148 codewithmini Arrays Searching Arrays Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n12 Jun, 2022" }, { "code": null, "e": 270, "s": 53, "text": "We have a sorted array with duplicate elements and we have to find the index of last duplicate element and print index of it and also print the duplicate element. If no such element found print a message. Examples: " }, { "code": null, "e": 412, "s": 270, "text": "Input : arr[] = {1, 5, 5, 6, 6, 7}\nOutput :\nLast index: 4\nLast duplicate item: 6\n\nInput : arr[] = {1, 2, 3, 4, 5}\nOutput : No duplicate found" }, { "code": null, "e": 698, "s": 414, "text": "We simply iterate through the array in reverse order and compare the current and previous element. If a match is found then we print the index and duplicate element. As this is sorted array it will be the last duplicate. If no such element is found we will print the message for it. " }, { "code": null, "e": 878, "s": 698, "text": "1- for i = n-1 to 0\n if (arr[i] == arr[i-1])\n Print current element and its index.\n Return\n2- If no such element found print a message \n of no duplicate found." }, { "code": null, "e": 884, "s": 880, "text": "C++" }, { "code": null, "e": 886, "s": 884, "text": "C" }, { "code": null, "e": 891, "s": 886, "text": "Java" }, { "code": null, "e": 899, "s": 891, "text": "Python3" }, { "code": null, "e": 902, "s": 899, "text": "C#" }, { "code": null, "e": 906, "s": 902, "text": "PHP" }, { "code": null, "e": 917, "s": 906, "text": "Javascript" }, { "code": "// To print last duplicate element and its// index in a sorted array#include <bits/stdc++.h> void dupLastIndex(int arr[], int n) { // if array is null or size is less // than equal to 0 return if (arr == NULL || n <= 0) return; // compare elements and return last // duplicate and its index for (int i = n - 1; i > 0; i--) { if (arr[i] == arr[i - 1]) { printf(\"Last index: %d\\nLast \" \"duplicate item: %d\\n\", i, arr[i]); return; } } // If we reach here, then no duplicate // found. printf(\"no duplicate found\");} int main() { int arr[] = {1, 5, 5, 6, 6, 7, 9}; int n = sizeof(arr) / sizeof(int); dupLastIndex(arr, n); return 0;}", "e": 1594, "s": 917, "text": null }, { "code": "// C code To print last duplicate element and its// index in a sorted array#include <stdio.h> void dupLastIndex(int arr[], int n){ // if array is null or size is less // than equal to 0 return if (arr == NULL || n <= 0) return; // compare elements and return last // duplicate and its index for (int i = n - 1; i > 0; i--) { if (arr[i] == arr[i - 1]) { printf(\"Last index: %d\\nLast \" \"duplicate item: %d\\n\", i, arr[i]); return; } } // If we reach here, then no duplicate // found. printf(\"no duplicate found\");} int main(){ int arr[] = { 1, 5, 5, 6, 6, 7, 9 }; int n = sizeof(arr) / sizeof(int); dupLastIndex(arr, n); return 0;} // This code is contributed by muditj148.", "e": 2389, "s": 1594, "text": null }, { "code": "// Java code to print last duplicate element// and its index in a sorted arrayimport java.io.*; class GFG{ static void dupLastIndex(int arr[], int n) { // if array is null or size is less // than equal to 0 return if (arr == null || n <= 0) return; // compare elements and return last // duplicate and its index for (int i = n - 1; i > 0; i--) { if (arr[i] == arr[i - 1]) { System.out.println(\"Last index:\" + i); System.out.println(\"Last duplicate item: \" + arr[i]); return; } } // If we reach here, then no duplicate // found. System.out.print(\"no duplicate found\"); } // Driver code public static void main (String[] args) { int arr[] = {1, 5, 5, 6, 6, 7, 9}; int n = arr.length; dupLastIndex(arr, n); }} // This code is contributed by vt_m", "e": 3385, "s": 2389, "text": null }, { "code": "# Python3 code to print last duplicate# element and its index in a sorted array def dupLastIndex(arr, n): # if array is null or size is less # than equal to 0 return if (arr == None or n <= 0): return # compare elements and return last # duplicate and its index for i in range(n - 1, 0, -1): if (arr[i] == arr[i - 1]): print(\"Last index:\", i, \"\\nLast\", \"duplicate item:\",arr[i]) return # If we reach here, then no duplicate # found. print(\"no duplicate found\") arr = [1, 5, 5, 6, 6, 7, 9]n = len(arr)dupLastIndex(arr, n) # This code is contributed by# Smitha Dinesh Semwal", "e": 4066, "s": 3385, "text": null }, { "code": "// C# code to print last duplicate element// and its index in a sorted arrayusing System; class GFG { static void dupLastIndex(int []arr, int n) { // if array is null or size is less // than equal to 0 return if (arr == null || n <= 0) return; // compare elements and return last // duplicate and its index for (int i = n - 1; i > 0; i--) { if (arr[i] == arr[i - 1]) { Console.WriteLine(\"Last index:\" + i); Console.WriteLine(\"Last duplicate item: \" + arr[i]); return; } } // If we reach here, then no duplicate // found. Console.WriteLine(\"no duplicate found\"); } // Driver code public static void Main () { int []arr = {1, 5, 5, 6, 6, 7, 9}; int n = arr.Length; dupLastIndex(arr, n); }} // This code is contributed by vt_m.", "e": 5072, "s": 4066, "text": null }, { "code": "<?php// PHP program to print last// duplicate element and its// index in a sorted array function dupLastIndex($arr, $n){ // if array is null or size is less // than equal to 0 return if ($arr == null or $n <= 0) return; // compare elements and return last // duplicate and its index for ( $i = $n - 1; $i > 0; $i--) { if ($arr[$i] == $arr[$i - 1]) { echo \"Last index:\", $i , \"\\n\"; echo \"Last duplicate item:\", $arr[$i]; return; }} // If we reach here, then // no duplicate found. echo \"no duplicate found\";} // Driver Code$arr = array(1, 5, 5, 6, 6, 7, 9);$n = count($arr);dupLastIndex($arr, $n); // This code is contributed by anuj_67.?>", "e": 5809, "s": 5072, "text": null }, { "code": "<script> // JavaScript program to print last duplicate element// and its index in a sorted array function dupLastIndex(arr, n) { // if array is null or size is less // than equal to 0 return if (arr == null || n <= 0) return; // compare elements and return last // duplicate and its index for (let i = n - 1; i > 0; i--) { if (arr[i] == arr[i - 1]) { document.write(\"Last index:\" + i + \"<br/>\"); document.write(\"Last duplicate item: \" + arr[i] + \"<br/>\"); return; } } // If we reach here, then no duplicate // found. document.write(\"no duplicate found\"); } // Driver code let arr = [1, 5, 5, 6, 6, 7, 9]; let n = arr.length; dupLastIndex(arr, n); </script>", "e": 6705, "s": 5809, "text": null }, { "code": null, "e": 6742, "s": 6705, "text": "Last index: 4\nLast duplicate item: 6" }, { "code": null, "e": 6767, "s": 6744, "text": "Time Complexity: O(n) " }, { "code": null, "e": 6816, "s": 6767, "text": "Auxiliary Space: O(1), as no extra space is used" }, { "code": null, "e": 6821, "s": 6816, "text": "vt_m" }, { "code": null, "e": 6831, "s": 6821, "text": "sanjoy_62" }, { "code": null, "e": 6841, "s": 6831, "text": "muditj148" }, { "code": null, "e": 6854, "s": 6841, "text": "codewithmini" }, { "code": null, "e": 6861, "s": 6854, "text": "Arrays" }, { "code": null, "e": 6871, "s": 6861, "text": "Searching" }, { "code": null, "e": 6878, "s": 6871, "text": "Arrays" }, { "code": null, "e": 6888, "s": 6878, "text": "Searching" } ]
if/else condition in CSS
30 Jun, 2022 Given an HTML file and we need to apply using if-else conditions in CSS.No, We can not use if-else conditions in CSS as CSS doesn’t support logics. But we can use some alternatives to if-else which are discussed below:Method 1: In this method, we will use classes in HTML file to achieve this. We will define different class names according to the conditions which we want to apply in CSS. Suppose we want to change the color of text according to the line number then the if-else condition will be: if(line1){ color : red; }else{ color : green; } By using the above-discussed method, we will create classes and then apply CSS in it: .color-line1{ color : red; } .color-line2{ color : green; } So, the above classes will execute only for HTML tags in which these classes are used.Example: html <html> <head> <title> If-else condition in CSS </title> <!-- Applying CSS --> <style> /* First line CSS */ .color-line1{ color : red; } /* Second line CSS */ .color-line2{ color: green; } </style></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksforGeeks </h1> <h3> If-else condition in CSS </h3> <span class="color-line1">This is first line</span> <br><br> <span class="color-line2">This is second line</span> </body> </html> Output: Method 2: We can use CSS preprocessors like SASS which allows us to write condition statements in it. Even if you use SASS you have to pre-process your stylesheets which means that the condition are evaluated at compile time, not at run time.Syntax: $type: line; p { @if $type == line1 { color: blue; } @else if $type == line2 { color: red; } @else if $type == line3 { color: green; } @else { color: black; } } To know more about SASS click hereTo read about if-else in SASS click hereSupported Browsers: Google Chrome Internet Explorer Firefox Opera Safari CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples. ysachin2314 CSS-Misc Picked SASS CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n30 Jun, 2022" }, { "code": null, "e": 442, "s": 52, "text": "Given an HTML file and we need to apply using if-else conditions in CSS.No, We can not use if-else conditions in CSS as CSS doesn’t support logics. But we can use some alternatives to if-else which are discussed below:Method 1: In this method, we will use classes in HTML file to achieve this. We will define different class names according to the conditions which we want to apply in CSS." }, { "code": null, "e": 551, "s": 442, "text": "Suppose we want to change the color of text according to the line number then the if-else condition will be:" }, { "code": null, "e": 605, "s": 551, "text": "if(line1){\n color : red;\n}else{\n color : green;\n}" }, { "code": null, "e": 691, "s": 605, "text": "By using the above-discussed method, we will create classes and then apply CSS in it:" }, { "code": null, "e": 757, "s": 691, "text": ".color-line1{\n color : red;\n}\n.color-line2{\n color : green;\n}" }, { "code": null, "e": 852, "s": 757, "text": "So, the above classes will execute only for HTML tags in which these classes are used.Example:" }, { "code": null, "e": 857, "s": 852, "text": "html" }, { "code": "<html> <head> <title> If-else condition in CSS </title> <!-- Applying CSS --> <style> /* First line CSS */ .color-line1{ color : red; } /* Second line CSS */ .color-line2{ color: green; } </style></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h3> If-else condition in CSS </h3> <span class=\"color-line1\">This is first line</span> <br><br> <span class=\"color-line2\">This is second line</span> </body> </html> ", "e": 1501, "s": 857, "text": null }, { "code": null, "e": 1509, "s": 1501, "text": "Output:" }, { "code": null, "e": 1759, "s": 1509, "text": "Method 2: We can use CSS preprocessors like SASS which allows us to write condition statements in it. Even if you use SASS you have to pre-process your stylesheets which means that the condition are evaluated at compile time, not at run time.Syntax:" }, { "code": null, "e": 1946, "s": 1759, "text": "$type: line;\np {\n @if $type == line1 {\n color: blue;\n } @else if $type == line2 {\n color: red;\n } @else if $type == line3 {\n color: green;\n } @else {\n color: black;\n }\n}" }, { "code": null, "e": 2040, "s": 1946, "text": "To know more about SASS click hereTo read about if-else in SASS click hereSupported Browsers:" }, { "code": null, "e": 2054, "s": 2040, "text": "Google Chrome" }, { "code": null, "e": 2072, "s": 2054, "text": "Internet Explorer" }, { "code": null, "e": 2080, "s": 2072, "text": "Firefox" }, { "code": null, "e": 2086, "s": 2080, "text": "Opera" }, { "code": null, "e": 2093, "s": 2086, "text": "Safari" }, { "code": null, "e": 2279, "s": 2093, "text": "CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples." }, { "code": null, "e": 2291, "s": 2279, "text": "ysachin2314" }, { "code": null, "e": 2300, "s": 2291, "text": "CSS-Misc" }, { "code": null, "e": 2307, "s": 2300, "text": "Picked" }, { "code": null, "e": 2312, "s": 2307, "text": "SASS" }, { "code": null, "e": 2316, "s": 2312, "text": "CSS" }, { "code": null, "e": 2333, "s": 2316, "text": "Web Technologies" } ]
Genesys Interview Experience (On-Campus)
20 Dec, 2018 Genesys is a networking based company. Most of the questions were from Networks, Operating Systems, C++ and Java. No questions were asked from Database. Day 1: Written Test: (2 hours) 5 sections of aptitude questions: Correct answer: 2 marks, Wrong answer: -1 mark Verbal – 5 questionsQuantitative – 10 questionsNetworks – 10 questionsProgramming -10 questionsOperating System – 10 questionsFollowed by one coding question (Difficulty: hard). I solved it using backtracking algorithm. Day 2: Tech Round 1: (1 hour) Explain your project.I was asked to explain my networking based project and to explain how I handled the difficulties. Write a singleton class.I wrote 3 ways (Non-thread safe, Thread safe, optimized and thread safe) to make a class singleton. Explain some OOP concepts you knowI explained Inheritance, abstraction, polymorphism. What are the types of inheritance?Explained single level, multi-level, hybrid class A { void show(){}} class B : public A{ void show(){}} int main() { A *a = new A(); B *b = new B(); A *a1 = new B(); a.show(); b.show(); a1.show(); return 0;} Asked me to explain which methods will be called. I also added the use of virtual keyword in my explanation. 3 coding questions. Given an array find equilibrium index in it.( https://www.geeksforgeeks.org/equilibrium-index-of-an-array/)Check whether string is palindrome. If not convert it into palindrome by adding characters in front of string with minimal number of steps.Given me this sequence β€œ12” -> β€œ 1112” -> β€œ3112”->”132112”->... Write a code to find nth string in this sequence. Given an array find equilibrium index in it.( https://www.geeksforgeeks.org/equilibrium-index-of-an-array/) Check whether string is palindrome. If not convert it into palindrome by adding characters in front of string with minimal number of steps. Given me this sequence β€œ12” -> β€œ 1112” -> β€œ3112”->”132112”->... Write a code to find nth string in this sequence. Tech round 2: (20 minutes) This round started with 2 puzzles. Why did you get rejected in previous companies? Be prepared to answer in optimistic way ? Rate yourself in Linux. After I rated myself, he asked to me explain the use of LEX and YACC command. What is the first stage of compilation? What are the OSI layers? What are the commands exchanged when a socket connection gets established? The question wasn’t about TCP three way handshake. Tech Round 3: (3 minutes)He asked to choose comfortable zone from my areas of interest. I chose Data Structures. How will you represent K-nary Tree Node? Find merge point of two linked list. (https://www.geeksforgeeks.org/write-a-function-to-get-the-intersection-point-of-two-linked-lists/). After I solve it, he was modifying the question and asked me to solve them. Converted it to circular list. Then added Loops in both the list. I had a project that does β€œNetwork Chatting”. He asked to me explain how I handled multiple requests from different clients. Explain multithreading issues. HR Round: (5 minutes)This is just a personal interview. Asked about my nature, how I deal with people, why did I choose TCE... Finally 2 hours later, Offer letters were distributed ? Genesys On-Campus Interview Experiences Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Amazon Interview Experience for SDE 1 Amazon Interview Experience SDE-2 (3 Years Experienced) Write It Up: Share Your Interview Experiences Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022 Amazon Interview Experience for SDE-1 Google SWE Interview Experience (Google Online Coding Challenge) 2022 Nagarro Interview Experience Tiger Analytics Interview Experience for Data Analyst (On-Campus) Goldman Sachs Interview Experience for FTE ( On-Campus) Virtual 2021-22 Nagarro Interview Experience | On-Campus 2021
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Dec, 2018" }, { "code": null, "e": 181, "s": 28, "text": "Genesys is a networking based company. Most of the questions were from Networks, Operating Systems, C++ and Java. No questions were asked from Database." }, { "code": null, "e": 188, "s": 181, "text": "Day 1:" }, { "code": null, "e": 212, "s": 188, "text": "Written Test: (2 hours)" }, { "code": null, "e": 246, "s": 212, "text": "5 sections of aptitude questions:" }, { "code": null, "e": 293, "s": 246, "text": "Correct answer: 2 marks, Wrong answer: -1 mark" }, { "code": null, "e": 513, "s": 293, "text": "Verbal – 5 questionsQuantitative – 10 questionsNetworks – 10 questionsProgramming -10 questionsOperating System – 10 questionsFollowed by one coding question (Difficulty: hard). I solved it using backtracking algorithm." }, { "code": null, "e": 522, "s": 515, "text": "Day 2:" }, { "code": null, "e": 545, "s": 522, "text": "Tech Round 1: (1 hour)" }, { "code": null, "e": 664, "s": 545, "text": "Explain your project.I was asked to explain my networking based project and to explain how I handled the difficulties." }, { "code": null, "e": 788, "s": 664, "text": "Write a singleton class.I wrote 3 ways (Non-thread safe, Thread safe, optimized and thread safe) to make a class singleton." }, { "code": null, "e": 874, "s": 788, "text": "Explain some OOP concepts you knowI explained Inheritance, abstraction, polymorphism." }, { "code": null, "e": 952, "s": 874, "text": "What are the types of inheritance?Explained single level, multi-level, hybrid" }, { "code": "class A { void show(){}} class B : public A{ void show(){}} int main() { A *a = new A(); B *b = new B(); A *a1 = new B(); a.show(); b.show(); a1.show(); return 0;}", "e": 1128, "s": 952, "text": null }, { "code": null, "e": 1178, "s": 1128, "text": "Asked me to explain which methods will be called." }, { "code": null, "e": 1237, "s": 1178, "text": "I also added the use of virtual keyword in my explanation." }, { "code": null, "e": 1257, "s": 1237, "text": "3 coding questions." }, { "code": null, "e": 1617, "s": 1257, "text": "Given an array find equilibrium index in it.( https://www.geeksforgeeks.org/equilibrium-index-of-an-array/)Check whether string is palindrome. If not convert it into palindrome by adding characters in front of string with minimal number of steps.Given me this sequence β€œ12” -> β€œ 1112” -> β€œ3112”->”132112”->... Write a code to find nth string in this sequence." }, { "code": null, "e": 1725, "s": 1617, "text": "Given an array find equilibrium index in it.( https://www.geeksforgeeks.org/equilibrium-index-of-an-array/)" }, { "code": null, "e": 1865, "s": 1725, "text": "Check whether string is palindrome. If not convert it into palindrome by adding characters in front of string with minimal number of steps." }, { "code": null, "e": 1979, "s": 1865, "text": "Given me this sequence β€œ12” -> β€œ 1112” -> β€œ3112”->”132112”->... Write a code to find nth string in this sequence." }, { "code": null, "e": 2006, "s": 1979, "text": "Tech round 2: (20 minutes)" }, { "code": null, "e": 2041, "s": 2006, "text": "This round started with 2 puzzles." }, { "code": null, "e": 2131, "s": 2041, "text": "Why did you get rejected in previous companies? Be prepared to answer in optimistic way ?" }, { "code": null, "e": 2233, "s": 2131, "text": "Rate yourself in Linux. After I rated myself, he asked to me explain the use of LEX and YACC command." }, { "code": null, "e": 2273, "s": 2233, "text": "What is the first stage of compilation?" }, { "code": null, "e": 2298, "s": 2273, "text": "What are the OSI layers?" }, { "code": null, "e": 2424, "s": 2298, "text": "What are the commands exchanged when a socket connection gets established? The question wasn’t about TCP three way handshake." }, { "code": null, "e": 2537, "s": 2424, "text": "Tech Round 3: (3 minutes)He asked to choose comfortable zone from my areas of interest. I chose Data Structures." }, { "code": null, "e": 2578, "s": 2537, "text": "How will you represent K-nary Tree Node?" }, { "code": null, "e": 2716, "s": 2578, "text": "Find merge point of two linked list. (https://www.geeksforgeeks.org/write-a-function-to-get-the-intersection-point-of-two-linked-lists/)." }, { "code": null, "e": 2792, "s": 2716, "text": "After I solve it, he was modifying the question and asked me to solve them." }, { "code": null, "e": 2823, "s": 2792, "text": "Converted it to circular list." }, { "code": null, "e": 2858, "s": 2823, "text": "Then added Loops in both the list." }, { "code": null, "e": 3014, "s": 2858, "text": "I had a project that does β€œNetwork Chatting”. He asked to me explain how I handled multiple requests from different clients. Explain multithreading issues." }, { "code": null, "e": 3141, "s": 3014, "text": "HR Round: (5 minutes)This is just a personal interview. Asked about my nature, how I deal with people, why did I choose TCE..." }, { "code": null, "e": 3197, "s": 3141, "text": "Finally 2 hours later, Offer letters were distributed ?" }, { "code": null, "e": 3205, "s": 3197, "text": "Genesys" }, { "code": null, "e": 3215, "s": 3205, "text": "On-Campus" }, { "code": null, "e": 3237, "s": 3215, "text": "Interview Experiences" }, { "code": null, "e": 3335, "s": 3237, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3373, "s": 3335, "text": "Amazon Interview Experience for SDE 1" }, { "code": null, "e": 3429, "s": 3373, "text": "Amazon Interview Experience SDE-2 (3 Years Experienced)" }, { "code": null, "e": 3475, "s": 3429, "text": "Write It Up: Share Your Interview Experiences" }, { "code": null, "e": 3548, "s": 3475, "text": "Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022" }, { "code": null, "e": 3586, "s": 3548, "text": "Amazon Interview Experience for SDE-1" }, { "code": null, "e": 3656, "s": 3586, "text": "Google SWE Interview Experience (Google Online Coding Challenge) 2022" }, { "code": null, "e": 3685, "s": 3656, "text": "Nagarro Interview Experience" }, { "code": null, "e": 3751, "s": 3685, "text": "Tiger Analytics Interview Experience for Data Analyst (On-Campus)" }, { "code": null, "e": 3823, "s": 3751, "text": "Goldman Sachs Interview Experience for FTE ( On-Campus) Virtual 2021-22" } ]
Python | Ways to join pair of elements in list
25 Jun, 2019 Given a list, the task is to join a pair of elements of the list. Given below are a few methods to solve the given task. Method #1: Using zip() method # Python code to demonstrate # how to join pair of elements of list # Initialising listini_list = ['a', 'b', 'c', 'd', 'e', 'f'] # Printing initial list print ("Initial list", str(ini_list)) # Pairing the elements of listsres = [i + j for i, j in zip(ini_list[::2], ini_list[1::2])] # Printing final resultprint ("Result", str(res)) Initial list ['a', 'b', 'c', 'd', 'e', 'f'] Result ['ab', 'cd', 'ef'] Method #2: Using list comprehension and next and iters # Python code to demonstrate # how to join pair of elements of list # Initialising listini_list = iter(['a', 'b', 'c', 'd', 'e', 'f']) # Pairing the elements of listsres = [h + next(ini_list, '') for h in ini_list] # Printing final resultprint ("Result", str(res)) Result ['ab', 'cd', 'ef'] Method #3: Using list comprehension # Python code to demonstrate # how to join pair of elements of list # Initialising listini_list = ['a', 'b', 'c', 'd', 'e', 'f'] # Printing initial listsprint ("Initial list", str(ini_list)) # Pairing the elements of listsres = [ini_list[i] + ini_list[i + 1] for i in range(0, len(ini_list), 2)] # Printing final resultprint ("Result", str(res)) Initial list ['a', 'b', 'c', 'd', 'e', 'f'] Result ['ab', 'cd', 'ef'] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers Python | Convert string dictionary to dictionary
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Jun, 2019" }, { "code": null, "e": 149, "s": 28, "text": "Given a list, the task is to join a pair of elements of the list. Given below are a few methods to solve the given task." }, { "code": null, "e": 179, "s": 149, "text": "Method #1: Using zip() method" }, { "code": "# Python code to demonstrate # how to join pair of elements of list # Initialising listini_list = ['a', 'b', 'c', 'd', 'e', 'f'] # Printing initial list print (\"Initial list\", str(ini_list)) # Pairing the elements of listsres = [i + j for i, j in zip(ini_list[::2], ini_list[1::2])] # Printing final resultprint (\"Result\", str(res))", "e": 516, "s": 179, "text": null }, { "code": null, "e": 587, "s": 516, "text": "Initial list ['a', 'b', 'c', 'd', 'e', 'f']\nResult ['ab', 'cd', 'ef']\n" }, { "code": null, "e": 643, "s": 587, "text": " Method #2: Using list comprehension and next and iters" }, { "code": "# Python code to demonstrate # how to join pair of elements of list # Initialising listini_list = iter(['a', 'b', 'c', 'd', 'e', 'f']) # Pairing the elements of listsres = [h + next(ini_list, '') for h in ini_list] # Printing final resultprint (\"Result\", str(res))", "e": 911, "s": 643, "text": null }, { "code": null, "e": 938, "s": 911, "text": "Result ['ab', 'cd', 'ef']\n" }, { "code": null, "e": 975, "s": 938, "text": " Method #3: Using list comprehension" }, { "code": "# Python code to demonstrate # how to join pair of elements of list # Initialising listini_list = ['a', 'b', 'c', 'd', 'e', 'f'] # Printing initial listsprint (\"Initial list\", str(ini_list)) # Pairing the elements of listsres = [ini_list[i] + ini_list[i + 1] for i in range(0, len(ini_list), 2)] # Printing final resultprint (\"Result\", str(res))", "e": 1332, "s": 975, "text": null }, { "code": null, "e": 1403, "s": 1332, "text": "Initial list ['a', 'b', 'c', 'd', 'e', 'f']\nResult ['ab', 'cd', 'ef']\n" }, { "code": null, "e": 1424, "s": 1403, "text": "Python list-programs" }, { "code": null, "e": 1431, "s": 1424, "text": "Python" }, { "code": null, "e": 1447, "s": 1431, "text": "Python Programs" }, { "code": null, "e": 1545, "s": 1447, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1577, "s": 1545, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1604, "s": 1577, "text": "Python Classes and Objects" }, { "code": null, "e": 1625, "s": 1604, "text": "Python OOPs Concepts" }, { "code": null, "e": 1648, "s": 1625, "text": "Introduction To PYTHON" }, { "code": null, "e": 1704, "s": 1648, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1726, "s": 1704, "text": "Defaultdict in Python" }, { "code": null, "e": 1765, "s": 1726, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 1803, "s": 1765, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 1840, "s": 1803, "text": "Python Program for Fibonacci numbers" } ]
Scope Resolution operator in PHP
21 Jul, 2021 The scope resolution operator also known as Paamayim Nekudotayim or more commonly known as the double colon is a token that allows access to static, constant, and overridden properties or methods of a class. It is used to refer to blocks or codes in context to classes, objects, etc. An identifier is used with the scope resolution operator. The most common example of the application of the scope resolution operator in PHP is to access the properties and methods of the class. The following examples show the usage of the scope resolution operator in various scenarios. Example 1: This type of definition is used while defining constants within a class. PHP <?php class democlass { const PI = 3.14;} echo democlass::PI; ?> Output: 3.14 Example 2: Three special keywords self, parent, and static are used to access properties or methods from inside the class definition. PHP <?php // Declaring parent classclass demo{ public static $bar=10; public static function func(){ echo static::$bar."\n"; }} // Declaring child classclass Child extends demo{ public static $bar=20; } // Calling for demo's version of func()demo::func(); // Calling for child's version of func()Child::func(); ?> Output: 10 20 Example 3: When an extending class overrides its parent’s function, the compiler calls the child class’s version of the method but it is up to the child class to call its parent’s version of the method. PHP <?php class demo{ public function myfunc() { echo "myfunc() of parent class\n "; }} class child extends demo { public function myfunc(){ // Calling parent's version // of myfunc() method parent::myfunc(); echo "myfunc() of child class"; }} $class = new child;$class -> myfunc() ?> Output: myfunc() of parent class myfunc() of child class sagar0719kumar PHP-Operators PHP PHP Programs Write From Home PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to fetch data from localserver database and display on HTML table using PHP ? Difference between HTTP GET and POST Methods Different ways for passing data to view in Laravel PHP | file_exists( ) Function PHP | Ternary Operator How to call PHP function on the click of a Button ? How to fetch data from localserver database and display on HTML table using PHP ? PHP | Ternary Operator How to create admin login page using PHP? How to send an email using PHPMailer ?
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Jul, 2021" }, { "code": null, "e": 236, "s": 28, "text": "The scope resolution operator also known as Paamayim Nekudotayim or more commonly known as the double colon is a token that allows access to static, constant, and overridden properties or methods of a class." }, { "code": null, "e": 508, "s": 236, "text": "It is used to refer to blocks or codes in context to classes, objects, etc. An identifier is used with the scope resolution operator. The most common example of the application of the scope resolution operator in PHP is to access the properties and methods of the class. " }, { "code": null, "e": 601, "s": 508, "text": "The following examples show the usage of the scope resolution operator in various scenarios." }, { "code": null, "e": 685, "s": 601, "text": "Example 1: This type of definition is used while defining constants within a class." }, { "code": null, "e": 689, "s": 685, "text": "PHP" }, { "code": "<?php class democlass { const PI = 3.14;} echo democlass::PI; ?>", "e": 760, "s": 689, "text": null }, { "code": null, "e": 769, "s": 760, "text": "Output: " }, { "code": null, "e": 774, "s": 769, "text": "3.14" }, { "code": null, "e": 909, "s": 774, "text": "Example 2: Three special keywords self, parent, and static are used to access properties or methods from inside the class definition. " }, { "code": null, "e": 913, "s": 909, "text": "PHP" }, { "code": "<?php // Declaring parent classclass demo{ public static $bar=10; public static function func(){ echo static::$bar.\"\\n\"; }} // Declaring child classclass Child extends demo{ public static $bar=20; } // Calling for demo's version of func()demo::func(); // Calling for child's version of func()Child::func(); ?>", "e": 1256, "s": 913, "text": null }, { "code": null, "e": 1265, "s": 1256, "text": "Output: " }, { "code": null, "e": 1272, "s": 1265, "text": "10 \n20" }, { "code": null, "e": 1475, "s": 1272, "text": "Example 3: When an extending class overrides its parent’s function, the compiler calls the child class’s version of the method but it is up to the child class to call its parent’s version of the method." }, { "code": null, "e": 1479, "s": 1475, "text": "PHP" }, { "code": "<?php class demo{ public function myfunc() { echo \"myfunc() of parent class\\n \"; }} class child extends demo { public function myfunc(){ // Calling parent's version // of myfunc() method parent::myfunc(); echo \"myfunc() of child class\"; }} $class = new child;$class -> myfunc() ?>", "e": 1821, "s": 1479, "text": null }, { "code": null, "e": 1830, "s": 1821, "text": "Output: " }, { "code": null, "e": 1880, "s": 1830, "text": "myfunc() of parent class \nmyfunc() of child class" }, { "code": null, "e": 1897, "s": 1882, "text": "sagar0719kumar" }, { "code": null, "e": 1911, "s": 1897, "text": "PHP-Operators" }, { "code": null, "e": 1915, "s": 1911, "text": "PHP" }, { "code": null, "e": 1928, "s": 1915, "text": "PHP Programs" }, { "code": null, "e": 1944, "s": 1928, "text": "Write From Home" }, { "code": null, "e": 1948, "s": 1944, "text": "PHP" }, { "code": null, "e": 2046, "s": 1948, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2128, "s": 2046, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 2173, "s": 2128, "text": "Difference between HTTP GET and POST Methods" }, { "code": null, "e": 2224, "s": 2173, "text": "Different ways for passing data to view in Laravel" }, { "code": null, "e": 2254, "s": 2224, "text": "PHP | file_exists( ) Function" }, { "code": null, "e": 2277, "s": 2254, "text": "PHP | Ternary Operator" }, { "code": null, "e": 2329, "s": 2277, "text": "How to call PHP function on the click of a Button ?" }, { "code": null, "e": 2411, "s": 2329, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 2434, "s": 2411, "text": "PHP | Ternary Operator" }, { "code": null, "e": 2476, "s": 2434, "text": "How to create admin login page using PHP?" } ]
Batch Script - MOVE
This batch command moves files or directories between directories. move [source] [destination] The files will be copied from source to destination location. The following example shows the different variants of the move command. @echo off Rem Moves the file list.txt to the directory c:\tp move C:\lists.txt c:\tp Rem Renames directory Dir1 to Dir2, assuming Dir1 is a directory and Dir2 does not exist. move Dir1 Dir2 Rem Moves the file lists.txt to the current directory. move C:\lists.txt All actions are performed as per the remarks in the batch file.
[ { "code": null, "e": 2370, "s": 2303, "text": "This batch command moves files or directories between directories." }, { "code": null, "e": 2399, "s": 2370, "text": "move [source] [destination]\n" }, { "code": null, "e": 2461, "s": 2399, "text": "The files will be copied from source to destination location." }, { "code": null, "e": 2533, "s": 2461, "text": "The following example shows the different variants of the move command." }, { "code": null, "e": 2797, "s": 2533, "text": "@echo off\nRem Moves the file list.txt to the directory c:\\tp\nmove C:\\lists.txt c:\\tp\nRem Renames directory Dir1 to Dir2, assuming Dir1 is a directory and Dir2 does not exist. \nmove Dir1 Dir2\nRem Moves the file lists.txt to the current directory.\nmove C:\\lists.txt" } ]
MapReduce Program – Weather Data Analysis For Analyzing Hot And Cold Days
23 Dec, 2021 Here, we will write a Map-Reduce program for analyzing weather datasets to understand its data processing programming model. Weather sensors are collecting weather information across the globe in a large volume of log data. This weather data is semi-structured and record-oriented.This data is stored in a line-oriented ASCII format, where each row represents a single record. Each row has lots of fields like longitude, latitude, daily max-min temperature, daily average temperature, etc. for easiness, we will focus on the main element, i.e. temperature. We will use the data from the National Centres for Environmental Information(NCEI). It has a massive amount of historical weather data that we can use for our data analysis. Problem Statement: Analyzing weather data of Fairbanks, Alaska to find cold and hot days using MapReduce Hadoop. We can download the dataset from this Link, For various cities in different years. choose the year of your choice and select any one of the data text-file for analyzing. In my case, I have selected CRND0103-2020-AK_Fairbanks_11_NE.txt dataset for analysis of hot and cold days in Fairbanks, Alaska.We can get information about data from README.txt file available on the NCEI website. Below is the example of our dataset where column 6 and column 7 is showing Maximum and Minimum temperature, respectively. Make a project in Eclipse with below steps: First Open Eclipse -> then select File -> New -> Java Project ->Name it MyProject -> then select use an execution environment -> choose JavaSE-1.8 then next -> Finish. In this Project Create Java class with name MyMaxMin -> then click Finish Copy the below source code to this MyMaxMin java class JAVA // importing Librariesimport java.io.IOException;import java.util.Iterator;import org.apache.hadoop.fs.Path;import org.apache.hadoop.io.LongWritable;import org.apache.hadoop.io.Text;import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;import org.apache.hadoop.mapreduce.Job;import org.apache.hadoop.mapreduce.Mapper;import org.apache.hadoop.mapreduce.Reducer;import org.apache.hadoop.conf.Configuration; public class MyMaxMin { // Mapper /*MaxTemperatureMapper class is static * and extends Mapper abstract class * having four Hadoop generics type * LongWritable, Text, Text, Text. */ public static class MaxTemperatureMapper extends Mapper<LongWritable, Text, Text, Text> { /** * @method map * This method takes the input as a text data type. * Now leaving the first five tokens, it takes * 6th token is taken as temp_max and * 7th token is taken as temp_min. Now * temp_max > 30 and temp_min < 15 are * passed to the reducer. */ // the data in our data set with // this value is inconsistent data public static final int MISSING = 9999; @Override public void map(LongWritable arg0, Text Value, Context context) throws IOException, InterruptedException { // Convert the single row(Record) to // String and store it in String // variable name line String line = Value.toString(); // Check for the empty line if (!(line.length() == 0)) { // from character 6 to 14 we have // the date in our dataset String date = line.substring(6, 14); // similarly we have taken the maximum // temperature from 39 to 45 characters float temp_Max = Float.parseFloat(line.substring(39, 45).trim()); // similarly we have taken the minimum // temperature from 47 to 53 characters float temp_Min = Float.parseFloat(line.substring(47, 53).trim()); // if maximum temperature is // greater than 30, it is a hot day if (temp_Max > 30.0) { // Hot day context.write(new Text("The Day is Hot Day :" + date), new Text(String.valueOf(temp_Max))); } // if the minimum temperature is // less than 15, it is a cold day if (temp_Min < 15) { // Cold day context.write(new Text("The Day is Cold Day :" + date), new Text(String.valueOf(temp_Min))); } } } } // Reducer /*MaxTemperatureReducer class is static and extends Reducer abstract class having four Hadoop generics type Text, Text, Text, Text. */ public static class MaxTemperatureReducer extends Reducer<Text, Text, Text, Text> { /** * @method reduce * This method takes the input as key and * list of values pair from the mapper, * it does aggregation based on keys and * produces the final context. */ public void reduce(Text Key, Iterator<Text> Values, Context context) throws IOException, InterruptedException { // putting all the values in // temperature variable of type String String temperature = Values.next().toString(); context.write(Key, new Text(temperature)); } } /** * @method main * This method is used for setting * all the configuration properties. * It acts as a driver for map-reduce * code. */ public static void main(String[] args) throws Exception { // reads the default configuration of the // cluster from the configuration XML files Configuration conf = new Configuration(); // Initializing the job with the // default configuration of the cluster Job job = new Job(conf, "weather example"); // Assigning the driver class name job.setJarByClass(MyMaxMin.class); // Key type coming out of mapper job.setMapOutputKeyClass(Text.class); // value type coming out of mapper job.setMapOutputValueClass(Text.class); // Defining the mapper class name job.setMapperClass(MaxTemperatureMapper.class); // Defining the reducer class name job.setReducerClass(MaxTemperatureReducer.class); // Defining input Format class which is // responsible to parse the dataset // into a key value pair job.setInputFormatClass(TextInputFormat.class); // Defining output Format class which is // responsible to parse the dataset // into a key value pair job.setOutputFormatClass(TextOutputFormat.class); // setting the second argument // as a path in a path variable Path OutputPath = new Path(args[1]); // Configuring the input path // from the filesystem into the job FileInputFormat.addInputPath(job, new Path(args[0])); // Configuring the output path from // the filesystem into the job FileOutputFormat.setOutputPath(job, new Path(args[1])); // deleting the context path automatically // from hdfs so that we don't have // to delete it explicitly OutputPath.getFileSystem(conf).delete(OutputPath); // exiting the job only if the // flag value becomes false System.exit(job.waitForCompletion(true) ? 0 : 1); }} Now we need to add external jar for the packages that we have import. Download the jar package Hadoop Common and Hadoop MapReduce Core according to your Hadoop version. You can check Hadoop Version: hadoop version Now we add these external jars to our MyProject. Right Click on MyProject -> then select Build Path-> Click on Configure Build Path and select Add External jars.... and add jars from it’s download location then click -> Apply and Close. Now export the project as jar file. Right-click on MyProject choose Export.. and go to Java -> JAR file click -> Next and choose your export destination then click -> Next. choose Main Class as MyMaxMin by clicking -> Browse and then click -> Finish -> Ok. Start our Hadoop Daemons start-dfs.sh start-yarn.sh Move your dataset to the Hadoop HDFS.Syntax: hdfs dfs -put /file_path /destination In below command / shows the root directory of our HDFS. hdfs dfs -put /home/dikshant/Downloads/CRND0103-2020-AK_Fairbanks_11_NE.txt / Check the file sent to our HDFS. hdfs dfs -ls / Now Run your Jar File with below command and produce the output in MyOutput File.Syntax: hadoop jar /jar_file_location /dataset_location_in_HDFS /output-file_name Command: hadoop jar /home/dikshant/Documents/Project.jar /CRND0103-2020-AK_Fairbanks_11_NE.txt /MyOutput Now Move to localhost:50070/, under utilities select Browse the file system and download part-r-00000 in /MyOutput directory to see result. See the result in the Downloaded File. In the above image, you can see the top 10 results showing the cold days. The second column is a day in yyyy/mm/dd format. For Example, 20200101 means year = 2020 month = 01 Date = 01 khushboogoyal499 anikakapoor Hadoop MapReduce Hadoop Hadoop Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference Between Hadoop and Spark Hadoop Streaming Using Python - Word Count Problem Architecture of HBase Architecture and Working of Hive What is Big Data? Applications of Big Data Hadoop - Different Modes of Operation Introduction to Apache Pig How to Create Table in Hive? Anatomy of File Read and Write in HDFS
[ { "code": null, "e": 54, "s": 26, "text": "\n23 Dec, 2021" }, { "code": null, "e": 805, "s": 54, "text": "Here, we will write a Map-Reduce program for analyzing weather datasets to understand its data processing programming model. Weather sensors are collecting weather information across the globe in a large volume of log data. This weather data is semi-structured and record-oriented.This data is stored in a line-oriented ASCII format, where each row represents a single record. Each row has lots of fields like longitude, latitude, daily max-min temperature, daily average temperature, etc. for easiness, we will focus on the main element, i.e. temperature. We will use the data from the National Centres for Environmental Information(NCEI). It has a massive amount of historical weather data that we can use for our data analysis. Problem Statement: " }, { "code": null, "e": 899, "s": 805, "text": "Analyzing weather data of Fairbanks, Alaska to find cold and hot days using MapReduce Hadoop." }, { "code": null, "e": 1284, "s": 899, "text": "We can download the dataset from this Link, For various cities in different years. choose the year of your choice and select any one of the data text-file for analyzing. In my case, I have selected CRND0103-2020-AK_Fairbanks_11_NE.txt dataset for analysis of hot and cold days in Fairbanks, Alaska.We can get information about data from README.txt file available on the NCEI website. " }, { "code": null, "e": 1408, "s": 1284, "text": "Below is the example of our dataset where column 6 and column 7 is showing Maximum and Minimum temperature, respectively. " }, { "code": null, "e": 1453, "s": 1408, "text": "Make a project in Eclipse with below steps: " }, { "code": null, "e": 1622, "s": 1453, "text": "First Open Eclipse -> then select File -> New -> Java Project ->Name it MyProject -> then select use an execution environment -> choose JavaSE-1.8 then next -> Finish. " }, { "code": null, "e": 1698, "s": 1622, "text": "In this Project Create Java class with name MyMaxMin -> then click Finish " }, { "code": null, "e": 1754, "s": 1698, "text": "Copy the below source code to this MyMaxMin java class " }, { "code": null, "e": 1759, "s": 1754, "text": "JAVA" }, { "code": "// importing Librariesimport java.io.IOException;import java.util.Iterator;import org.apache.hadoop.fs.Path;import org.apache.hadoop.io.LongWritable;import org.apache.hadoop.io.Text;import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;import org.apache.hadoop.mapreduce.Job;import org.apache.hadoop.mapreduce.Mapper;import org.apache.hadoop.mapreduce.Reducer;import org.apache.hadoop.conf.Configuration; public class MyMaxMin { // Mapper /*MaxTemperatureMapper class is static * and extends Mapper abstract class * having four Hadoop generics type * LongWritable, Text, Text, Text. */ public static class MaxTemperatureMapper extends Mapper<LongWritable, Text, Text, Text> { /** * @method map * This method takes the input as a text data type. * Now leaving the first five tokens, it takes * 6th token is taken as temp_max and * 7th token is taken as temp_min. Now * temp_max > 30 and temp_min < 15 are * passed to the reducer. */ // the data in our data set with // this value is inconsistent data public static final int MISSING = 9999; @Override public void map(LongWritable arg0, Text Value, Context context) throws IOException, InterruptedException { // Convert the single row(Record) to // String and store it in String // variable name line String line = Value.toString(); // Check for the empty line if (!(line.length() == 0)) { // from character 6 to 14 we have // the date in our dataset String date = line.substring(6, 14); // similarly we have taken the maximum // temperature from 39 to 45 characters float temp_Max = Float.parseFloat(line.substring(39, 45).trim()); // similarly we have taken the minimum // temperature from 47 to 53 characters float temp_Min = Float.parseFloat(line.substring(47, 53).trim()); // if maximum temperature is // greater than 30, it is a hot day if (temp_Max > 30.0) { // Hot day context.write(new Text(\"The Day is Hot Day :\" + date), new Text(String.valueOf(temp_Max))); } // if the minimum temperature is // less than 15, it is a cold day if (temp_Min < 15) { // Cold day context.write(new Text(\"The Day is Cold Day :\" + date), new Text(String.valueOf(temp_Min))); } } } } // Reducer /*MaxTemperatureReducer class is static and extends Reducer abstract class having four Hadoop generics type Text, Text, Text, Text. */ public static class MaxTemperatureReducer extends Reducer<Text, Text, Text, Text> { /** * @method reduce * This method takes the input as key and * list of values pair from the mapper, * it does aggregation based on keys and * produces the final context. */ public void reduce(Text Key, Iterator<Text> Values, Context context) throws IOException, InterruptedException { // putting all the values in // temperature variable of type String String temperature = Values.next().toString(); context.write(Key, new Text(temperature)); } } /** * @method main * This method is used for setting * all the configuration properties. * It acts as a driver for map-reduce * code. */ public static void main(String[] args) throws Exception { // reads the default configuration of the // cluster from the configuration XML files Configuration conf = new Configuration(); // Initializing the job with the // default configuration of the cluster Job job = new Job(conf, \"weather example\"); // Assigning the driver class name job.setJarByClass(MyMaxMin.class); // Key type coming out of mapper job.setMapOutputKeyClass(Text.class); // value type coming out of mapper job.setMapOutputValueClass(Text.class); // Defining the mapper class name job.setMapperClass(MaxTemperatureMapper.class); // Defining the reducer class name job.setReducerClass(MaxTemperatureReducer.class); // Defining input Format class which is // responsible to parse the dataset // into a key value pair job.setInputFormatClass(TextInputFormat.class); // Defining output Format class which is // responsible to parse the dataset // into a key value pair job.setOutputFormatClass(TextOutputFormat.class); // setting the second argument // as a path in a path variable Path OutputPath = new Path(args[1]); // Configuring the input path // from the filesystem into the job FileInputFormat.addInputPath(job, new Path(args[0])); // Configuring the output path from // the filesystem into the job FileOutputFormat.setOutputPath(job, new Path(args[1])); // deleting the context path automatically // from hdfs so that we don't have // to delete it explicitly OutputPath.getFileSystem(conf).delete(OutputPath); // exiting the job only if the // flag value becomes false System.exit(job.waitForCompletion(true) ? 0 : 1); }}", "e": 7820, "s": 1759, "text": null }, { "code": null, "e": 8020, "s": 7820, "text": "Now we need to add external jar for the packages that we have import. Download the jar package Hadoop Common and Hadoop MapReduce Core according to your Hadoop version. You can check Hadoop Version: " }, { "code": null, "e": 8035, "s": 8020, "text": "hadoop version" }, { "code": null, "e": 8273, "s": 8035, "text": "Now we add these external jars to our MyProject. Right Click on MyProject -> then select Build Path-> Click on Configure Build Path and select Add External jars.... and add jars from it’s download location then click -> Apply and Close. " }, { "code": null, "e": 8531, "s": 8273, "text": "Now export the project as jar file. Right-click on MyProject choose Export.. and go to Java -> JAR file click -> Next and choose your export destination then click -> Next. choose Main Class as MyMaxMin by clicking -> Browse and then click -> Finish -> Ok. " }, { "code": null, "e": 8560, "s": 8535, "text": "Start our Hadoop Daemons" }, { "code": null, "e": 8573, "s": 8560, "text": "start-dfs.sh" }, { "code": null, "e": 8587, "s": 8573, "text": "start-yarn.sh" }, { "code": null, "e": 8633, "s": 8587, "text": "Move your dataset to the Hadoop HDFS.Syntax: " }, { "code": null, "e": 8671, "s": 8633, "text": "hdfs dfs -put /file_path /destination" }, { "code": null, "e": 8729, "s": 8671, "text": "In below command / shows the root directory of our HDFS. " }, { "code": null, "e": 8807, "s": 8729, "text": "hdfs dfs -put /home/dikshant/Downloads/CRND0103-2020-AK_Fairbanks_11_NE.txt /" }, { "code": null, "e": 8841, "s": 8807, "text": "Check the file sent to our HDFS. " }, { "code": null, "e": 8856, "s": 8841, "text": "hdfs dfs -ls /" }, { "code": null, "e": 8947, "s": 8858, "text": "Now Run your Jar File with below command and produce the output in MyOutput File.Syntax:" }, { "code": null, "e": 9021, "s": 8947, "text": "hadoop jar /jar_file_location /dataset_location_in_HDFS /output-file_name" }, { "code": null, "e": 9030, "s": 9021, "text": "Command:" }, { "code": null, "e": 9126, "s": 9030, "text": "hadoop jar /home/dikshant/Documents/Project.jar /CRND0103-2020-AK_Fairbanks_11_NE.txt /MyOutput" }, { "code": null, "e": 9269, "s": 9128, "text": "Now Move to localhost:50070/, under utilities select Browse the file system and download part-r-00000 in /MyOutput directory to see result. " }, { "code": null, "e": 9313, "s": 9273, "text": "See the result in the Downloaded File. " }, { "code": null, "e": 9465, "s": 9313, "text": "In the above image, you can see the top 10 results showing the cold days. The second column is a day in yyyy/mm/dd format. For Example, 20200101 means " }, { "code": null, "e": 9499, "s": 9465, "text": "year = 2020\nmonth = 01\nDate = 01 " }, { "code": null, "e": 9516, "s": 9499, "text": "khushboogoyal499" }, { "code": null, "e": 9528, "s": 9516, "text": "anikakapoor" }, { "code": null, "e": 9535, "s": 9528, "text": "Hadoop" }, { "code": null, "e": 9545, "s": 9535, "text": "MapReduce" }, { "code": null, "e": 9552, "s": 9545, "text": "Hadoop" }, { "code": null, "e": 9559, "s": 9552, "text": "Hadoop" }, { "code": null, "e": 9657, "s": 9559, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9693, "s": 9657, "text": "Difference Between Hadoop and Spark" }, { "code": null, "e": 9744, "s": 9693, "text": "Hadoop Streaming Using Python - Word Count Problem" }, { "code": null, "e": 9766, "s": 9744, "text": "Architecture of HBase" }, { "code": null, "e": 9799, "s": 9766, "text": "Architecture and Working of Hive" }, { "code": null, "e": 9817, "s": 9799, "text": "What is Big Data?" }, { "code": null, "e": 9842, "s": 9817, "text": "Applications of Big Data" }, { "code": null, "e": 9880, "s": 9842, "text": "Hadoop - Different Modes of Operation" }, { "code": null, "e": 9907, "s": 9880, "text": "Introduction to Apache Pig" }, { "code": null, "e": 9936, "s": 9907, "text": "How to Create Table in Hive?" } ]
Multi-plot grid in Seaborn
14 Jan, 2022 Prerequisites: Matplotlib, Seaborn In this article, we are going to see multi-dimensional plot data, It is a useful approach to draw multiple instances of the same plot on different subsets of your dataset. It allows a viewer to quickly extract a large amount of information about a complex dataset. In Seaborn, we will plot multiple graphs in a single window in two ways. First with the help of Facetgrid() function and other by implicit with the help of matplotlib. FacetGrid: FacetGrid is a general way of plotting grids based on a function. It helps in visualizing distribution of one variable as well as the relationship between multiple variables. Its object uses the dataframe as Input and the names of the variables that shape the column, row, or color dimensions of the grid, the syntax is given below: Syntax: seaborn.FacetGrid( data, \*\*kwargs) data: Tidy dataframe where each column is a variable and each row is an observation. \*\*kwargs: It uses many arguments as input such as, i.e. row, col, hue, palette etc. Below is the implementation of above method: Import all Python libraries needed Python3 import seaborn as snsimport numpy as npimport pandas as pdimport matplotlib.pyplot as plt Example 1: Here, we are Initializing the grid like this sets up the matplotlib figure and axes, but doesn’t draw anything on them, we are using the Exercise dataset which is well known dataset available as an inbuilt dataset in seaborn. The basic usage of the class is very similar to FacetGrid. First you initialize the grid, then you pass plotting function to a map method and it will be called on each subplot. Python3 # loading of a dataframe from seabornexercise = sns.load_dataset("exercise") # Form a facetgrid using columnssea = sns.FacetGrid(exercise, col = "time") Output: Example 2: This function will draw the figure and annotate the axes. To make a relational plot, First, you initialize the grid, then you pass the plotting function to a map method and it will be called on each subplot. Python3 # Form a facetgrid using columns with a huesea = sns.FacetGrid(exercise, col = "time", hue = "kind") # map the above form facetgrid with some attributes sea.map(sns.scatterplot, "pulse", "time", alpha = .8) # adding legendsea.add_legend() Output: Example 3: There are several options for controlling the look of the grid that can be passed to the class constructor. Python3 sea = sns.FacetGrid(exercise, row = "diet", col = "time", margin_titles = True) sea.map(sns.regplot, "id", "pulse", color = ".3", fit_reg = False, x_jitter = .1) Output: Example 4: The size of the figure is set by providing the height of each facet, along with the aspect ratio: Python3 sea = sns.FacetGrid(exercise, col = "time", height = 4, aspect =.5) sea.map(sns.barplot, "diet", "pulse", order = ["no fat", "low fat"]) Output: Example 5: The default ordering of the facets is derived from the information in the DataFrame. If the variable used to define facets has a categorical type, then the order of the categories is used. Otherwise, the facets will be in the order of appearance of the category levels. It is possible, however, to specify an ordering of any facet dimension with the appropriate *_order parameter: Python3 exercise_kind = exercise.kind.value_counts().indexsea = sns.FacetGrid(exercise, row = "kind", row_order = exercise_kind, height = 1.7, aspect = 4) sea.map(sns.kdeplot, "id") Output: Example 6: If you have many levels of one variable, you can plot it along the columns but β€œwrap” them so that they span multiple rows. When doing this, you cannot use a row variable. Python3 g = sns.PairGrid(exercise)g.map_diag(sns.histplot)g.map_offdiag(sns.scatterplot) Output: Example 7: In this example, we will see that we can also plot multiplot grid with the help of pairplot() function. This shows the relationship for (n, 2) combination of variable in a DataFrame as a matrix of plots and the diagonal plots are the univariate plots. Python3 # importing packagesimport seabornimport matplotlib.pyplot as plt # loading dataset using seaborndf = seaborn.load_dataset('tips') # pairplot with hue sexseaborn.pairplot(df, hue ='size')plt.show() Output Method 2: Implicit with the help of matplotlib. In this we will learn how to create subplots using matplotlib and seaborn. Import all Python libraries needed Python3 import seaborn as snsimport numpy as npimport pandas as pdimport matplotlib.pyplot as plt # Setting seaborn as default style even# if use only matplotlibsns.set() Example 1: Here, we are Initializing the grid without arguments returns a Figure and a single Axes, which we can unpack using the syntax bellow. Python3 figure, axes = plt.subplots()figure.suptitle('Geeksforgeeks - one axes with no data') Output: Example 2: In this example we create a plot with 1 row and 2 columns, still no data passed i.e. nrows and ncols. If given in this order, we don’t need to type the arg names, just its values. figsize set the total dimension of our figure. sharex and sharey are used to share one or both axes between the charts. Python3 figure, axes = plt.subplots(1, 2, sharex=True, figsize=(10,5))figure.suptitle('Geeksforgeeks')axes[0].set_title('first chart with no data')axes[1].set_title('second chart with no data') Output: Example 3: If you have many levels Python3 figure, axes = plt.subplots(3, 4, sharex=True, figsize=(16,8))figure.suptitle('Geeksforgeeks - 3 x 4 axes with no data') Output Example 4: Here, we are Initializing matplotlib figure and axes, In this example, we are passing required data on them with the help of the Exercise dataset which is a well-known dataset available as an inbuilt dataset in seaborn. By using this method you can plot any number of the multi-plot grid and any style of the graph by implicit rows and columns with the help of matplotlib in seaborn. We are using sns.boxplot here, where we need to set the argument with the correspondent element from the axes variable. Python3 import seaborn as snsimport numpy as npimport pandas as pdimport matplotlib.pyplot as plt fig, axes = plt.subplots(2, 3, figsize=(18, 10)) fig.suptitle('Geeksforgeeks - 2 x 3 axes Box plot with data') iris = sns.load_dataset("iris") sns.boxplot(ax=axes[0, 0], data=iris, x='species', y='petal_width')sns.boxplot(ax=axes[0, 1], data=iris, x='species', y='petal_length')sns.boxplot(ax=axes[0, 2], data=iris, x='species', y='sepal_width')sns.boxplot(ax=axes[1, 0], data=iris, x='species', y='sepal_length')sns.boxplot(ax=axes[1, 1], data=iris, x='species', y='petal_width')sns.boxplot(ax=axes[1, 2], data=iris, x='species', y='petal_length') Output: Example 5: A gridspec() is for a grid of rows and columns with some specified width and height space. The plt.GridSpec object does not create a plot by itself but it is simply a convenient interface that is recognized by the subplot() command. Python3 import matplotlib.pyplot as plt Grid_plot = plt.GridSpec(2, 3, wspace = 0.8, hspace = 0.6) plt.subplot(Grid_plot[0, 0])plt.subplot(Grid_plot[0, 1:])plt.subplot(Grid_plot[1, :2])plt.subplot(Grid_plot[1, 2]) Output: Example 6: Here we’ll create a 3Γ—4 grid of subplot using subplots(), where all axes in the same row share their y-axis scale, and all axes in the same column share their x-axis scale. Python3 import matplotlib.pyplot as plt figure, axes = plt.subplots(3, 4, figsize = (15, 10)) figure.suptitle('Geeksforgeeks - 2 x 3 axes grid plot using subplots') Output: adnanirshad158 Python-Seaborn Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Jan, 2022" }, { "code": null, "e": 63, "s": 28, "text": "Prerequisites: Matplotlib, Seaborn" }, { "code": null, "e": 496, "s": 63, "text": "In this article, we are going to see multi-dimensional plot data, It is a useful approach to draw multiple instances of the same plot on different subsets of your dataset. It allows a viewer to quickly extract a large amount of information about a complex dataset. In Seaborn, we will plot multiple graphs in a single window in two ways. First with the help of Facetgrid() function and other by implicit with the help of matplotlib." }, { "code": null, "e": 840, "s": 496, "text": "FacetGrid: FacetGrid is a general way of plotting grids based on a function. It helps in visualizing distribution of one variable as well as the relationship between multiple variables. Its object uses the dataframe as Input and the names of the variables that shape the column, row, or color dimensions of the grid, the syntax is given below:" }, { "code": null, "e": 885, "s": 840, "text": "Syntax: seaborn.FacetGrid( data, \\*\\*kwargs)" }, { "code": null, "e": 970, "s": 885, "text": "data: Tidy dataframe where each column is a variable and each row is an observation." }, { "code": null, "e": 1056, "s": 970, "text": "\\*\\*kwargs: It uses many arguments as input such as, i.e. row, col, hue, palette etc." }, { "code": null, "e": 1101, "s": 1056, "text": "Below is the implementation of above method:" }, { "code": null, "e": 1136, "s": 1101, "text": "Import all Python libraries needed" }, { "code": null, "e": 1144, "s": 1136, "text": "Python3" }, { "code": "import seaborn as snsimport numpy as npimport pandas as pdimport matplotlib.pyplot as plt", "e": 1234, "s": 1144, "text": null }, { "code": null, "e": 1648, "s": 1234, "text": "Example 1: Here, we are Initializing the grid like this sets up the matplotlib figure and axes, but doesn’t draw anything on them, we are using the Exercise dataset which is well known dataset available as an inbuilt dataset in seaborn. The basic usage of the class is very similar to FacetGrid. First you initialize the grid, then you pass plotting function to a map method and it will be called on each subplot." }, { "code": null, "e": 1656, "s": 1648, "text": "Python3" }, { "code": "# loading of a dataframe from seabornexercise = sns.load_dataset(\"exercise\") # Form a facetgrid using columnssea = sns.FacetGrid(exercise, col = \"time\")", "e": 1809, "s": 1656, "text": null }, { "code": null, "e": 1817, "s": 1809, "text": "Output:" }, { "code": null, "e": 2036, "s": 1817, "text": "Example 2: This function will draw the figure and annotate the axes. To make a relational plot, First, you initialize the grid, then you pass the plotting function to a map method and it will be called on each subplot." }, { "code": null, "e": 2044, "s": 2036, "text": "Python3" }, { "code": "# Form a facetgrid using columns with a huesea = sns.FacetGrid(exercise, col = \"time\", hue = \"kind\") # map the above form facetgrid with some attributes sea.map(sns.scatterplot, \"pulse\", \"time\", alpha = .8) # adding legendsea.add_legend()", "e": 2286, "s": 2044, "text": null }, { "code": null, "e": 2294, "s": 2286, "text": "Output:" }, { "code": null, "e": 2413, "s": 2294, "text": "Example 3: There are several options for controlling the look of the grid that can be passed to the class constructor." }, { "code": null, "e": 2421, "s": 2413, "text": "Python3" }, { "code": "sea = sns.FacetGrid(exercise, row = \"diet\", col = \"time\", margin_titles = True) sea.map(sns.regplot, \"id\", \"pulse\", color = \".3\", fit_reg = False, x_jitter = .1)", "e": 2609, "s": 2421, "text": null }, { "code": null, "e": 2617, "s": 2609, "text": "Output:" }, { "code": null, "e": 2726, "s": 2617, "text": "Example 4: The size of the figure is set by providing the height of each facet, along with the aspect ratio:" }, { "code": null, "e": 2734, "s": 2726, "text": "Python3" }, { "code": "sea = sns.FacetGrid(exercise, col = \"time\", height = 4, aspect =.5) sea.map(sns.barplot, \"diet\", \"pulse\", order = [\"no fat\", \"low fat\"])", "e": 2898, "s": 2734, "text": null }, { "code": null, "e": 2906, "s": 2898, "text": "Output:" }, { "code": null, "e": 3298, "s": 2906, "text": "Example 5: The default ordering of the facets is derived from the information in the DataFrame. If the variable used to define facets has a categorical type, then the order of the categories is used. Otherwise, the facets will be in the order of appearance of the category levels. It is possible, however, to specify an ordering of any facet dimension with the appropriate *_order parameter:" }, { "code": null, "e": 3306, "s": 3298, "text": "Python3" }, { "code": "exercise_kind = exercise.kind.value_counts().indexsea = sns.FacetGrid(exercise, row = \"kind\", row_order = exercise_kind, height = 1.7, aspect = 4) sea.map(sns.kdeplot, \"id\")", "e": 3518, "s": 3306, "text": null }, { "code": null, "e": 3526, "s": 3518, "text": "Output:" }, { "code": null, "e": 3709, "s": 3526, "text": "Example 6: If you have many levels of one variable, you can plot it along the columns but β€œwrap” them so that they span multiple rows. When doing this, you cannot use a row variable." }, { "code": null, "e": 3717, "s": 3709, "text": "Python3" }, { "code": "g = sns.PairGrid(exercise)g.map_diag(sns.histplot)g.map_offdiag(sns.scatterplot)", "e": 3798, "s": 3717, "text": null }, { "code": null, "e": 3806, "s": 3798, "text": "Output:" }, { "code": null, "e": 3817, "s": 3806, "text": "Example 7:" }, { "code": null, "e": 4069, "s": 3817, "text": "In this example, we will see that we can also plot multiplot grid with the help of pairplot() function. This shows the relationship for (n, 2) combination of variable in a DataFrame as a matrix of plots and the diagonal plots are the univariate plots." }, { "code": null, "e": 4077, "s": 4069, "text": "Python3" }, { "code": "# importing packagesimport seabornimport matplotlib.pyplot as plt # loading dataset using seaborndf = seaborn.load_dataset('tips') # pairplot with hue sexseaborn.pairplot(df, hue ='size')plt.show()", "e": 4275, "s": 4077, "text": null }, { "code": null, "e": 4282, "s": 4275, "text": "Output" }, { "code": null, "e": 4330, "s": 4282, "text": "Method 2: Implicit with the help of matplotlib." }, { "code": null, "e": 4405, "s": 4330, "text": "In this we will learn how to create subplots using matplotlib and seaborn." }, { "code": null, "e": 4440, "s": 4405, "text": "Import all Python libraries needed" }, { "code": null, "e": 4448, "s": 4440, "text": "Python3" }, { "code": "import seaborn as snsimport numpy as npimport pandas as pdimport matplotlib.pyplot as plt # Setting seaborn as default style even# if use only matplotlibsns.set()", "e": 4611, "s": 4448, "text": null }, { "code": null, "e": 4756, "s": 4611, "text": "Example 1: Here, we are Initializing the grid without arguments returns a Figure and a single Axes, which we can unpack using the syntax bellow." }, { "code": null, "e": 4764, "s": 4756, "text": "Python3" }, { "code": "figure, axes = plt.subplots()figure.suptitle('Geeksforgeeks - one axes with no data')", "e": 4850, "s": 4764, "text": null }, { "code": null, "e": 4858, "s": 4850, "text": "Output:" }, { "code": null, "e": 5050, "s": 4858, "text": "Example 2: In this example we create a plot with 1 row and 2 columns, still no data passed i.e. nrows and ncols. If given in this order, we don’t need to type the arg names, just its values. " }, { "code": null, "e": 5097, "s": 5050, "text": "figsize set the total dimension of our figure." }, { "code": null, "e": 5170, "s": 5097, "text": "sharex and sharey are used to share one or both axes between the charts." }, { "code": null, "e": 5178, "s": 5170, "text": "Python3" }, { "code": "figure, axes = plt.subplots(1, 2, sharex=True, figsize=(10,5))figure.suptitle('Geeksforgeeks')axes[0].set_title('first chart with no data')axes[1].set_title('second chart with no data')", "e": 5364, "s": 5178, "text": null }, { "code": null, "e": 5372, "s": 5364, "text": "Output:" }, { "code": null, "e": 5408, "s": 5372, "text": "Example 3: If you have many levels " }, { "code": null, "e": 5416, "s": 5408, "text": "Python3" }, { "code": "figure, axes = plt.subplots(3, 4, sharex=True, figsize=(16,8))figure.suptitle('Geeksforgeeks - 3 x 4 axes with no data')", "e": 5537, "s": 5416, "text": null }, { "code": null, "e": 5544, "s": 5537, "text": "Output" }, { "code": null, "e": 6059, "s": 5544, "text": "Example 4: Here, we are Initializing matplotlib figure and axes, In this example, we are passing required data on them with the help of the Exercise dataset which is a well-known dataset available as an inbuilt dataset in seaborn. By using this method you can plot any number of the multi-plot grid and any style of the graph by implicit rows and columns with the help of matplotlib in seaborn. We are using sns.boxplot here, where we need to set the argument with the correspondent element from the axes variable." }, { "code": null, "e": 6067, "s": 6059, "text": "Python3" }, { "code": "import seaborn as snsimport numpy as npimport pandas as pdimport matplotlib.pyplot as plt fig, axes = plt.subplots(2, 3, figsize=(18, 10)) fig.suptitle('Geeksforgeeks - 2 x 3 axes Box plot with data') iris = sns.load_dataset(\"iris\") sns.boxplot(ax=axes[0, 0], data=iris, x='species', y='petal_width')sns.boxplot(ax=axes[0, 1], data=iris, x='species', y='petal_length')sns.boxplot(ax=axes[0, 2], data=iris, x='species', y='sepal_width')sns.boxplot(ax=axes[1, 0], data=iris, x='species', y='sepal_length')sns.boxplot(ax=axes[1, 1], data=iris, x='species', y='petal_width')sns.boxplot(ax=axes[1, 2], data=iris, x='species', y='petal_length')", "e": 6707, "s": 6067, "text": null }, { "code": null, "e": 6715, "s": 6707, "text": "Output:" }, { "code": null, "e": 6959, "s": 6715, "text": "Example 5: A gridspec() is for a grid of rows and columns with some specified width and height space. The plt.GridSpec object does not create a plot by itself but it is simply a convenient interface that is recognized by the subplot() command." }, { "code": null, "e": 6967, "s": 6959, "text": "Python3" }, { "code": "import matplotlib.pyplot as plt Grid_plot = plt.GridSpec(2, 3, wspace = 0.8, hspace = 0.6) plt.subplot(Grid_plot[0, 0])plt.subplot(Grid_plot[0, 1:])plt.subplot(Grid_plot[1, :2])plt.subplot(Grid_plot[1, 2])", "e": 7197, "s": 6967, "text": null }, { "code": null, "e": 7205, "s": 7197, "text": "Output:" }, { "code": null, "e": 7389, "s": 7205, "text": "Example 6: Here we’ll create a 3Γ—4 grid of subplot using subplots(), where all axes in the same row share their y-axis scale, and all axes in the same column share their x-axis scale." }, { "code": null, "e": 7397, "s": 7389, "text": "Python3" }, { "code": "import matplotlib.pyplot as plt figure, axes = plt.subplots(3, 4, figsize = (15, 10)) figure.suptitle('Geeksforgeeks - 2 x 3 axes grid plot using subplots')", "e": 7581, "s": 7397, "text": null }, { "code": null, "e": 7589, "s": 7581, "text": "Output:" }, { "code": null, "e": 7604, "s": 7589, "text": "adnanirshad158" }, { "code": null, "e": 7619, "s": 7604, "text": "Python-Seaborn" }, { "code": null, "e": 7626, "s": 7619, "text": "Python" } ]
COBOL - Loop Statements
There are some tasks that need to be done over and over again like reading each record of a file till its end. The loop statements used in COBOL are βˆ’ Perform Thru Perform Until Perform Times Perform Varying Perform Thru is used to execute a series of paragraph by giving the first and last paragraph names in the sequence. After executing the last paragraph, the control is returned back. Statements inside the PERFORM will be executed till END-PERFORM is reached. Following is the syntax of In-line perform βˆ’ PERFORM DISPLAY 'HELLO WORLD' END-PERFORM. Here, a statement is executed in one paragraph and then the control is transferred to other paragraph or section. Following is the syntax of Out-of-line perform βˆ’ PERFORM PARAGRAPH1 THRU PARAGRAPH2 Example IDENTIFICATION DIVISION. PROGRAM-ID. HELLO. PROCEDURE DIVISION. A-PARA. PERFORM DISPLAY 'IN A-PARA' END-PERFORM. PERFORM C-PARA THRU E-PARA. B-PARA. DISPLAY 'IN B-PARA'. STOP RUN. C-PARA. DISPLAY 'IN C-PARA'. D-PARA. DISPLAY 'IN D-PARA'. E-PARA. DISPLAY 'IN E-PARA'. JCL to execute the above COBOL program. //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C //STEP1 EXEC PGM = HELLO When you compile and execute the above program, it produces the following result βˆ’ IN A-PARA IN C-PARA IN D-PARA IN E-PARA IN B-PARA In β€˜perform until’, a paragraph is executed until the given condition becomes true. β€˜With test before’ is the default condition and it indicates that the condition is checked before the execution of statements in a paragraph. Following is the syntax of perform until βˆ’ PERFORM A-PARA UNTIL COUNT=5 PERFORM A-PARA WITH TEST BEFORE UNTIL COUNT=5 PERFORM A-PARA WITH TEST AFTER UNTIL COUNT=5 Example IDENTIFICATION DIVISION. PROGRAM-ID. HELLO. DATA DIVISION. WORKING-STORAGE SECTION. 01 WS-CNT PIC 9(1) VALUE 0. PROCEDURE DIVISION. A-PARA. PERFORM B-PARA WITH TEST AFTER UNTIL WS-CNT>3. STOP RUN. B-PARA. DISPLAY 'WS-CNT : 'WS-CNT. ADD 1 TO WS-CNT. JCL to execute the above COBOL program βˆ’ //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C //STEP1 EXEC PGM = HELLO When you compile and execute the above program, it produces the following result βˆ’ WS-CNT : 0 WS-CNT : 1 WS-CNT : 2 WS-CNT : 3 In β€˜perform times’, a paragraph will be executed the number of times specified. Following is the syntax of perform times βˆ’ PERFORM A-PARA 5 TIMES. Example IDENTIFICATION DIVISION. PROGRAM-ID. HELLO. PROCEDURE DIVISION. A-PARA. PERFORM B-PARA 3 TIMES. STOP RUN. B-PARA. DISPLAY 'IN B-PARA'. JCL to execute the above COBOL program βˆ’ //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C //STEP1 EXEC PGM = HELLO When you compile and execute the above program, it produces the following result βˆ’ IN B-PARA IN B-PARA IN B-PARA In perform varying, a paragraph will be executed till the condition in Until phrase becomes true. Following is the syntax of perform varying βˆ’ PERFORM A-PARA VARYING A FROM 1 BY 1 UNTIL A = 5. Example IDENTIFICATION DIVISION. PROGRAM-ID. HELLO. DATA DIVISION. WORKING-STORAGE SECTION. 01 WS-A PIC 9 VALUE 0. PROCEDURE DIVISION. A-PARA. PERFORM B-PARA VARYING WS-A FROM 1 BY 1 UNTIL WS-A=5 STOP RUN. B-PARA. DISPLAY 'IN B-PARA ' WS-A. JCL to execute the above COBOL program βˆ’ //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C //STEP1 EXEC PGM = HELLO When you compile and execute the above program, it produces the following result βˆ’ IN B-PARA 1 IN B-PARA 2 IN B-PARA 3 IN B-PARA 4 GO TO statement is used to change the flow of execution in a program. In GO TO statements, transfer goes only in the forward direction. It is used to exit a paragraph. The different types of GO TO statements used are as follows βˆ’ GO TO para-name. GO TO para-1 para-2 para-3 DEPENDING ON x. If 'x' is equal to 1, then the control will be transferred to the first paragraph; and if 'x' is equal to 2, then the control will be transferred to the second paragraph, and so on. Example IDENTIFICATION DIVISION. PROGRAM-ID. HELLO. DATA DIVISION. WORKING-STORAGE SECTION. 01 WS-A PIC 9 VALUE 2. PROCEDURE DIVISION. A-PARA. DISPLAY 'IN A-PARA' GO TO B-PARA. B-PARA. DISPLAY 'IN B-PARA '. GO TO C-PARA D-PARA DEPENDING ON WS-A. C-PARA. DISPLAY 'IN C-PARA '. D-PARA. DISPLAY 'IN D-PARA '. STOP RUN. JCL to execute the above COBOL program: //SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C //STEP1 EXEC PGM = HELLO When you compile and execute the above program, it produces the following result:
[ { "code": null, "e": 2307, "s": 2156, "text": "There are some tasks that need to be done over and over again like reading each record of a file till its end. The loop statements used in COBOL are βˆ’" }, { "code": null, "e": 2320, "s": 2307, "text": "Perform Thru" }, { "code": null, "e": 2334, "s": 2320, "text": "Perform Until" }, { "code": null, "e": 2348, "s": 2334, "text": "Perform Times" }, { "code": null, "e": 2364, "s": 2348, "text": "Perform Varying" }, { "code": null, "e": 2546, "s": 2364, "text": "Perform Thru is used to execute a series of paragraph by giving the first and last paragraph names in the sequence. After executing the last paragraph, the control is returned back." }, { "code": null, "e": 2622, "s": 2546, "text": "Statements inside the PERFORM will be executed till END-PERFORM is reached." }, { "code": null, "e": 2667, "s": 2622, "text": "Following is the syntax of In-line perform βˆ’" }, { "code": null, "e": 2715, "s": 2667, "text": "PERFORM \n DISPLAY 'HELLO WORLD'\nEND-PERFORM.\n" }, { "code": null, "e": 2829, "s": 2715, "text": "Here, a statement is executed in one paragraph and then the control is transferred to other paragraph or section." }, { "code": null, "e": 2878, "s": 2829, "text": "Following is the syntax of Out-of-line perform βˆ’" }, { "code": null, "e": 2914, "s": 2878, "text": "PERFORM PARAGRAPH1 THRU PARAGRAPH2\n" }, { "code": null, "e": 2922, "s": 2914, "text": "Example" }, { "code": null, "e": 3245, "s": 2922, "text": "IDENTIFICATION DIVISION.\nPROGRAM-ID. HELLO.\n\nPROCEDURE DIVISION.\n A-PARA.\n PERFORM DISPLAY 'IN A-PARA'\n END-PERFORM.\n PERFORM C-PARA THRU E-PARA.\n \n B-PARA.\n DISPLAY 'IN B-PARA'.\n STOP RUN.\n \n C-PARA.\n DISPLAY 'IN C-PARA'.\n \n D-PARA.\n DISPLAY 'IN D-PARA'.\n \n E-PARA.\n DISPLAY 'IN E-PARA'." }, { "code": null, "e": 3285, "s": 3245, "text": "JCL to execute the above COBOL program." }, { "code": null, "e": 3362, "s": 3285, "text": "//SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C\n//STEP1 EXEC PGM = HELLO" }, { "code": null, "e": 3445, "s": 3362, "text": "When you compile and execute the above program, it produces the following result βˆ’" }, { "code": null, "e": 3496, "s": 3445, "text": "IN A-PARA\nIN C-PARA\nIN D-PARA\nIN E-PARA\nIN B-PARA\n" }, { "code": null, "e": 3722, "s": 3496, "text": "In β€˜perform until’, a paragraph is executed until the given condition becomes true. β€˜With test before’ is the default condition and it indicates that the condition is checked before the execution of statements in a paragraph." }, { "code": null, "e": 3765, "s": 3722, "text": "Following is the syntax of perform until βˆ’" }, { "code": null, "e": 3887, "s": 3765, "text": "PERFORM A-PARA UNTIL COUNT=5\n\nPERFORM A-PARA WITH TEST BEFORE UNTIL COUNT=5\n\nPERFORM A-PARA WITH TEST AFTER UNTIL COUNT=5" }, { "code": null, "e": 3895, "s": 3887, "text": "Example" }, { "code": null, "e": 4175, "s": 3895, "text": "IDENTIFICATION DIVISION.\nPROGRAM-ID. HELLO.\n\nDATA DIVISION.\n WORKING-STORAGE SECTION.\n 01 WS-CNT PIC 9(1) VALUE 0. \n\nPROCEDURE DIVISION.\n A-PARA.\n PERFORM B-PARA WITH TEST AFTER UNTIL WS-CNT>3.\n STOP RUN.\n \n B-PARA.\n DISPLAY 'WS-CNT : 'WS-CNT.\n ADD 1 TO WS-CNT." }, { "code": null, "e": 4216, "s": 4175, "text": "JCL to execute the above COBOL program βˆ’" }, { "code": null, "e": 4293, "s": 4216, "text": "//SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C\n//STEP1 EXEC PGM = HELLO" }, { "code": null, "e": 4376, "s": 4293, "text": "When you compile and execute the above program, it produces the following result βˆ’" }, { "code": null, "e": 4421, "s": 4376, "text": "WS-CNT : 0\nWS-CNT : 1\nWS-CNT : 2\nWS-CNT : 3\n" }, { "code": null, "e": 4501, "s": 4421, "text": "In β€˜perform times’, a paragraph will be executed the number of times specified." }, { "code": null, "e": 4544, "s": 4501, "text": "Following is the syntax of perform times βˆ’" }, { "code": null, "e": 4569, "s": 4544, "text": "PERFORM A-PARA 5 TIMES.\n" }, { "code": null, "e": 4577, "s": 4569, "text": "Example" }, { "code": null, "e": 4732, "s": 4577, "text": "IDENTIFICATION DIVISION.\nPROGRAM-ID. HELLO.\n\nPROCEDURE DIVISION.\n A-PARA.\n PERFORM B-PARA 3 TIMES.\n STOP RUN.\n \n B-PARA.\n DISPLAY 'IN B-PARA'." }, { "code": null, "e": 4773, "s": 4732, "text": "JCL to execute the above COBOL program βˆ’" }, { "code": null, "e": 4850, "s": 4773, "text": "//SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C\n//STEP1 EXEC PGM = HELLO" }, { "code": null, "e": 4933, "s": 4850, "text": "When you compile and execute the above program, it produces the following result βˆ’" }, { "code": null, "e": 4964, "s": 4933, "text": "IN B-PARA\nIN B-PARA\nIN B-PARA\n" }, { "code": null, "e": 5062, "s": 4964, "text": "In perform varying, a paragraph will be executed till the condition in Until phrase becomes true." }, { "code": null, "e": 5107, "s": 5062, "text": "Following is the syntax of perform varying βˆ’" }, { "code": null, "e": 5158, "s": 5107, "text": "PERFORM A-PARA VARYING A FROM 1 BY 1 UNTIL A = 5.\n" }, { "code": null, "e": 5166, "s": 5158, "text": "Example" }, { "code": null, "e": 5426, "s": 5166, "text": "IDENTIFICATION DIVISION.\nPROGRAM-ID. HELLO.\n\nDATA DIVISION.\n WORKING-STORAGE SECTION.\n 01 WS-A PIC 9 VALUE 0.\n\nPROCEDURE DIVISION.\n A-PARA.\n PERFORM B-PARA VARYING WS-A FROM 1 BY 1 UNTIL WS-A=5\n STOP RUN.\n \n B-PARA.\n DISPLAY 'IN B-PARA ' WS-A." }, { "code": null, "e": 5467, "s": 5426, "text": "JCL to execute the above COBOL program βˆ’" }, { "code": null, "e": 5544, "s": 5467, "text": "//SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C\n//STEP1 EXEC PGM = HELLO" }, { "code": null, "e": 5627, "s": 5544, "text": "When you compile and execute the above program, it produces the following result βˆ’" }, { "code": null, "e": 5676, "s": 5627, "text": "IN B-PARA 1\nIN B-PARA 2\nIN B-PARA 3\nIN B-PARA 4\n" }, { "code": null, "e": 5906, "s": 5676, "text": "GO TO statement is used to change the flow of execution in a program. In GO TO statements, transfer goes only in the forward direction. It is used to exit a paragraph. The different types of GO TO statements used are as follows βˆ’" }, { "code": null, "e": 5924, "s": 5906, "text": "GO TO para-name.\n" }, { "code": null, "e": 5968, "s": 5924, "text": "GO TO para-1 para-2 para-3 DEPENDING ON x.\n" }, { "code": null, "e": 6150, "s": 5968, "text": "If 'x' is equal to 1, then the control will be transferred to the first paragraph; and if 'x' is equal to 2, then the control will be transferred to the second paragraph, and so on." }, { "code": null, "e": 6158, "s": 6150, "text": "Example" }, { "code": null, "e": 6522, "s": 6158, "text": "IDENTIFICATION DIVISION.\nPROGRAM-ID. HELLO.\n\nDATA DIVISION.\n WORKING-STORAGE SECTION.\n 01 WS-A PIC 9 VALUE 2.\n \nPROCEDURE DIVISION.\n A-PARA.\n DISPLAY 'IN A-PARA'\n GO TO B-PARA.\n \n B-PARA.\n DISPLAY 'IN B-PARA '.\n GO TO C-PARA D-PARA DEPENDING ON WS-A.\n \n C-PARA.\n DISPLAY 'IN C-PARA '.\n \n D-PARA.\n DISPLAY 'IN D-PARA '.\n STOP RUN." }, { "code": null, "e": 6562, "s": 6522, "text": "JCL to execute the above COBOL program:" }, { "code": null, "e": 6639, "s": 6562, "text": "//SAMPLE JOB(TESTJCL,XXXXXX),CLASS = A,MSGCLASS = C\n//STEP1 EXEC PGM = HELLO" } ]
Working With the EditText in Android
10 Jun, 2021 EditText is one of the basic UI widgets, which is used to take the input from the user. The EditText is derived or is the extension of the TextView in Android. This article its been discussed in detail about the EditText in Android. The article also contains some of the redirections to other articles, also refer to them to get the detailed perspective of the EditText widget in Android. Have a look at the following list to get an idea of the overall discussion. Input Type for the EditTextGetting the data or retrieving the data entered by the userInput Data CustomizationAdding hints for the placeholderChange the stroke colorChange the highlighted color inside the EditTextEvent Listener for the EditTextError Message for the EditText filedImplementing Password visibility toggleCharacter counting using Material Design EditText Input Type for the EditText Getting the data or retrieving the data entered by the user Input Data Customization Adding hints for the placeholder Change the stroke color Change the highlighted color inside the EditText Event Listener for the EditText Error Message for the EditText filed Implementing Password visibility toggle Character counting using Material Design EditText Step 1: Create an empty activity project Create an empty activity Android Studio project. Refer to How to Create/Start a New Project in Android Studio, to know how to create an empty activity Android project. Step 2: Working with the activity_main.xml file The main layout of the application contains the EditText Widget and two buttons. To implement the UI invoke the following code inside the activity_main.xml file. To get an idea about how the basic EditText in android looks like. XML <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" tools:ignore="HardcodedText"> <EditText android:id="@+id/editText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginEnd="16dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.321" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:backgroundTint="@color/green_500" android:text="SUBMIT" android:textColor="@color/white" app:layout_constraintEnd_toEndOf="@+id/editText" app:layout_constraintTop_toBottomOf="@+id/editText" /> <Button style="@style/Widget.AppCompat.Button.Borderless" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:layout_marginEnd="8dp" android:backgroundTint="@color/green_500" android:text="CANCEL" android:textColor="@color/green_500" app:layout_constraintEnd_toStartOf="@+id/button" app:layout_constraintTop_toBottomOf="@+id/editText" /> </androidx.constraintlayout.widget.ConstraintLayout> Output UI: This is one of the attributes which is needed to be specified under the EditText widget. Which defines the type of data to be entered by the user. The following are attributes which are needed to be invoked and refer to its output to get a clear understanding. InputType Attribute Type of the Data which is entered Refer to the following code, which contains only the phone as the input type, for demonstration purposes. Which the value of that can be replaced with the values mentioned in the above table. XML <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" tools:ignore="HardcodedText"> <!--the values mentioned in the table are to be invoked inside the inputType attribute--> <EditText android:id="@+id/editText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginEnd="16dp" android:inputType="phone" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.321" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:backgroundTint="@color/green_500" android:text="SUBMIT" android:textColor="@color/white" app:layout_constraintEnd_toEndOf="@+id/editText" app:layout_constraintTop_toBottomOf="@+id/editText" /> <Button style="@style/Widget.AppCompat.Button.Borderless" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:layout_marginEnd="8dp" android:backgroundTint="@color/green_500" android:text="CANCEL" android:textColor="@color/green_500" app:layout_constraintEnd_toStartOf="@+id/button" app:layout_constraintTop_toBottomOf="@+id/editText" /> </androidx.constraintlayout.widget.ConstraintLayout> Output: To get the data entered by the user, firstly the EditText widget has to be invoked with the id. which is used to point to the unique widgets in android. Provide the EditText with the id, by referring to the following code, which has to be invoked inside the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" tools:ignore="HardcodedText"> <EditText android:id="@+id/editText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginEnd="16dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.321" /> <Button android:id="@+id/submitButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:backgroundTint="@color/green_500" android:text="SUBMIT" android:textColor="@color/white" app:layout_constraintEnd_toEndOf="@+id/editText" app:layout_constraintTop_toBottomOf="@+id/editText" /> <Button android:id="@+id/cancelButton" style="@style/Widget.AppCompat.Button.Borderless" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:layout_marginEnd="8dp" android:backgroundTint="@color/green_500" android:text="CANCEL" android:textColor="@color/green_500" app:layout_constraintEnd_toStartOf="@+id/submitButton" app:layout_constraintTop_toBottomOf="@+id/editText" /> </androidx.constraintlayout.widget.ConstraintLayout> The following code needs to be invoked inside the MainActivity.kt file. Which performs the retrieving operation and provides the Toast message the same as the entered data. There is one scenario, if the user left the EditText blank, it has to be checked whether it’s blank or not. To check whether it is blank EditText. Kotlin Java import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Buttonimport android.widget.EditTextimport android.widget.Toast class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // register editText with instance val editText: EditText = findViewById(R.id.editText) // also register the submit button with the appropriate id val submitButton: Button = findViewById(R.id.submitButton) // handle the button with the onClickListener submitButton.setOnClickListener { // get the data with the "editText.text.toString()" val enteredData: String = editText.text.toString() // check whether the retrieved data is empty or not // based on the emptiness provide the Toast Message if (enteredData.isEmpty()) { Toast.makeText(applicationContext, "Please Enter the Data", Toast.LENGTH_SHORT) .show() } else { Toast.makeText(applicationContext, enteredData, Toast.LENGTH_SHORT).show() } } }} import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast;import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { EditText editText; Button submitButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // register editText with instance editText = (EditText) findViewById(R.id.editText); // also register the submit button with the appropriate id submitButton = (Button) findViewById(R.id.submitButton); // handle the button with the onClickListener submitButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { // get the data with the // "editText.text.toString()" String enteredData = editText.getText().toString(); // check whether the retrieved data is // empty or not based on the emptiness // provide the Toast Message if (enteredData.isEmpty()) { Toast.makeText(getApplicationContext(), "Please Enter the Data", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getApplicationContext(), enteredData, Toast.LENGTH_SHORT).show(); } } }); }} Output: The EditText allows developers to make restrictions for the amount of data to be entered by the user. For example, the number of characters entered can be restricted, or the number of lines can be restricted, or the number of digits can be restricted. Following are some of the attributes: Input only particular numbers -> The following attribute takes only the digits 5 & 6 as input and no other numbers can be entered by the user. digits=”56β€²β€²inputType=”number” digits=”56β€²β€² inputType=”number” Restrict the number of characters of the input -> The following attribute makes user to enter only 6 number of characters. maxLength=”6β€²β€² maxLength=”6β€²β€² Restrict the number of lines of input -> The following attribute makes user restricted to only single line, in which the EditText do not expand if the amount of the data gets more than single line. lines=”1β€²β€²maxLines=”1β€²β€² lines=”1β€²β€² maxLines=”1β€²β€² Following is the example of the numberPassword with only 6 digits as maxLength. XML <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" tools:ignore="HardcodedText"> <EditText android:id="@+id/editText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginEnd="16dp" android:inputType="numberPassword" android:maxLength="6" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.321" /> <Button android:id="@+id/submitButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:backgroundTint="@color/green_500" android:text="SUBMIT" android:textColor="@color/white" app:layout_constraintEnd_toEndOf="@+id/editText" app:layout_constraintTop_toBottomOf="@+id/editText" /> <Button android:id="@+id/cancelButton" style="@style/Widget.AppCompat.Button.Borderless" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:layout_marginEnd="8dp" android:backgroundTint="@color/green_500" android:text="CANCEL" android:textColor="@color/green_500" app:layout_constraintEnd_toStartOf="@+id/submitButton" app:layout_constraintTop_toBottomOf="@+id/editText" /> </androidx.constraintlayout.widget.ConstraintLayout> Output: The hints for the EditText give confidence to the user, on what the data they have to enter into the EditText. The attribute which is used to provide the hint text for the EditText is: android:hint=”First and Last Name” Refer to the following code and its output for better understanding. XML <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" tools:ignore="HardcodedText"> <EditText android:id="@+id/editText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginEnd="16dp" android:hint="First and Last Name" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.321" /> <Button android:id="@+id/submitButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:backgroundTint="@color/green_500" android:text="SUBMIT" android:textColor="@color/white" app:layout_constraintEnd_toEndOf="@+id/editText" app:layout_constraintTop_toBottomOf="@+id/editText" /> <Button android:id="@+id/cancelButton" style="@style/Widget.AppCompat.Button.Borderless" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:layout_marginEnd="8dp" android:backgroundTint="@color/green_500" android:text="CANCEL" android:textColor="@color/green_500" app:layout_constraintEnd_toStartOf="@+id/submitButton" app:layout_constraintTop_toBottomOf="@+id/editText" /> </androidx.constraintlayout.widget.ConstraintLayout> Output: The stroke color which appears when it is in focus can also be changed, by the following attribute android:backgroundTint=”colorValue” Refer to the following code and its output, for better understanding. XML <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" tools:ignore="HardcodedText"> <EditText android:id="@+id/editText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginEnd="16dp" android:backgroundTint="@android:color/holo_red_dark" android:hint="First and Last Name" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.321" /> <Button android:id="@+id/submitButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:backgroundTint="@color/green_500" android:text="SUBMIT" android:textColor="@color/white" app:layout_constraintEnd_toEndOf="@+id/editText" app:layout_constraintTop_toBottomOf="@+id/editText" /> <Button android:id="@+id/cancelButton" style="@style/Widget.AppCompat.Button.Borderless" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:layout_marginEnd="8dp" android:backgroundTint="@color/green_500" android:text="CANCEL" android:textColor="@color/green_500" app:layout_constraintEnd_toStartOf="@+id/submitButton" app:layout_constraintTop_toBottomOf="@+id/editText" /> </androidx.constraintlayout.widget.ConstraintLayout> Output: The text inside the EditText gets highlighted when the user selects the particular text from it. The color of the highlighted text inside the EditText can be changed using the following attribute. android:textColorHighlight=”colorValue” Refer to the following code and its output for better understanding. XML <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" tools:ignore="HardcodedText"> <EditText android:id="@+id/editText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginEnd="16dp" android:textColorHighlight="@android:color/holo_orange_light" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.321" /> <Button android:id="@+id/submitButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:backgroundTint="@color/green_500" android:text="SUBMIT" android:textColor="@color/white" app:layout_constraintEnd_toEndOf="@+id/editText" app:layout_constraintTop_toBottomOf="@+id/editText" /> <Button android:id="@+id/cancelButton" style="@style/Widget.AppCompat.Button.Borderless" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:layout_marginEnd="8dp" android:backgroundTint="@color/green_500" android:text="CANCEL" android:textColor="@color/green_500" app:layout_constraintEnd_toStartOf="@+id/submitButton" app:layout_constraintTop_toBottomOf="@+id/editText" /> </androidx.constraintlayout.widget.ConstraintLayout> Output: Event listeners for the EditText can also be implemented to perform particular actions. Refer to the How to Implement TextWatcher in Android? If the user misses out on any of the EditText or left the EditText blank without inputting any data, the user has to be alerted with the error message. To implement such functionality, refer to Implement Form Validation (Error to EditText) in Android Implement the password visibility toggle for the EditText by referring to How to Toggle Password Visibility in Android?. Invoke the following dependency to access the Material Design components. implementation β€˜com.google.android.material:material:1.2.1’ The following attributes are to be invoked inside the TextInputLayout app:counterEnabled=”true” app:counterMaxLength=”6β€²β€² Refer to the following code and its output for better understanding. XML <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" tools:ignore="HardcodedText"> <com.google.android.material.textfield.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="32dp" android:layout_marginEnd="16dp" android:hint="Enter Something" app:counterEnabled="true" app:counterMaxLength="6" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent"> <com.google.android.material.textfield.TextInputEditText android:layout_width="match_parent" android:layout_height="wrap_content" /> </com.google.android.material.textfield.TextInputLayout> </androidx.constraintlayout.widget.ConstraintLayout> Output: raghav14 sooda367 android Android-View Technical Scripter 2020 Android Kotlin Technical Scripter Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Add Views Dynamically and Store Data in Arraylist in Android? Android SDK and it's Components Flutter - Custom Bottom Navigation Bar How to Communicate Between Fragments in Android? Retrofit with Kotlin Coroutine in Android How to Add Views Dynamically and Store Data in Arraylist in Android? Android UI Layouts Kotlin Array How to Communicate Between Fragments in Android? Retrofit with Kotlin Coroutine in Android
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Jun, 2021" }, { "code": null, "e": 493, "s": 28, "text": "EditText is one of the basic UI widgets, which is used to take the input from the user. The EditText is derived or is the extension of the TextView in Android. This article its been discussed in detail about the EditText in Android. The article also contains some of the redirections to other articles, also refer to them to get the detailed perspective of the EditText widget in Android. Have a look at the following list to get an idea of the overall discussion." }, { "code": null, "e": 862, "s": 493, "text": "Input Type for the EditTextGetting the data or retrieving the data entered by the userInput Data CustomizationAdding hints for the placeholderChange the stroke colorChange the highlighted color inside the EditTextEvent Listener for the EditTextError Message for the EditText filedImplementing Password visibility toggleCharacter counting using Material Design EditText" }, { "code": null, "e": 890, "s": 862, "text": "Input Type for the EditText" }, { "code": null, "e": 950, "s": 890, "text": "Getting the data or retrieving the data entered by the user" }, { "code": null, "e": 975, "s": 950, "text": "Input Data Customization" }, { "code": null, "e": 1008, "s": 975, "text": "Adding hints for the placeholder" }, { "code": null, "e": 1032, "s": 1008, "text": "Change the stroke color" }, { "code": null, "e": 1081, "s": 1032, "text": "Change the highlighted color inside the EditText" }, { "code": null, "e": 1113, "s": 1081, "text": "Event Listener for the EditText" }, { "code": null, "e": 1150, "s": 1113, "text": "Error Message for the EditText filed" }, { "code": null, "e": 1190, "s": 1150, "text": "Implementing Password visibility toggle" }, { "code": null, "e": 1240, "s": 1190, "text": "Character counting using Material Design EditText" }, { "code": null, "e": 1281, "s": 1240, "text": "Step 1: Create an empty activity project" }, { "code": null, "e": 1449, "s": 1281, "text": "Create an empty activity Android Studio project. Refer to How to Create/Start a New Project in Android Studio, to know how to create an empty activity Android project." }, { "code": null, "e": 1497, "s": 1449, "text": "Step 2: Working with the activity_main.xml file" }, { "code": null, "e": 1726, "s": 1497, "text": "The main layout of the application contains the EditText Widget and two buttons. To implement the UI invoke the following code inside the activity_main.xml file. To get an idea about how the basic EditText in android looks like." }, { "code": null, "e": 1730, "s": 1726, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\" tools:ignore=\"HardcodedText\"> <EditText android:id=\"@+id/editText\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"16dp\" android:layout_marginEnd=\"16dp\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" app:layout_constraintVertical_bias=\"0.321\" /> <Button android:id=\"@+id/button\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"16dp\" android:backgroundTint=\"@color/green_500\" android:text=\"SUBMIT\" android:textColor=\"@color/white\" app:layout_constraintEnd_toEndOf=\"@+id/editText\" app:layout_constraintTop_toBottomOf=\"@+id/editText\" /> <Button style=\"@style/Widget.AppCompat.Button.Borderless\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"16dp\" android:layout_marginEnd=\"8dp\" android:backgroundTint=\"@color/green_500\" android:text=\"CANCEL\" android:textColor=\"@color/green_500\" app:layout_constraintEnd_toStartOf=\"@+id/button\" app:layout_constraintTop_toBottomOf=\"@+id/editText\" /> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 3539, "s": 1730, "text": null }, { "code": null, "e": 3554, "s": 3543, "text": "Output UI:" }, { "code": null, "e": 3703, "s": 3556, "text": "This is one of the attributes which is needed to be specified under the EditText widget. Which defines the type of data to be entered by the user." }, { "code": null, "e": 3817, "s": 3703, "text": "The following are attributes which are needed to be invoked and refer to its output to get a clear understanding." }, { "code": null, "e": 3837, "s": 3817, "text": "InputType Attribute" }, { "code": null, "e": 3872, "s": 3837, "text": "Type of the Data which is entered" }, { "code": null, "e": 4064, "s": 3872, "text": "Refer to the following code, which contains only the phone as the input type, for demonstration purposes. Which the value of that can be replaced with the values mentioned in the above table." }, { "code": null, "e": 4070, "s": 4066, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\" tools:ignore=\"HardcodedText\"> <!--the values mentioned in the table are to be invoked inside the inputType attribute--> <EditText android:id=\"@+id/editText\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"16dp\" android:layout_marginEnd=\"16dp\" android:inputType=\"phone\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" app:layout_constraintVertical_bias=\"0.321\" /> <Button android:id=\"@+id/button\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"16dp\" android:backgroundTint=\"@color/green_500\" android:text=\"SUBMIT\" android:textColor=\"@color/white\" app:layout_constraintEnd_toEndOf=\"@+id/editText\" app:layout_constraintTop_toBottomOf=\"@+id/editText\" /> <Button style=\"@style/Widget.AppCompat.Button.Borderless\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"16dp\" android:layout_marginEnd=\"8dp\" android:backgroundTint=\"@color/green_500\" android:text=\"CANCEL\" android:textColor=\"@color/green_500\" app:layout_constraintEnd_toStartOf=\"@+id/button\" app:layout_constraintTop_toBottomOf=\"@+id/editText\" /> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 6042, "s": 4070, "text": null }, { "code": null, "e": 6055, "s": 6046, "text": "Output: " }, { "code": null, "e": 6210, "s": 6057, "text": "To get the data entered by the user, firstly the EditText widget has to be invoked with the id. which is used to point to the unique widgets in android." }, { "code": null, "e": 6339, "s": 6210, "text": "Provide the EditText with the id, by referring to the following code, which has to be invoked inside the activity_main.xml file." }, { "code": null, "e": 6345, "s": 6341, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\" tools:ignore=\"HardcodedText\"> <EditText android:id=\"@+id/editText\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"16dp\" android:layout_marginEnd=\"16dp\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" app:layout_constraintVertical_bias=\"0.321\" /> <Button android:id=\"@+id/submitButton\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"16dp\" android:backgroundTint=\"@color/green_500\" android:text=\"SUBMIT\" android:textColor=\"@color/white\" app:layout_constraintEnd_toEndOf=\"@+id/editText\" app:layout_constraintTop_toBottomOf=\"@+id/editText\" /> <Button android:id=\"@+id/cancelButton\" style=\"@style/Widget.AppCompat.Button.Borderless\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"16dp\" android:layout_marginEnd=\"8dp\" android:backgroundTint=\"@color/green_500\" android:text=\"CANCEL\" android:textColor=\"@color/green_500\" app:layout_constraintEnd_toStartOf=\"@+id/submitButton\" app:layout_constraintTop_toBottomOf=\"@+id/editText\" /> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 8204, "s": 6345, "text": null }, { "code": null, "e": 8380, "s": 8207, "text": "The following code needs to be invoked inside the MainActivity.kt file. Which performs the retrieving operation and provides the Toast message the same as the entered data." }, { "code": null, "e": 8527, "s": 8380, "text": "There is one scenario, if the user left the EditText blank, it has to be checked whether it’s blank or not. To check whether it is blank EditText." }, { "code": null, "e": 8536, "s": 8529, "text": "Kotlin" }, { "code": null, "e": 8541, "s": 8536, "text": "Java" }, { "code": "import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Buttonimport android.widget.EditTextimport android.widget.Toast class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // register editText with instance val editText: EditText = findViewById(R.id.editText) // also register the submit button with the appropriate id val submitButton: Button = findViewById(R.id.submitButton) // handle the button with the onClickListener submitButton.setOnClickListener { // get the data with the \"editText.text.toString()\" val enteredData: String = editText.text.toString() // check whether the retrieved data is empty or not // based on the emptiness provide the Toast Message if (enteredData.isEmpty()) { Toast.makeText(applicationContext, \"Please Enter the Data\", Toast.LENGTH_SHORT) .show() } else { Toast.makeText(applicationContext, enteredData, Toast.LENGTH_SHORT).show() } } }}", "e": 9769, "s": 8541, "text": null }, { "code": "import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast;import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { EditText editText; Button submitButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // register editText with instance editText = (EditText) findViewById(R.id.editText); // also register the submit button with the appropriate id submitButton = (Button) findViewById(R.id.submitButton); // handle the button with the onClickListener submitButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { // get the data with the // \"editText.text.toString()\" String enteredData = editText.getText().toString(); // check whether the retrieved data is // empty or not based on the emptiness // provide the Toast Message if (enteredData.isEmpty()) { Toast.makeText(getApplicationContext(), \"Please Enter the Data\", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getApplicationContext(), enteredData, Toast.LENGTH_SHORT).show(); } } }); }}", "e": 11429, "s": 9769, "text": null }, { "code": null, "e": 11442, "s": 11433, "text": "Output: " }, { "code": null, "e": 11696, "s": 11444, "text": "The EditText allows developers to make restrictions for the amount of data to be entered by the user. For example, the number of characters entered can be restricted, or the number of lines can be restricted, or the number of digits can be restricted." }, { "code": null, "e": 11734, "s": 11696, "text": "Following are some of the attributes:" }, { "code": null, "e": 11877, "s": 11734, "text": "Input only particular numbers -> The following attribute takes only the digits 5 & 6 as input and no other numbers can be entered by the user." }, { "code": null, "e": 11908, "s": 11877, "text": "digits=”56β€²β€²inputType=”number”" }, { "code": null, "e": 11921, "s": 11908, "text": "digits=”56β€²β€²" }, { "code": null, "e": 11940, "s": 11921, "text": "inputType=”number”" }, { "code": null, "e": 12063, "s": 11940, "text": "Restrict the number of characters of the input -> The following attribute makes user to enter only 6 number of characters." }, { "code": null, "e": 12078, "s": 12063, "text": "maxLength=”6β€²β€²" }, { "code": null, "e": 12093, "s": 12078, "text": "maxLength=”6β€²β€²" }, { "code": null, "e": 12291, "s": 12093, "text": "Restrict the number of lines of input -> The following attribute makes user restricted to only single line, in which the EditText do not expand if the amount of the data gets more than single line." }, { "code": null, "e": 12315, "s": 12291, "text": "lines=”1β€²β€²maxLines=”1β€²β€²" }, { "code": null, "e": 12326, "s": 12315, "text": "lines=”1β€²β€²" }, { "code": null, "e": 12340, "s": 12326, "text": "maxLines=”1β€²β€²" }, { "code": null, "e": 12420, "s": 12340, "text": "Following is the example of the numberPassword with only 6 digits as maxLength." }, { "code": null, "e": 12426, "s": 12422, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\" tools:ignore=\"HardcodedText\"> <EditText android:id=\"@+id/editText\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"16dp\" android:layout_marginEnd=\"16dp\" android:inputType=\"numberPassword\" android:maxLength=\"6\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" app:layout_constraintVertical_bias=\"0.321\" /> <Button android:id=\"@+id/submitButton\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"16dp\" android:backgroundTint=\"@color/green_500\" android:text=\"SUBMIT\" android:textColor=\"@color/white\" app:layout_constraintEnd_toEndOf=\"@+id/editText\" app:layout_constraintTop_toBottomOf=\"@+id/editText\" /> <Button android:id=\"@+id/cancelButton\" style=\"@style/Widget.AppCompat.Button.Borderless\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"16dp\" android:layout_marginEnd=\"8dp\" android:backgroundTint=\"@color/green_500\" android:text=\"CANCEL\" android:textColor=\"@color/green_500\" app:layout_constraintEnd_toStartOf=\"@+id/submitButton\" app:layout_constraintTop_toBottomOf=\"@+id/editText\" /> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 14386, "s": 12426, "text": null }, { "code": null, "e": 14398, "s": 14390, "text": "Output:" }, { "code": null, "e": 14511, "s": 14400, "text": "The hints for the EditText give confidence to the user, on what the data they have to enter into the EditText." }, { "code": null, "e": 14585, "s": 14511, "text": "The attribute which is used to provide the hint text for the EditText is:" }, { "code": null, "e": 14620, "s": 14585, "text": "android:hint=”First and Last Name”" }, { "code": null, "e": 14689, "s": 14620, "text": "Refer to the following code and its output for better understanding." }, { "code": null, "e": 14695, "s": 14691, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\" tools:ignore=\"HardcodedText\"> <EditText android:id=\"@+id/editText\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"16dp\" android:layout_marginEnd=\"16dp\" android:hint=\"First and Last Name\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" app:layout_constraintVertical_bias=\"0.321\" /> <Button android:id=\"@+id/submitButton\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"16dp\" android:backgroundTint=\"@color/green_500\" android:text=\"SUBMIT\" android:textColor=\"@color/white\" app:layout_constraintEnd_toEndOf=\"@+id/editText\" app:layout_constraintTop_toBottomOf=\"@+id/editText\" /> <Button android:id=\"@+id/cancelButton\" style=\"@style/Widget.AppCompat.Button.Borderless\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"16dp\" android:layout_marginEnd=\"8dp\" android:backgroundTint=\"@color/green_500\" android:text=\"CANCEL\" android:textColor=\"@color/green_500\" app:layout_constraintEnd_toStartOf=\"@+id/submitButton\" app:layout_constraintTop_toBottomOf=\"@+id/editText\" /> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 16626, "s": 14695, "text": null }, { "code": null, "e": 16639, "s": 16630, "text": "Output: " }, { "code": null, "e": 16740, "s": 16641, "text": "The stroke color which appears when it is in focus can also be changed, by the following attribute" }, { "code": null, "e": 16776, "s": 16740, "text": "android:backgroundTint=”colorValue”" }, { "code": null, "e": 16846, "s": 16776, "text": "Refer to the following code and its output, for better understanding." }, { "code": null, "e": 16852, "s": 16848, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\" tools:ignore=\"HardcodedText\"> <EditText android:id=\"@+id/editText\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"16dp\" android:layout_marginEnd=\"16dp\" android:backgroundTint=\"@android:color/holo_red_dark\" android:hint=\"First and Last Name\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" app:layout_constraintVertical_bias=\"0.321\" /> <Button android:id=\"@+id/submitButton\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"16dp\" android:backgroundTint=\"@color/green_500\" android:text=\"SUBMIT\" android:textColor=\"@color/white\" app:layout_constraintEnd_toEndOf=\"@+id/editText\" app:layout_constraintTop_toBottomOf=\"@+id/editText\" /> <Button android:id=\"@+id/cancelButton\" style=\"@style/Widget.AppCompat.Button.Borderless\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"16dp\" android:layout_marginEnd=\"8dp\" android:backgroundTint=\"@color/green_500\" android:text=\"CANCEL\" android:textColor=\"@color/green_500\" app:layout_constraintEnd_toStartOf=\"@+id/submitButton\" app:layout_constraintTop_toBottomOf=\"@+id/editText\" /> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 18832, "s": 16852, "text": null }, { "code": null, "e": 18845, "s": 18836, "text": "Output: " }, { "code": null, "e": 18944, "s": 18847, "text": "The text inside the EditText gets highlighted when the user selects the particular text from it." }, { "code": null, "e": 19044, "s": 18944, "text": "The color of the highlighted text inside the EditText can be changed using the following attribute." }, { "code": null, "e": 19084, "s": 19044, "text": "android:textColorHighlight=”colorValue”" }, { "code": null, "e": 19153, "s": 19084, "text": "Refer to the following code and its output for better understanding." }, { "code": null, "e": 19159, "s": 19155, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\" tools:ignore=\"HardcodedText\"> <EditText android:id=\"@+id/editText\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"16dp\" android:layout_marginEnd=\"16dp\" android:textColorHighlight=\"@android:color/holo_orange_light\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" app:layout_constraintVertical_bias=\"0.321\" /> <Button android:id=\"@+id/submitButton\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"16dp\" android:backgroundTint=\"@color/green_500\" android:text=\"SUBMIT\" android:textColor=\"@color/white\" app:layout_constraintEnd_toEndOf=\"@+id/editText\" app:layout_constraintTop_toBottomOf=\"@+id/editText\" /> <Button android:id=\"@+id/cancelButton\" style=\"@style/Widget.AppCompat.Button.Borderless\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"16dp\" android:layout_marginEnd=\"8dp\" android:backgroundTint=\"@color/green_500\" android:text=\"CANCEL\" android:textColor=\"@color/green_500\" app:layout_constraintEnd_toStartOf=\"@+id/submitButton\" app:layout_constraintTop_toBottomOf=\"@+id/editText\" /> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 21089, "s": 19159, "text": null }, { "code": null, "e": 21102, "s": 21093, "text": "Output: " }, { "code": null, "e": 21246, "s": 21104, "text": "Event listeners for the EditText can also be implemented to perform particular actions. Refer to the How to Implement TextWatcher in Android?" }, { "code": null, "e": 21398, "s": 21246, "text": "If the user misses out on any of the EditText or left the EditText blank without inputting any data, the user has to be alerted with the error message." }, { "code": null, "e": 21497, "s": 21398, "text": "To implement such functionality, refer to Implement Form Validation (Error to EditText) in Android" }, { "code": null, "e": 21618, "s": 21497, "text": "Implement the password visibility toggle for the EditText by referring to How to Toggle Password Visibility in Android?." }, { "code": null, "e": 21692, "s": 21618, "text": "Invoke the following dependency to access the Material Design components." }, { "code": null, "e": 21752, "s": 21692, "text": "implementation β€˜com.google.android.material:material:1.2.1’" }, { "code": null, "e": 21822, "s": 21752, "text": "The following attributes are to be invoked inside the TextInputLayout" }, { "code": null, "e": 21848, "s": 21822, "text": "app:counterEnabled=”true”" }, { "code": null, "e": 21874, "s": 21848, "text": "app:counterMaxLength=”6β€²β€²" }, { "code": null, "e": 21943, "s": 21874, "text": "Refer to the following code and its output for better understanding." }, { "code": null, "e": 21949, "s": 21945, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\" tools:ignore=\"HardcodedText\"> <com.google.android.material.textfield.TextInputLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"32dp\" android:layout_marginEnd=\"16dp\" android:hint=\"Enter Something\" app:counterEnabled=\"true\" app:counterMaxLength=\"6\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\"> <com.google.android.material.textfield.TextInputEditText android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" /> </com.google.android.material.textfield.TextInputLayout> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 23150, "s": 21949, "text": null }, { "code": null, "e": 23163, "s": 23154, "text": "Output: " }, { "code": null, "e": 23176, "s": 23167, "text": "raghav14" }, { "code": null, "e": 23185, "s": 23176, "text": "sooda367" }, { "code": null, "e": 23193, "s": 23185, "text": "android" }, { "code": null, "e": 23206, "s": 23193, "text": "Android-View" }, { "code": null, "e": 23230, "s": 23206, "text": "Technical Scripter 2020" }, { "code": null, "e": 23238, "s": 23230, "text": "Android" }, { "code": null, "e": 23245, "s": 23238, "text": "Kotlin" }, { "code": null, "e": 23264, "s": 23245, "text": "Technical Scripter" }, { "code": null, "e": 23272, "s": 23264, "text": "Android" }, { "code": null, "e": 23370, "s": 23272, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 23439, "s": 23370, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 23471, "s": 23439, "text": "Android SDK and it's Components" }, { "code": null, "e": 23510, "s": 23471, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 23559, "s": 23510, "text": "How to Communicate Between Fragments in Android?" }, { "code": null, "e": 23601, "s": 23559, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 23670, "s": 23601, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 23689, "s": 23670, "text": "Android UI Layouts" }, { "code": null, "e": 23702, "s": 23689, "text": "Kotlin Array" }, { "code": null, "e": 23751, "s": 23702, "text": "How to Communicate Between Fragments in Android?" } ]
Create a responsive navigation menu with CSS Media Queries
Media Queries is used when you need to set a style to different devices such as tablet, mobile, desktop, etc. You can try to run the following code to create a responsive navigation menu with Media Queries: Live Demo <!DOCTYPE html> <html lang = "en"> <head> <meta charset = "utf-8"> <meta name = "viewport" content = "width = device-width, initial-scale = 1"> <style> .demo { overflow: hidden; background-color: blue; } .demo a { float: left; display: block; color: white; text-align: center; padding: 10px; text-decoration: none; } @media screen and (max-width: 600px) { .demo a { float: none; width: 100%; } } </style> </head> <body> <p>Navigation Menu:</p> <div class = "demo"> <a href = "#">Home</a> <a href = "#">About</a> <a href = "#">Tutorials</a> <a href = "#">QA</a> <a href = "#">Videos</a> <a href = "#">Contact</a> </div> </body> </html>
[ { "code": null, "e": 1297, "s": 1187, "text": "Media Queries is used when you need to set a style to different devices such as tablet, mobile, desktop, etc." }, { "code": null, "e": 1394, "s": 1297, "text": "You can try to run the following code to create a responsive navigation menu with Media Queries:" }, { "code": null, "e": 1404, "s": 1394, "text": "Live Demo" }, { "code": null, "e": 2351, "s": 1404, "text": "<!DOCTYPE html>\n<html lang = \"en\">\n <head>\n <meta charset = \"utf-8\">\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1\">\n <style>\n .demo {\n overflow: hidden;\n background-color: blue;\n }\n .demo a {\n float: left;\n display: block;\n color: white;\n text-align: center;\n padding: 10px;\n text-decoration: none;\n }\n @media screen and (max-width: 600px) {\n .demo a {\n float: none;\n width: 100%;\n }\n }\n </style>\n </head>\n <body>\n <p>Navigation Menu:</p>\n <div class = \"demo\">\n <a href = \"#\">Home</a>\n <a href = \"#\">About</a>\n <a href = \"#\">Tutorials</a>\n <a href = \"#\">QA</a>\n <a href = \"#\">Videos</a>\n <a href = \"#\">Contact</a>\n </div>\n </body>\n</html>" } ]
How to Add a Y-Axis Label to the Secondary Y-Axis in Matplotlib?
30 Aug, 2021 Sometimes while analyzing any data through graphs we need two x or y-axis to get some more insights into the data. Matplotlib library of Python is the most popular data visualization library, and we can generate any type of plot in Matplotlib. We can create a plot that has two y-axes and can provide different labels to both of the y-axis. We can make a plot with two different y-axes by creating or using two different axes objects with the help of twinx() function. First, we create figure and axis objects and make the first plot. And we also set the x and y-axis labels with the help of the axis object created. Axes object: Axes are the most basic and flexible unit for creating subplots. Axes are used for the placement of plots at any location in the figure. A given figure of the plot can contain many axes, but a given axes object can only be in one figure of the plot. Import packages. Use the axes object and create a subplot. Using the twinx() define the plot values. Now label the axis. Show plot. Example 1: In this example we have created a plot with two different y-axes by using two different axes objects a and a2 with the help of twinx() function. ax.twinx() creates a new Axes object ax2 for a y-axis that is opposite to the original y-axis. The second axes object ax2 is used to make the plot of the second y-axis variable and to update its label. Python3 # Adding a Y-Axis Label to the Secondary Y-Axis in Matplotlib# importing the librariesimport numpy as npimport matplotlib.pyplot as plt # creating data for plot# data arrangement between 0 and 50# with the difference of 2# x-axisx = np.arange(0, 50, 2) # y-axis valuesy1 = x**2 # secondary y-axis valuesy2 = x**3 # plotting figures by creating aexs object# using subplots() functionfig, ax = plt.subplots(figsize = (10, 5))plt.title('Example of Two Y labels') # using the twinx() for creating another# axes object for secondary y-Axisax2 = ax.twinx()ax.plot(x, y1, color = 'g')ax2.plot(x, y2, color = 'b') # giving labels to the axisesax.set_xlabel('x-axis', color = 'r')ax.set_ylabel('y1-axis', color = 'g') # secondary y-axis labelax2.set_ylabel('Secondary y-axis', color = 'b') # defining display layoutplt.tight_layout() # show plotplt.show() Output: Example 2: In this example we have created a bar plot using same method. Python3 # Adding a Y-Axis Label to the# Secondary Y-Axis in Matplotlib# importing the librariesimport numpy as npimport matplotlib.pyplot as plt # creating data for plot# data arrangement between 0 and 50 with the difference of 2# x-axis valuesx = np.arange(0, 50, 2) #y-axis valuesy1 = x**2 # secondary y-axis valuesy2 = x**3 # plotting figures by creating aexs object# using subplots() functionfig, ax = plt.subplots(figsize = (10, 5))plt.title('Example of Two Y labels') # using the twinx() for creating# another axes object for secondary y-Axisax2 = ax.twinx()# creating a bar plotax.bar(x, y1, color = 'g')ax2.bar(x, y2, color = 'b') # giving labels to the axisesax.set_xlabel('x-axis', color = 'r')ax.set_ylabel('y1-axis', color = 'g') # secondary y-axis labelax2.set_ylabel('Secondary y-axis', color = 'b') # defining display layoutplt.tight_layout() # show plotplt.show() Output: Example 3: We can add a y-axis label to the secondary y-axis in pandas too. Generating a plot from DataFrame and also without using twinx() function. In this example, we will use simple DataFrame.plot() function with some parameters to specify the plot. When we set the secondary_y parameter to be True in DataFrame.plot method, it returns different axes that can be used to set the labels. Python3 # Adding a Y-Axis Label to# the Secondary Y-Axis in Matplotlib# importing the librariesimport pandas as pdimport matplotlib.pyplot as plt #creating dataframe for plotdataset = pd.DataFrame({'Name':['Rohit', 'Seema', 'Meena', 'Geeta', 'Rajat'], 'Height': [155,129,138,164,145], 'Weight': [60,40,45,55,60]}) # creating axes object and defining plotax = dataset.plot(kind = 'line', x = 'Name', y = 'Height', color = 'Blue', linewidth = 3) ax2 = dataset.plot(kind = 'line', x = 'Name', y = 'Weight', secondary_y = True, color = 'Red', linewidth = 3, ax = ax) #title of the plotplt.title("Student Data") #labeling x and y-axisax.set_xlabel('Name', color = 'g')ax.set_ylabel('Height', color = "b")ax2.set_ylabel('Weight', color = 'r') #defining display layoutplt.tight_layout() #show plotplt.show() Output: In above example, the plot is created without using twinx() function, but we have created two axis object ax and ax2 as given in other examples for two y-axis to make the plot with two y-axis and update its label. ruhelaa48 Picked Python-matplotlib Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Aug, 2021" }, { "code": null, "e": 645, "s": 28, "text": "Sometimes while analyzing any data through graphs we need two x or y-axis to get some more insights into the data. Matplotlib library of Python is the most popular data visualization library, and we can generate any type of plot in Matplotlib. We can create a plot that has two y-axes and can provide different labels to both of the y-axis. We can make a plot with two different y-axes by creating or using two different axes objects with the help of twinx() function. First, we create figure and axis objects and make the first plot. And we also set the x and y-axis labels with the help of the axis object created." }, { "code": null, "e": 909, "s": 645, "text": "Axes object: Axes are the most basic and flexible unit for creating subplots. Axes are used for the placement of plots at any location in the figure. A given figure of the plot can contain many axes, but a given axes object can only be in one figure of the plot. " }, { "code": null, "e": 926, "s": 909, "text": "Import packages." }, { "code": null, "e": 968, "s": 926, "text": "Use the axes object and create a subplot." }, { "code": null, "e": 1010, "s": 968, "text": "Using the twinx() define the plot values." }, { "code": null, "e": 1030, "s": 1010, "text": "Now label the axis." }, { "code": null, "e": 1041, "s": 1030, "text": "Show plot." }, { "code": null, "e": 1052, "s": 1041, "text": "Example 1:" }, { "code": null, "e": 1399, "s": 1052, "text": "In this example we have created a plot with two different y-axes by using two different axes objects a and a2 with the help of twinx() function. ax.twinx() creates a new Axes object ax2 for a y-axis that is opposite to the original y-axis. The second axes object ax2 is used to make the plot of the second y-axis variable and to update its label." }, { "code": null, "e": 1407, "s": 1399, "text": "Python3" }, { "code": "# Adding a Y-Axis Label to the Secondary Y-Axis in Matplotlib# importing the librariesimport numpy as npimport matplotlib.pyplot as plt # creating data for plot# data arrangement between 0 and 50# with the difference of 2# x-axisx = np.arange(0, 50, 2) # y-axis valuesy1 = x**2 # secondary y-axis valuesy2 = x**3 # plotting figures by creating aexs object# using subplots() functionfig, ax = plt.subplots(figsize = (10, 5))plt.title('Example of Two Y labels') # using the twinx() for creating another# axes object for secondary y-Axisax2 = ax.twinx()ax.plot(x, y1, color = 'g')ax2.plot(x, y2, color = 'b') # giving labels to the axisesax.set_xlabel('x-axis', color = 'r')ax.set_ylabel('y1-axis', color = 'g') # secondary y-axis labelax2.set_ylabel('Secondary y-axis', color = 'b') # defining display layoutplt.tight_layout() # show plotplt.show()", "e": 2254, "s": 1407, "text": null }, { "code": null, "e": 2262, "s": 2254, "text": "Output:" }, { "code": null, "e": 2276, "s": 2264, "text": "Example 2: " }, { "code": null, "e": 2339, "s": 2276, "text": "In this example we have created a bar plot using same method. " }, { "code": null, "e": 2347, "s": 2339, "text": "Python3" }, { "code": "# Adding a Y-Axis Label to the# Secondary Y-Axis in Matplotlib# importing the librariesimport numpy as npimport matplotlib.pyplot as plt # creating data for plot# data arrangement between 0 and 50 with the difference of 2# x-axis valuesx = np.arange(0, 50, 2) #y-axis valuesy1 = x**2 # secondary y-axis valuesy2 = x**3 # plotting figures by creating aexs object# using subplots() functionfig, ax = plt.subplots(figsize = (10, 5))plt.title('Example of Two Y labels') # using the twinx() for creating# another axes object for secondary y-Axisax2 = ax.twinx()# creating a bar plotax.bar(x, y1, color = 'g')ax2.bar(x, y2, color = 'b') # giving labels to the axisesax.set_xlabel('x-axis', color = 'r')ax.set_ylabel('y1-axis', color = 'g') # secondary y-axis labelax2.set_ylabel('Secondary y-axis', color = 'b') # defining display layoutplt.tight_layout() # show plotplt.show()", "e": 3219, "s": 2347, "text": null }, { "code": null, "e": 3227, "s": 3219, "text": "Output:" }, { "code": null, "e": 3239, "s": 3227, "text": "Example 3: " }, { "code": null, "e": 3482, "s": 3239, "text": "We can add a y-axis label to the secondary y-axis in pandas too. Generating a plot from DataFrame and also without using twinx() function. In this example, we will use simple DataFrame.plot() function with some parameters to specify the plot." }, { "code": null, "e": 3619, "s": 3482, "text": "When we set the secondary_y parameter to be True in DataFrame.plot method, it returns different axes that can be used to set the labels." }, { "code": null, "e": 3627, "s": 3619, "text": "Python3" }, { "code": "# Adding a Y-Axis Label to# the Secondary Y-Axis in Matplotlib# importing the librariesimport pandas as pdimport matplotlib.pyplot as plt #creating dataframe for plotdataset = pd.DataFrame({'Name':['Rohit', 'Seema', 'Meena', 'Geeta', 'Rajat'], 'Height': [155,129,138,164,145], 'Weight': [60,40,45,55,60]}) # creating axes object and defining plotax = dataset.plot(kind = 'line', x = 'Name', y = 'Height', color = 'Blue', linewidth = 3) ax2 = dataset.plot(kind = 'line', x = 'Name', y = 'Weight', secondary_y = True, color = 'Red', linewidth = 3, ax = ax) #title of the plotplt.title(\"Student Data\") #labeling x and y-axisax.set_xlabel('Name', color = 'g')ax.set_ylabel('Height', color = \"b\")ax2.set_ylabel('Weight', color = 'r') #defining display layoutplt.tight_layout() #show plotplt.show()", "e": 4632, "s": 3627, "text": null }, { "code": null, "e": 4640, "s": 4632, "text": "Output:" }, { "code": null, "e": 4854, "s": 4640, "text": "In above example, the plot is created without using twinx() function, but we have created two axis object ax and ax2 as given in other examples for two y-axis to make the plot with two y-axis and update its label." }, { "code": null, "e": 4864, "s": 4854, "text": "ruhelaa48" }, { "code": null, "e": 4871, "s": 4864, "text": "Picked" }, { "code": null, "e": 4889, "s": 4871, "text": "Python-matplotlib" }, { "code": null, "e": 4913, "s": 4889, "text": "Technical Scripter 2020" }, { "code": null, "e": 4920, "s": 4913, "text": "Python" }, { "code": null, "e": 4939, "s": 4920, "text": "Technical Scripter" }, { "code": null, "e": 5037, "s": 4939, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5069, "s": 5037, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 5096, "s": 5069, "text": "Python Classes and Objects" }, { "code": null, "e": 5117, "s": 5096, "text": "Python OOPs Concepts" }, { "code": null, "e": 5140, "s": 5117, "text": "Introduction To PYTHON" }, { "code": null, "e": 5196, "s": 5140, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 5227, "s": 5196, "text": "Python | os.path.join() method" }, { "code": null, "e": 5269, "s": 5227, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 5311, "s": 5269, "text": "Check if element exists in list in Python" }, { "code": null, "e": 5350, "s": 5311, "text": "Python | datetime.timedelta() function" } ]
Define Node position in Sankey Diagram in plotly
15 Feb, 2022 Plotly is a Python library which is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library. Sankey Diagram is used to visualize the flow by defining the source node and target node. Value parameters is used to set the flow volume. There are basically arrangement for defining a node position. There are – perpendicular freeform fixed The node position can be set by setting the node.x and node.y value. let’s see the below example for better understanding. Example 1: Python3 import plotly.graph_objects as go plot = go.Figure(go.Sankey( node = { "label": ["A", "B", "C"], "x": [0.5, 0.2, 0.1], "y": [0.4, 0.3, 0.7], 'pad':5}, link = { "source": [1, 0, 1], "target": [2, 3, 4], "value": [4, 2, 1]})) plot.show() Output: Example 2: Python3 import plotly.graph_objects as go plot = go.Figure(go.Sankey( node = { "label": ["Geeks", "For", "Geeks", "GFG"], "x": [0.5, 0.2, 0.1, 0.9], "y": [0.6, 0.8, 0.7], "color": "green", 'pad':5}, link = { "source": [3, 2, 1], "target": [5, 3, 7], "value": [6, 1, 2]})) plot.show() Output: clintra Data Visualization Python-Plotly Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Feb, 2022" }, { "code": null, "e": 330, "s": 28, "text": "Plotly is a Python library which is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library." }, { "code": null, "e": 543, "s": 330, "text": "Sankey Diagram is used to visualize the flow by defining the source node and target node. Value parameters is used to set the flow volume. There are basically arrangement for defining a node position. There are –" }, { "code": null, "e": 557, "s": 543, "text": "perpendicular" }, { "code": null, "e": 566, "s": 557, "text": "freeform" }, { "code": null, "e": 572, "s": 566, "text": "fixed" }, { "code": null, "e": 695, "s": 572, "text": "The node position can be set by setting the node.x and node.y value. let’s see the below example for better understanding." }, { "code": null, "e": 706, "s": 695, "text": "Example 1:" }, { "code": null, "e": 714, "s": 706, "text": "Python3" }, { "code": "import plotly.graph_objects as go plot = go.Figure(go.Sankey( node = { \"label\": [\"A\", \"B\", \"C\"], \"x\": [0.5, 0.2, 0.1], \"y\": [0.4, 0.3, 0.7], 'pad':5}, link = { \"source\": [1, 0, 1], \"target\": [2, 3, 4], \"value\": [4, 2, 1]})) plot.show()", "e": 1009, "s": 714, "text": null }, { "code": null, "e": 1017, "s": 1009, "text": "Output:" }, { "code": null, "e": 1028, "s": 1017, "text": "Example 2:" }, { "code": null, "e": 1036, "s": 1028, "text": "Python3" }, { "code": "import plotly.graph_objects as go plot = go.Figure(go.Sankey( node = { \"label\": [\"Geeks\", \"For\", \"Geeks\", \"GFG\"], \"x\": [0.5, 0.2, 0.1, 0.9], \"y\": [0.6, 0.8, 0.7], \"color\": \"green\", 'pad':5}, link = { \"source\": [3, 2, 1], \"target\": [5, 3, 7], \"value\": [6, 1, 2]})) plot.show()", "e": 1378, "s": 1036, "text": null }, { "code": null, "e": 1386, "s": 1378, "text": "Output:" }, { "code": null, "e": 1394, "s": 1386, "text": "clintra" }, { "code": null, "e": 1413, "s": 1394, "text": "Data Visualization" }, { "code": null, "e": 1427, "s": 1413, "text": "Python-Plotly" }, { "code": null, "e": 1434, "s": 1427, "text": "Python" }, { "code": null, "e": 1532, "s": 1434, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1550, "s": 1532, "text": "Python Dictionary" }, { "code": null, "e": 1592, "s": 1550, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1627, "s": 1592, "text": "Read a file line by line in Python" }, { "code": null, "e": 1653, "s": 1627, "text": "Python String | replace()" }, { "code": null, "e": 1685, "s": 1653, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1714, "s": 1685, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1741, "s": 1714, "text": "Python Classes and Objects" }, { "code": null, "e": 1762, "s": 1741, "text": "Python OOPs Concepts" }, { "code": null, "e": 1785, "s": 1762, "text": "Introduction To PYTHON" } ]
java.math.MathContext Class in Java
22 Feb, 2021 The java.math.MathContext class provides immutable objects that encapsulate context settings and define those numerical operator rules, such as those that the BigDecimal class implements. The base-independent configurations are as follows: Precision: The number of digits to be used for an operation; this accuracy is rounded to results. RoundingMode: a RoundingMode object that determines the rounding algorithm to be used. The number of significant digits is specified by the precision. The default mode in rounding off is HALF_UP mode which will be introduced in later part. Illustration: Suppose a random number say be it 123 is selected and the task now is to round off for 2 significant digits, you’re going to get 120. It might be more apparent if you think in terms of scientific notation. As in scientific notations, 123 would be 1.23e2. If you only keep 2 significant digits, then you get 1.2e2, or 120. By reducing the number of significant digits, we reduce the precision with which we can specify a number. The RoundingMode part specifies how we should handle the loss of precision. If you use 123 as the number and ask for 2 significant digits, you’ve reduced your accuracy to reuse the example. With a RoundingMode of HALF_UP (the default mode), 123 will become 120. With a RoundingMode of CEILING, you’ll get 130. Syntax: Class declaration public final class MathContext extends Object implements Serializable Constructor: MathContext(int setPrecision): This constructor constructs a new MathContext with the specified precision and the HALF_UP rounding mode. MathContext(int setPrecision, RoundingMode setRoundingMode): This constructor constructs a new MathContext with a specified precision and rounding mode. MathContext(String val): This constructor constructs a new MathContext from a string. Now, dwelling onto the methods present in this class, later on, to be used in the implementation part in the program for the same. Method Description Example: Java // Java Program to illustrate java.math.Context class // Importing all classes from// java.math packageimport java.math.*; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Custom input number 'N' over which // class operation are performed // N = 246.8 // erforming the rounding of operations // Rounding off is carried out across // 4 digits // N = 246.8 // It has 4 digits only so // the output is same as input // Case 1 // Across all digits of the input N = 4 System.out.println(new BigDecimal( "246.8", new MathContext(4, RoundingMode.HALF_UP))); // Case 2 // Across 'N/2' of the input 'N' // Here, acrossings 2 digits as input N has 4 digits // Rounding HALF_UP System.out.println(new BigDecimal( "246.8", new MathContext(2, RoundingMode.HALF_UP))); // Rounding HALF_DOWN System.out.println(new BigDecimal( "246.8", new MathContext(2, RoundingMode.CEILING))); // Case 3 // Across '1' digit of the input 'N' // Here, acrossings 2 digits of 4 digits of input N // Rounding HALF_UP System.out.println(new BigDecimal( "246.8", new MathContext(1, RoundingMode.HALF_UP))); // Rounding HALF_DOWN System.out.println(new BigDecimal( "246.8", new MathContext(1, RoundingMode.CEILING))); }} 246.8 2.5E+2 2.5E+2 2E+2 3E+2 Java-Classes Picked Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Feb, 2021" }, { "code": null, "e": 216, "s": 28, "text": "The java.math.MathContext class provides immutable objects that encapsulate context settings and define those numerical operator rules, such as those that the BigDecimal class implements." }, { "code": null, "e": 268, "s": 216, "text": "The base-independent configurations are as follows:" }, { "code": null, "e": 366, "s": 268, "text": "Precision: The number of digits to be used for an operation; this accuracy is rounded to results." }, { "code": null, "e": 453, "s": 366, "text": "RoundingMode: a RoundingMode object that determines the rounding algorithm to be used." }, { "code": null, "e": 606, "s": 453, "text": "The number of significant digits is specified by the precision. The default mode in rounding off is HALF_UP mode which will be introduced in later part." }, { "code": null, "e": 620, "s": 606, "text": "Illustration:" }, { "code": null, "e": 1048, "s": 620, "text": "Suppose a random number say be it 123 is selected and the task now is to round off for 2 significant digits, you’re going to get 120. It might be more apparent if you think in terms of scientific notation. As in scientific notations, 123 would be 1.23e2. If you only keep 2 significant digits, then you get 1.2e2, or 120. By reducing the number of significant digits, we reduce the precision with which we can specify a number." }, { "code": null, "e": 1358, "s": 1048, "text": "The RoundingMode part specifies how we should handle the loss of precision. If you use 123 as the number and ask for 2 significant digits, you’ve reduced your accuracy to reuse the example. With a RoundingMode of HALF_UP (the default mode), 123 will become 120. With a RoundingMode of CEILING, you’ll get 130." }, { "code": null, "e": 1384, "s": 1358, "text": "Syntax: Class declaration" }, { "code": null, "e": 1455, "s": 1384, "text": "public final class MathContext extends Object implements Serializable" }, { "code": null, "e": 1468, "s": 1455, "text": "Constructor:" }, { "code": null, "e": 1605, "s": 1468, "text": "MathContext(int setPrecision): This constructor constructs a new MathContext with the specified precision and the HALF_UP rounding mode." }, { "code": null, "e": 1758, "s": 1605, "text": "MathContext(int setPrecision, RoundingMode setRoundingMode): This constructor constructs a new MathContext with a specified precision and rounding mode." }, { "code": null, "e": 1844, "s": 1758, "text": "MathContext(String val): This constructor constructs a new MathContext from a string." }, { "code": null, "e": 1975, "s": 1844, "text": "Now, dwelling onto the methods present in this class, later on, to be used in the implementation part in the program for the same." }, { "code": null, "e": 1982, "s": 1975, "text": "Method" }, { "code": null, "e": 1994, "s": 1982, "text": "Description" }, { "code": null, "e": 2003, "s": 1994, "text": "Example:" }, { "code": null, "e": 2008, "s": 2003, "text": "Java" }, { "code": "// Java Program to illustrate java.math.Context class // Importing all classes from// java.math packageimport java.math.*; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Custom input number 'N' over which // class operation are performed // N = 246.8 // erforming the rounding of operations // Rounding off is carried out across // 4 digits // N = 246.8 // It has 4 digits only so // the output is same as input // Case 1 // Across all digits of the input N = 4 System.out.println(new BigDecimal( \"246.8\", new MathContext(4, RoundingMode.HALF_UP))); // Case 2 // Across 'N/2' of the input 'N' // Here, acrossings 2 digits as input N has 4 digits // Rounding HALF_UP System.out.println(new BigDecimal( \"246.8\", new MathContext(2, RoundingMode.HALF_UP))); // Rounding HALF_DOWN System.out.println(new BigDecimal( \"246.8\", new MathContext(2, RoundingMode.CEILING))); // Case 3 // Across '1' digit of the input 'N' // Here, acrossings 2 digits of 4 digits of input N // Rounding HALF_UP System.out.println(new BigDecimal( \"246.8\", new MathContext(1, RoundingMode.HALF_UP))); // Rounding HALF_DOWN System.out.println(new BigDecimal( \"246.8\", new MathContext(1, RoundingMode.CEILING))); }}", "e": 3565, "s": 2008, "text": null }, { "code": null, "e": 3595, "s": 3565, "text": "246.8\n2.5E+2\n2.5E+2\n2E+2\n3E+2" }, { "code": null, "e": 3608, "s": 3595, "text": "Java-Classes" }, { "code": null, "e": 3615, "s": 3608, "text": "Picked" }, { "code": null, "e": 3620, "s": 3615, "text": "Java" }, { "code": null, "e": 3625, "s": 3620, "text": "Java" } ]
How to handle SSL certificate error using Selenium WebDriver?
We can handle SSL certificate error using Selenium webdriver while we try to launch a web page based on HTTP. SSL certificate errors are encountered in multiple browsers like Chrome, Safari, and Firefox and so on. SSL certificate error comes up if the site we are making an attempt to access has an outdated, invalid or an untrusted certificate. SSL or Secure Sockets Layer is a protocol followed to create a connection between the client (browser) and the server. To handle the SSL certificate error we have to use the DesiredCapabilities class and then accept the SSL error by setting the ACCEPT_SSL_CERTS to true and applying this capability to the browser DesiredCapabilities c=DesiredCapabilities.internetExplorer(); c.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true); import org.openqa.selenium.WebDriver; import org.openqa.selenium.Capabilities; import org.openqa.selenium.ie.InternetExplorerDriver; import org.openqa.selenium.remote.CapabilityType; import org.openqa.selenium.remote.DesiredCapabilities; public class SSLError{ public static void main(String[] args) { //DesiredCapabilities object DesiredCapabilities c=DesiredCapabilities.internetExplorer(); //set SSL certificate to true c.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true); System.setProperty("webdriver.ie.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\IEDriverServer.exe"); //configure capability to browser WebDriver driver = new InternetExplorerDriver(c); //implicit wait driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); //URL launch driver.get("application url to be entered"); } }
[ { "code": null, "e": 1401, "s": 1187, "text": "We can handle SSL certificate error using Selenium webdriver while we try to launch a web page based on HTTP. SSL certificate errors are encountered in multiple browsers like Chrome, Safari, and Firefox and so on." }, { "code": null, "e": 1652, "s": 1401, "text": "SSL certificate error comes up if the site we are making an attempt to access has an outdated, invalid or an untrusted certificate. SSL or Secure Sockets Layer is a protocol followed to create a connection between the client (browser) and the server." }, { "code": null, "e": 1847, "s": 1652, "text": "To handle the SSL certificate error we have to use the DesiredCapabilities class and then accept the SSL error by setting the ACCEPT_SSL_CERTS to true and applying this capability to the browser" }, { "code": null, "e": 1965, "s": 1847, "text": "DesiredCapabilities c=DesiredCapabilities.internetExplorer();\nc.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);" }, { "code": null, "e": 2842, "s": 1965, "text": "import org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.Capabilities;\nimport org.openqa.selenium.ie.InternetExplorerDriver;\nimport org.openqa.selenium.remote.CapabilityType;\nimport org.openqa.selenium.remote.DesiredCapabilities;\npublic class SSLError{\n public static void main(String[] args) {\n //DesiredCapabilities object\n DesiredCapabilities c=DesiredCapabilities.internetExplorer();\n //set SSL certificate to true\n c.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);\n System.setProperty(\"webdriver.ie.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\IEDriverServer.exe\");\n //configure capability to browser\n WebDriver driver = new InternetExplorerDriver(c);\n //implicit wait\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n //URL launch\n driver.get(\"application url to be entered\");\n }\n}" } ]
Robot Framework - Introduction to Ride
Ride is a testing editor for Robot Framework. Further, we will write test cases in Ride. To start Ride, we need to run the command shown below. ride.py The above command will open the IDE as shown in the following screenshot βˆ’ In this chapter, we will walk through the editor to see what options and features are available in the IDE. The options and features will help us in testing our project. Go to File and click on New Project as shown below βˆ’ The following screen will appear when you click New Project. Enter the name of the project. Created Path is the path where the project will get saved. You can change the location if required. The project can be saved as File or directory. You can also save the project in format like ROBOT, TXT, TSV or HTML. In this tutorial, we are going to use the format ROBOT and how to write and execute test-cases. Now, we will add a project as a file the way it is shown below. The project is named Testing and the following screen sppears after the project is created. The name of the project is shown on the left side and on the right side we can see three tabs Edit, TextEdit and Run. Edit has a lot of options on the UI as shown above. In this section, we can add data required to run our test cases. We can import Library, Resource, Variables, Add scalar, Add list, Add dict and Add Metadata. The details added in the Edit section will be seen in the next tab, Text Edit. You can write the code here in text edit section. If there is any change added in Textedit, it will be seen in the Edit section. Therefore, both the tabs Edit and TextEdit are dependent on each other and the changes done will be seen on both. Once the test cases are ready, we can we use the third tab Run to execute them. The Run UI is as shown above. It allows to run the test case and comes with options like start, stop, pause continue, next test case, step over, etc. You can also create Report, Log for the test cases you are executing. To create a test case, we have to do the following βˆ’ Right-click on the project created and click on new test case as shown below βˆ’ Upon clicking New Test Case, a screen appears as shown below βˆ’ Enter the name of the test case and click OK. We have saved the test case as TC0. The following screen appears once the test case is saved. The test case has options like Documentation, setup, teardown, tags, timeout and Template. They have an edit button across it; upon clicking the button a screen appears wherein, you can enter the details for each option. We will discuss the various parameters of these details in our subsequent chapters. The test cases can be written in tabular format as shown below. Robot framework test cases are keyword based and we can write the test-cases using built-in keywords or keywords imported from the library. We can also create user-defined keywords, variables, etc. in robot framework. There are shortcuts available in the navigation bar to run/stop test case as shown below βˆ’ The search keyword option can be used as shown in the screenshot below βˆ’ To get the list of keywords available with robot framework, simple press ctrl+space in the tabular format as shown below and it will display all the keywords available βˆ’ In case, you cannot remember the keyword, this will help you get the details. We have the details available across each keyword. The details also show how to use the related keyword. In our next chapter, we will learn how to create our first test case in ride. In this chapter, we have seen the features available with RIDE. We also learnt how to create test cases and execute them.
[ { "code": null, "e": 2447, "s": 2303, "text": "Ride is a testing editor for Robot Framework. Further, we will write test cases in Ride. To start Ride, we need to run the command shown below." }, { "code": null, "e": 2456, "s": 2447, "text": "ride.py\n" }, { "code": null, "e": 2531, "s": 2456, "text": "The above command will open the IDE as shown in the following screenshot βˆ’" }, { "code": null, "e": 2701, "s": 2531, "text": "In this chapter, we will walk through the editor to see what options and features are available in the IDE. The options and features will help us in testing our project." }, { "code": null, "e": 2754, "s": 2701, "text": "Go to File and click on New Project as shown below βˆ’" }, { "code": null, "e": 2815, "s": 2754, "text": "The following screen will appear when you click New Project." }, { "code": null, "e": 3159, "s": 2815, "text": "Enter the name of the project. Created Path is the path where the project will get saved. You can change the location if required. The project can be saved as File or directory. You can also save the project in format like ROBOT, TXT, TSV or HTML. In this tutorial, we are going to use the format ROBOT and how to write and execute test-cases." }, { "code": null, "e": 3315, "s": 3159, "text": "Now, we will add a project as a file the way it is shown below. The project is named Testing and the following screen sppears after the project is created." }, { "code": null, "e": 3433, "s": 3315, "text": "The name of the project is shown on the left side and on the right side we can see three tabs Edit, TextEdit and Run." }, { "code": null, "e": 3643, "s": 3433, "text": "Edit has a lot of options on the UI as shown above. In this section, we can add data required to run our test cases. We can import Library, Resource, Variables, Add scalar, Add list, Add dict and Add Metadata." }, { "code": null, "e": 3772, "s": 3643, "text": "The details added in the Edit section will be seen in the next tab, Text Edit. You can write the code here in text edit section." }, { "code": null, "e": 3965, "s": 3772, "text": "If there is any change added in Textedit, it will be seen in the Edit section. Therefore, both the tabs Edit and TextEdit are dependent on each other and the changes done will be seen on both." }, { "code": null, "e": 4045, "s": 3965, "text": "Once the test cases are ready, we can we use the third tab Run to execute them." }, { "code": null, "e": 4265, "s": 4045, "text": "The Run UI is as shown above. It allows to run the test case and comes with options like start, stop, pause continue, next test case, step over, etc. You can also create Report, Log for the test cases you are executing." }, { "code": null, "e": 4318, "s": 4265, "text": "To create a test case, we have to do the following βˆ’" }, { "code": null, "e": 4397, "s": 4318, "text": "Right-click on the project created and click on new test case as shown below βˆ’" }, { "code": null, "e": 4460, "s": 4397, "text": "Upon clicking New Test Case, a screen appears as shown below βˆ’" }, { "code": null, "e": 4600, "s": 4460, "text": "Enter the name of the test case and click OK. We have saved the test case as TC0. The following screen appears once the test case is saved." }, { "code": null, "e": 4905, "s": 4600, "text": "The test case has options like Documentation, setup, teardown, tags, timeout and Template. They have an edit button across it; upon clicking the button a screen appears wherein, you can enter the details for each option. We will discuss the various parameters of these details in our subsequent chapters." }, { "code": null, "e": 5187, "s": 4905, "text": "The test cases can be written in tabular format as shown below. Robot framework test cases are keyword based and we can write the test-cases using built-in keywords or keywords imported from the library. We can also create user-defined keywords, variables, etc. in robot framework." }, { "code": null, "e": 5278, "s": 5187, "text": "There are shortcuts available in the navigation bar to run/stop test case as shown below βˆ’" }, { "code": null, "e": 5351, "s": 5278, "text": "The search keyword option can be used as shown in the screenshot below βˆ’" }, { "code": null, "e": 5521, "s": 5351, "text": "To get the list of keywords available with robot framework, simple press ctrl+space in the tabular format as shown below and it will display all the keywords available βˆ’" }, { "code": null, "e": 5782, "s": 5521, "text": "In case, you cannot remember the keyword, this will help you get the details. We have the details available across each keyword. The details also show how to use the related keyword. In our next chapter, we will learn how to create our first test case in ride." } ]
Count distinct elements in an array
29 Jun, 2022 Given an unsorted array, count all distinct elements in it.Examples: Input : arr[] = {10, 20, 20, 10, 30, 10} Output : 3 There are three distinct elements 10, 20 and 30. Input : arr[] = {10, 20, 20, 10, 20} Output : 2 A simple solution is to run two loops. For every element, check if it has appeared before. If yes, increment count of distinct elements. C++ Java Python3 C# PHP Javascript // C++ program to count distinct elements// in a given array#include <iostream>using namespace std; int countDistinct(int arr[], int n){ int res = 1; // Pick all elements one by one for (int i = 1; i < n; i++) { int j = 0; for (j = 0; j < i; j++) if (arr[i] == arr[j]) break; // If not printed earlier, then print it if (i == j) res++; } return res;} // Driver program to test above functionint main(){ int arr[] = { 12, 10, 9, 45, 2, 10, 10, 45 }; int n = sizeof(arr) / sizeof(arr[0]); cout << countDistinct(arr, n); return 0;} // Java program to count distinct// elements in a given arrayclass GFG{ static int countDistinct(int arr[], int n){ int res = 1; // Pick all elements one by one for (int i = 1; i < n; i++) { int j = 0; for (j = 0; j < i; j++) if (arr[i] == arr[j]) break; // If not printed earlier, // then print it if (i == j) res++; } return res;} // Driver codepublic static void main(String[] args){ int arr[] = { 12, 10, 9, 45, 2, 10, 10, 45 }; int n = arr.length; System.out.println(countDistinct(arr, n));}} // This code is contributed by Code_Mech. # Python3 program to count distinct# elements in a given arraydef countDistinct(arr, n): res = 1 # Pick all elements one by one for i in range(1, n): j = 0 for j in range(i): if (arr[i] == arr[j]): break # If not printed earlier, then print it if (i == j + 1): res += 1 return res # Driver Codearr = [12, 10, 9, 45, 2, 10, 10, 45]n = len(arr)print(countDistinct(arr, n)) # This code is contributed by Mohit Kumar // C# program to count distinct// elements in a given arrayusing System; class GFG{ static int countDistinct(int []arr, int n){ int res = 1; // Pick all elements one by one for (int i = 1; i < n; i++) { int j = 0; for (j = 0; j < i; j++) if (arr[i] == arr[j]) break; // If not printed earlier, // then print it if (i == j) res++; } return res;} // Driver codepublic static void Main(){ int []arr = { 12, 10, 9, 45, 2, 10, 10, 45 }; int n = arr.Length; Console.WriteLine(countDistinct(arr, n));}} // This code is contributed// by Akanksha Rai <?php// PHP program to count distinct elements// in a given arrayfunction countDistinct( &$arr, $n){ $res = 1; // Pick all elements one by one for ( $i = 1; $i < $n; $i++) { for ($j = 0; $j < $i; $j++) if ($arr[$i] == $arr[$j]) break; // If not printed earlier, // then print it if ($i == $j) $res++; } return $res;} // Driver Code$arr = array( 12, 10, 9, 45, 2, 10, 10, 45 );$n = count($arr);echo countDistinct($arr, $n); // This code is contributed by// Rajput-Ji?> <script> // JavaScript program to count distinct elements// in a given array function countDistinct(arr, n){ let res = 1; // Pick all elements one by one for (let i = 1; i < n; i++) { let j = 0; for (j = 0; j < i; j++) if (arr[i] === arr[j]) break; // If not printed earlier, then print it if (i === j) res++; } return res;} // Driver program to test above function let arr = [ 12, 10, 9, 45, 2, 10, 10, 45 ]; let n = arr.length; document.write(countDistinct(arr, n)); // This code is contributed by Surbhi Tyagi </script> 5 Time Complexity of above solution is O(n2). We can Use Sorting to solve the problem in O(nLogn) time. The idea is simple, first sort the array so that all occurrences of every element become consecutive. Once the occurrences become consecutive, we can traverse the sorted array and count distinct elements in O(n) time. Following is the implementation of the idea. C++ Java Python3 C# PHP Javascript // C++ program to count all distinct elements// in a given array#include <algorithm>#include <iostream>using namespace std; int countDistinct(int arr[], int n){ // First sort the array so that all // occurrences become consecutive sort(arr, arr + n); // Traverse the sorted array int res = 0; for (int i = 0; i < n; i++) { // Move the index ahead while // there are duplicates while (i < n - 1 && arr[i] == arr[i + 1]) i++; res++; } return res;} // Driver program to test above functionint main(){ int arr[] = { 6, 10, 5, 4, 9, 120, 4, 6, 10 }; int n = sizeof(arr) / sizeof(arr[0]); cout << countDistinct(arr, n); return 0;} // Java program to count all distinct elements// in a given arrayimport java.util.Arrays; class GFG{ static int countDistinct(int arr[], int n) { // First sort the array so that all // occurrences become consecutive Arrays.sort(arr); // Traverse the sorted array int res = 0; for (int i = 0; i < n; i++) { // Move the index ahead while // there are duplicates while (i < n - 1 && arr[i] == arr[i + 1]) { i++; } res++; } return res; } // Driver code public static void main(String[] args) { int arr[] = {6, 10, 5, 4, 9, 120, 4, 6, 10}; int n = arr.length; System.out.println(countDistinct(arr, n)); }} // This code is contributed by 29AjayKumar # Python3 program to count all distinct# elements in a given array def countDistinct(arr, n): # First sort the array so that all # occurrences become consecutive arr.sort(); # Traverse the sorted array res = 0; i = 0; while(i < n): # Move the index ahead while # there are duplicates while (i < n - 1 and arr[i] == arr[i + 1]): i += 1; res += 1; i += 1; return res; # Driver Codearr = [ 6, 10, 5, 4, 9, 120, 4, 6, 10 ];n = len(arr);print(countDistinct(arr, n)); # This code is contributed by mits // C# program to count all distinct elements// in a given arrayusing System; class GFG{ static int countDistinct(int[] arr, int n) { // First sort the array so that all // occurrences become consecutive Array.Sort(arr); // Traverse the sorted array int res = 0; for (int i = 0; i < n; i++) { // Move the index ahead while // there are duplicates while (i < n - 1 && arr[i] == arr[i + 1]) { i++; } res++; } return res; } // Driver code public static void Main() { int[] arr = {6, 10, 5, 4, 9, 120, 4, 6, 10}; int n = arr.Length; Console.WriteLine(countDistinct(arr, n)); }} // This code is contributed by Code_Mech. <?php// PHP program to count all distinct// elements in a given array function countDistinct($arr, $n){ // First sort the array so that all // occurrences become consecutive sort($arr, 0); // Traverse the sorted array $res = 0; for ($i = 0; $i < $n; $i++) { // Move the index ahead while // there are duplicates while ($i < $n - 1 && $arr[$i] == $arr[$i + 1]) $i++; $res++; } return $res;} // Driver Code$arr = array( 6, 10, 5, 4, 9, 120, 4, 6, 10 );$n = sizeof($arr);echo countDistinct($arr, $n); // This code is contributed by Akanksha Rai?> <script> // JavaScript program to count all distinct elements// in a given array function countDistinct(arr,n){ // First sort the array so that all // occurrences become consecutive arr.sort(function(a,b){return a-b;}); // Traverse the sorted array let res = 0; for (let i = 0; i < n; i++) { // Move the index ahead while // there are duplicates while (i < n - 1 && arr[i] == arr[i + 1]) { i++; } res++; } return res;} // Driver codelet arr=[6, 10, 5, 4, 9, 120, 4, 6, 10];let n = arr.length;document.write(countDistinct(arr, n)); // This code is contributed by unknown2108 </script> 6 We can Use Hashing to solve this in O(n) time on average. The idea is to traverse the given array from left to right and keep track of visited elements in a hash set , as a set consists of only unique elements. Following is the implementation of the idea. C++ Java Python3 C# PHP Javascript /* CPP program to print all distinct elements of a given array */#include <bits/stdc++.h>using namespace std; // This function prints all distinct elementsint countDistinct(int arr[], int n){ // Creates an empty hashset unordered_set<int> s; // Traverse the input array int res = 0; for (int i = 0; i < n; i++) { // If not present, then put it in // hashtable and increment result if (s.find(arr[i]) == s.end()) { s.insert(arr[i]); res++; } } return res;} // Driver program to test above functionint main(){ int arr[] = { 6, 10, 5, 4, 9, 120, 4, 6, 10 }; int n = sizeof(arr) / sizeof(arr[0]); cout << countDistinct(arr, n); return 0;} // Java Program to count// Unique elements in Arrayimport java.util.*; class GFG{ // This method returns count // of Unique elements public static int countDistinct(int arr[],int n) { HashSet<Integer> hs = new HashSet<Integer>(); for(int i = 0; i < n; i++) { // add all the elements to the HashSet hs.add(arr[i]); } // return the size of hashset as // it consists of all Unique elements return hs.size(); } // Driver code public static void main(String[] args) { int arr[] = new int[]{6, 10, 5, 4, 9, 120, 4, 6, 10}; System.out.println(countDistinct(arr, arr.length)); }} // This code is contributed by Adarsh_Verma ''' Python3 program to print all distinct elementsof a given array ''' # This function prints all distinct elementsdef countDistinct(arr, n): # Creates an empty hashset s = set() # Traverse the input array res = 0 for i in range(n): # If not present, then put it in # hashtable and increment result if (arr[i] not in s): s.add(arr[i]) res += 1 return res # Driver codearr = [6, 10, 5, 4, 9, 120, 4, 6, 10]n = len(arr)print(countDistinct(arr, n)) # This code is contributed by SHUBHAMSINGH10 // C# Program to count// Unique elements in Arrayusing System;using System.Collections.Generic; class GFG{ // This method returns count // of Unique elements public static int countDistinct(int []arr,int n) { HashSet<int> hs = new HashSet<int>(); for(int i = 0; i < n; i++) { // add all the elements to the HashSet hs.Add(arr[i]); } // return the size of hashset as // it consists of all Unique elements return hs.Count; } // Driver code public static void Main() { int []arr = new int[]{6, 10, 5, 4, 9, 120, 4, 6, 10}; Console.WriteLine(countDistinct(arr, arr.Length)); }} /* This code contributed by PrinciRaj1992 */ <?php// PHP program to print all distinct elements// of a given array // This function prints all distinct elementsfunction countDistinct($arr, $n){ // Creates an empty hashset $s = array(); // Traverse the input array $res = 0; for ($i = 0; $i < $n; $i++) { // If not present, then put it in // hashtable and increment result array_push($s,$arr[$i]); } $s = array_unique($s); return count($s);} // Driver Code$arr = array( 6, 10, 5, 4, 9, 120, 4, 6, 10 );$n = count($arr);echo countDistinct($arr, $n); // This code is contributed by mits?> <script>// Javascript Program to count// Unique elements in Array // This method returns count // of Unique elementsfunction countDistinct(arr,n){ let hs = new Set(); for(let i = 0; i < n; i++) { // add all the elements to the HashSet hs.add(arr[i]); } // return the size of hashset as // it consists of all Unique elements return hs.size; } // Driver codelet arr=[6, 10, 5, 4, 9,120, 4, 6, 10];document.write(countDistinct(arr,arr.length)); // This code is contributed by patel2127</script> 6 Time complexity: O(n) Auxiliary Space: O(n) Set STL approach: Sets are a type of associative containers in which each element has to be unique, because the value of the element identifies it. The value of the element cannot be modified once it is added to the set, though it is possible to remove and add the modified value of that element. We exploit the very basic property of set STL that it stores only unique numbers. Examples: Arr = [1,2,2,2,3,16,2,8,2,1,8] Distinct elements present = [1,2,3,16,8] Total number of distinct elements in the array are 5 Algorithm : 1. Insert all the elements into the set S one by one. 2. Store the total size s of the set using set::size(). 3.The total size s is the number of distinct elements present in the array. C++ Java Python3 C# Javascript #include <bits/stdc++.h>using namespace std;// function that accepts the array and it's size and returns// the number of distince elementsint distinct(int* arr, int len){ set<int> S; // declaring a set container using STL for (int i = 0; i < len; i++) { S.insert(arr[i]); // inserting all elements of the // array into set } int ans = S.size(); // calculating the size of the set return ans;}int main(){ int arr[] = { 12, 10, 9, 45, 2, 10, 10, 45}; int l = sizeof(arr) / sizeof( int); // calculating the size of the array int dis_elements = distinct(arr, l); // calling the function on array cout << dis_elements << endl; return 0;} import java.util.*;class GFG{ // function that accepts the array and it's size and returns // the number of distince elements static int distinct(int[] arr, int len) { HashSet<Integer> S = new HashSet<>(); // declaring a set container using STL for (int i = 0; i < len; i++) { S.add(arr[i]); // inserting all elements of the // array into set } int ans = S.size(); // calculating the size of the set return ans; } // Driver code public static void main(String[] args) { int arr[] = { 12, 10, 9, 45, 2, 10, 10, 45}; int l = arr.length; // calculating the size of the array int dis_elements = distinct(arr, l); // calling the function on array System.out.print(dis_elements +"\n"); }} // This code is contributed by Rajput-Ji # function that accepts the array and it's size and returns# the number of distince elementsdef distinct(arr, l): S = set(); # declaring a set container using STL for i in range(l): S.add(arr[i]); # inserting all elements of the # array into set ans = len(S); # calculating the size of the set return ans; # Driver codeif __name__ == '__main__': arr = [ 12, 10, 9, 45, 2, 10, 10, 45] ; l = len(arr); # calculating the size of the array dis_elements = distinct(arr, l); # calling the function on array print(dis_elements , ""); # This code is contributed by Rajput-Ji using System;using System.Collections.Generic; public class GFG{ // function that accepts the array and it's size and returns // the number of distince elements static int distinct(int[] arr, int len) { HashSet<int> S = new HashSet<int>(); // declaring a set container using STL for (int i = 0; i < len; i++) { S.Add(arr[i]); // inserting all elements of the // array into set } int ans = S.Count; // calculating the size of the set return ans; } // Driver code public static void Main(String[] args) { int []arr = { 12, 10, 9, 45, 2, 10, 10, 45 }; // calculating the size of the array int l = arr.Length; // calling the function on array int dis_elements = distinct(arr, l); Console.Write(dis_elements + "\n"); }} // This code is contributed by Rajput-Ji <script> // function that accepts the array and it's size and returns // the number of distince elements function distinct(arr , len) { var S = new Set(); // declaring a set container using STL var i =0; for (i = 0; i < len; i++) { S.add(arr[i]); // inserting all elements of the // array into set } var ans = S.size; // calculating the size of the set return ans; } // Driver code var arr = [ 12, 10, 9, 45, 2, 10, 10, 45 ]; var l = arr.length; // calculating the size of the array var dis_elements = distinct(arr, l); // calling the function on array document.write(dis_elements); // This code is contributed by Rajput-Ji.</script> 5 Time Complexity: O(n*log(n))Auxiliary Space: O(n) 29AjayKumar Adarsh_Verma mohit kumar 29 Code_Mech Akanksha_Rai Rajput-Ji princiraj1992 Mithun Kumar nidhi_biet SHUBHAMSINGH10 surbhityagi15 adityamutharia unknown2108 patel2127 simranarora5sos pushpeshrajdx01 cpp-unordered_set Arrays Hash Sorting Arrays Hash Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n29 Jun, 2022" }, { "code": null, "e": 123, "s": 52, "text": "Given an unsorted array, count all distinct elements in it.Examples: " }, { "code": null, "e": 277, "s": 123, "text": "Input : arr[] = {10, 20, 20, 10, 30, 10}\nOutput : 3\nThere are three distinct elements 10, 20 and 30.\n\nInput : arr[] = {10, 20, 20, 10, 20}\nOutput : 2" }, { "code": null, "e": 418, "s": 279, "text": "A simple solution is to run two loops. For every element, check if it has appeared before. If yes, increment count of distinct elements. " }, { "code": null, "e": 422, "s": 418, "text": "C++" }, { "code": null, "e": 427, "s": 422, "text": "Java" }, { "code": null, "e": 435, "s": 427, "text": "Python3" }, { "code": null, "e": 438, "s": 435, "text": "C#" }, { "code": null, "e": 442, "s": 438, "text": "PHP" }, { "code": null, "e": 453, "s": 442, "text": "Javascript" }, { "code": "// C++ program to count distinct elements// in a given array#include <iostream>using namespace std; int countDistinct(int arr[], int n){ int res = 1; // Pick all elements one by one for (int i = 1; i < n; i++) { int j = 0; for (j = 0; j < i; j++) if (arr[i] == arr[j]) break; // If not printed earlier, then print it if (i == j) res++; } return res;} // Driver program to test above functionint main(){ int arr[] = { 12, 10, 9, 45, 2, 10, 10, 45 }; int n = sizeof(arr) / sizeof(arr[0]); cout << countDistinct(arr, n); return 0;}", "e": 1076, "s": 453, "text": null }, { "code": "// Java program to count distinct// elements in a given arrayclass GFG{ static int countDistinct(int arr[], int n){ int res = 1; // Pick all elements one by one for (int i = 1; i < n; i++) { int j = 0; for (j = 0; j < i; j++) if (arr[i] == arr[j]) break; // If not printed earlier, // then print it if (i == j) res++; } return res;} // Driver codepublic static void main(String[] args){ int arr[] = { 12, 10, 9, 45, 2, 10, 10, 45 }; int n = arr.length; System.out.println(countDistinct(arr, n));}} // This code is contributed by Code_Mech.", "e": 1721, "s": 1076, "text": null }, { "code": "# Python3 program to count distinct# elements in a given arraydef countDistinct(arr, n): res = 1 # Pick all elements one by one for i in range(1, n): j = 0 for j in range(i): if (arr[i] == arr[j]): break # If not printed earlier, then print it if (i == j + 1): res += 1 return res # Driver Codearr = [12, 10, 9, 45, 2, 10, 10, 45]n = len(arr)print(countDistinct(arr, n)) # This code is contributed by Mohit Kumar", "e": 2219, "s": 1721, "text": null }, { "code": "// C# program to count distinct// elements in a given arrayusing System; class GFG{ static int countDistinct(int []arr, int n){ int res = 1; // Pick all elements one by one for (int i = 1; i < n; i++) { int j = 0; for (j = 0; j < i; j++) if (arr[i] == arr[j]) break; // If not printed earlier, // then print it if (i == j) res++; } return res;} // Driver codepublic static void Main(){ int []arr = { 12, 10, 9, 45, 2, 10, 10, 45 }; int n = arr.Length; Console.WriteLine(countDistinct(arr, n));}} // This code is contributed// by Akanksha Rai", "e": 2883, "s": 2219, "text": null }, { "code": "<?php// PHP program to count distinct elements// in a given arrayfunction countDistinct( &$arr, $n){ $res = 1; // Pick all elements one by one for ( $i = 1; $i < $n; $i++) { for ($j = 0; $j < $i; $j++) if ($arr[$i] == $arr[$j]) break; // If not printed earlier, // then print it if ($i == $j) $res++; } return $res;} // Driver Code$arr = array( 12, 10, 9, 45, 2, 10, 10, 45 );$n = count($arr);echo countDistinct($arr, $n); // This code is contributed by// Rajput-Ji?>", "e": 3437, "s": 2883, "text": null }, { "code": "<script> // JavaScript program to count distinct elements// in a given array function countDistinct(arr, n){ let res = 1; // Pick all elements one by one for (let i = 1; i < n; i++) { let j = 0; for (j = 0; j < i; j++) if (arr[i] === arr[j]) break; // If not printed earlier, then print it if (i === j) res++; } return res;} // Driver program to test above function let arr = [ 12, 10, 9, 45, 2, 10, 10, 45 ]; let n = arr.length; document.write(countDistinct(arr, n)); // This code is contributed by Surbhi Tyagi </script>", "e": 4052, "s": 3437, "text": null }, { "code": null, "e": 4054, "s": 4052, "text": "5" }, { "code": null, "e": 4421, "s": 4054, "text": "Time Complexity of above solution is O(n2). We can Use Sorting to solve the problem in O(nLogn) time. The idea is simple, first sort the array so that all occurrences of every element become consecutive. Once the occurrences become consecutive, we can traverse the sorted array and count distinct elements in O(n) time. Following is the implementation of the idea. " }, { "code": null, "e": 4425, "s": 4421, "text": "C++" }, { "code": null, "e": 4430, "s": 4425, "text": "Java" }, { "code": null, "e": 4438, "s": 4430, "text": "Python3" }, { "code": null, "e": 4441, "s": 4438, "text": "C#" }, { "code": null, "e": 4445, "s": 4441, "text": "PHP" }, { "code": null, "e": 4456, "s": 4445, "text": "Javascript" }, { "code": "// C++ program to count all distinct elements// in a given array#include <algorithm>#include <iostream>using namespace std; int countDistinct(int arr[], int n){ // First sort the array so that all // occurrences become consecutive sort(arr, arr + n); // Traverse the sorted array int res = 0; for (int i = 0; i < n; i++) { // Move the index ahead while // there are duplicates while (i < n - 1 && arr[i] == arr[i + 1]) i++; res++; } return res;} // Driver program to test above functionint main(){ int arr[] = { 6, 10, 5, 4, 9, 120, 4, 6, 10 }; int n = sizeof(arr) / sizeof(arr[0]); cout << countDistinct(arr, n); return 0;}", "e": 5160, "s": 4456, "text": null }, { "code": "// Java program to count all distinct elements// in a given arrayimport java.util.Arrays; class GFG{ static int countDistinct(int arr[], int n) { // First sort the array so that all // occurrences become consecutive Arrays.sort(arr); // Traverse the sorted array int res = 0; for (int i = 0; i < n; i++) { // Move the index ahead while // there are duplicates while (i < n - 1 && arr[i] == arr[i + 1]) { i++; } res++; } return res; } // Driver code public static void main(String[] args) { int arr[] = {6, 10, 5, 4, 9, 120, 4, 6, 10}; int n = arr.length; System.out.println(countDistinct(arr, n)); }} // This code is contributed by 29AjayKumar", "e": 6013, "s": 5160, "text": null }, { "code": "# Python3 program to count all distinct# elements in a given array def countDistinct(arr, n): # First sort the array so that all # occurrences become consecutive arr.sort(); # Traverse the sorted array res = 0; i = 0; while(i < n): # Move the index ahead while # there are duplicates while (i < n - 1 and arr[i] == arr[i + 1]): i += 1; res += 1; i += 1; return res; # Driver Codearr = [ 6, 10, 5, 4, 9, 120, 4, 6, 10 ];n = len(arr);print(countDistinct(arr, n)); # This code is contributed by mits", "e": 6599, "s": 6013, "text": null }, { "code": "// C# program to count all distinct elements// in a given arrayusing System; class GFG{ static int countDistinct(int[] arr, int n) { // First sort the array so that all // occurrences become consecutive Array.Sort(arr); // Traverse the sorted array int res = 0; for (int i = 0; i < n; i++) { // Move the index ahead while // there are duplicates while (i < n - 1 && arr[i] == arr[i + 1]) { i++; } res++; } return res; } // Driver code public static void Main() { int[] arr = {6, 10, 5, 4, 9, 120, 4, 6, 10}; int n = arr.Length; Console.WriteLine(countDistinct(arr, n)); }} // This code is contributed by Code_Mech.", "e": 7423, "s": 6599, "text": null }, { "code": "<?php// PHP program to count all distinct// elements in a given array function countDistinct($arr, $n){ // First sort the array so that all // occurrences become consecutive sort($arr, 0); // Traverse the sorted array $res = 0; for ($i = 0; $i < $n; $i++) { // Move the index ahead while // there are duplicates while ($i < $n - 1 && $arr[$i] == $arr[$i + 1]) $i++; $res++; } return $res;} // Driver Code$arr = array( 6, 10, 5, 4, 9, 120, 4, 6, 10 );$n = sizeof($arr);echo countDistinct($arr, $n); // This code is contributed by Akanksha Rai?>", "e": 8051, "s": 7423, "text": null }, { "code": "<script> // JavaScript program to count all distinct elements// in a given array function countDistinct(arr,n){ // First sort the array so that all // occurrences become consecutive arr.sort(function(a,b){return a-b;}); // Traverse the sorted array let res = 0; for (let i = 0; i < n; i++) { // Move the index ahead while // there are duplicates while (i < n - 1 && arr[i] == arr[i + 1]) { i++; } res++; } return res;} // Driver codelet arr=[6, 10, 5, 4, 9, 120, 4, 6, 10];let n = arr.length;document.write(countDistinct(arr, n)); // This code is contributed by unknown2108 </script>", "e": 8799, "s": 8051, "text": null }, { "code": null, "e": 8801, "s": 8799, "text": "6" }, { "code": null, "e": 9058, "s": 8801, "text": "We can Use Hashing to solve this in O(n) time on average. The idea is to traverse the given array from left to right and keep track of visited elements in a hash set , as a set consists of only unique elements. Following is the implementation of the idea. " }, { "code": null, "e": 9062, "s": 9058, "text": "C++" }, { "code": null, "e": 9067, "s": 9062, "text": "Java" }, { "code": null, "e": 9075, "s": 9067, "text": "Python3" }, { "code": null, "e": 9078, "s": 9075, "text": "C#" }, { "code": null, "e": 9082, "s": 9078, "text": "PHP" }, { "code": null, "e": 9093, "s": 9082, "text": "Javascript" }, { "code": "/* CPP program to print all distinct elements of a given array */#include <bits/stdc++.h>using namespace std; // This function prints all distinct elementsint countDistinct(int arr[], int n){ // Creates an empty hashset unordered_set<int> s; // Traverse the input array int res = 0; for (int i = 0; i < n; i++) { // If not present, then put it in // hashtable and increment result if (s.find(arr[i]) == s.end()) { s.insert(arr[i]); res++; } } return res;} // Driver program to test above functionint main(){ int arr[] = { 6, 10, 5, 4, 9, 120, 4, 6, 10 }; int n = sizeof(arr) / sizeof(arr[0]); cout << countDistinct(arr, n); return 0;}", "e": 9816, "s": 9093, "text": null }, { "code": "// Java Program to count// Unique elements in Arrayimport java.util.*; class GFG{ // This method returns count // of Unique elements public static int countDistinct(int arr[],int n) { HashSet<Integer> hs = new HashSet<Integer>(); for(int i = 0; i < n; i++) { // add all the elements to the HashSet hs.add(arr[i]); } // return the size of hashset as // it consists of all Unique elements return hs.size(); } // Driver code public static void main(String[] args) { int arr[] = new int[]{6, 10, 5, 4, 9, 120, 4, 6, 10}; System.out.println(countDistinct(arr, arr.length)); }} // This code is contributed by Adarsh_Verma", "e": 10627, "s": 9816, "text": null }, { "code": "''' Python3 program to print all distinct elementsof a given array ''' # This function prints all distinct elementsdef countDistinct(arr, n): # Creates an empty hashset s = set() # Traverse the input array res = 0 for i in range(n): # If not present, then put it in # hashtable and increment result if (arr[i] not in s): s.add(arr[i]) res += 1 return res # Driver codearr = [6, 10, 5, 4, 9, 120, 4, 6, 10]n = len(arr)print(countDistinct(arr, n)) # This code is contributed by SHUBHAMSINGH10", "e": 11195, "s": 10627, "text": null }, { "code": "// C# Program to count// Unique elements in Arrayusing System;using System.Collections.Generic; class GFG{ // This method returns count // of Unique elements public static int countDistinct(int []arr,int n) { HashSet<int> hs = new HashSet<int>(); for(int i = 0; i < n; i++) { // add all the elements to the HashSet hs.Add(arr[i]); } // return the size of hashset as // it consists of all Unique elements return hs.Count; } // Driver code public static void Main() { int []arr = new int[]{6, 10, 5, 4, 9, 120, 4, 6, 10}; Console.WriteLine(countDistinct(arr, arr.Length)); }} /* This code contributed by PrinciRaj1992 */", "e": 12009, "s": 11195, "text": null }, { "code": "<?php// PHP program to print all distinct elements// of a given array // This function prints all distinct elementsfunction countDistinct($arr, $n){ // Creates an empty hashset $s = array(); // Traverse the input array $res = 0; for ($i = 0; $i < $n; $i++) { // If not present, then put it in // hashtable and increment result array_push($s,$arr[$i]); } $s = array_unique($s); return count($s);} // Driver Code$arr = array( 6, 10, 5, 4, 9, 120, 4, 6, 10 );$n = count($arr);echo countDistinct($arr, $n); // This code is contributed by mits?>", "e": 12599, "s": 12009, "text": null }, { "code": "<script>// Javascript Program to count// Unique elements in Array // This method returns count // of Unique elementsfunction countDistinct(arr,n){ let hs = new Set(); for(let i = 0; i < n; i++) { // add all the elements to the HashSet hs.add(arr[i]); } // return the size of hashset as // it consists of all Unique elements return hs.size; } // Driver codelet arr=[6, 10, 5, 4, 9,120, 4, 6, 10];document.write(countDistinct(arr,arr.length)); // This code is contributed by patel2127</script>", "e": 13209, "s": 12599, "text": null }, { "code": null, "e": 13211, "s": 13209, "text": "6" }, { "code": null, "e": 13233, "s": 13211, "text": "Time complexity: O(n)" }, { "code": null, "e": 13255, "s": 13233, "text": "Auxiliary Space: O(n)" }, { "code": null, "e": 13273, "s": 13255, "text": "Set STL approach:" }, { "code": null, "e": 13635, "s": 13273, "text": " Sets are a type of associative containers in which each element has to be unique, because the value of the element identifies it. The value of the element cannot be modified once it is added to the set, though it is possible to remove and add the modified value of that element. We exploit the very basic property of set STL that it stores only unique numbers." }, { "code": null, "e": 13645, "s": 13635, "text": "Examples:" }, { "code": null, "e": 13676, "s": 13645, "text": "Arr = [1,2,2,2,3,16,2,8,2,1,8]" }, { "code": null, "e": 13717, "s": 13676, "text": "Distinct elements present = [1,2,3,16,8]" }, { "code": null, "e": 13770, "s": 13717, "text": "Total number of distinct elements in the array are 5" }, { "code": null, "e": 13782, "s": 13770, "text": "Algorithm :" }, { "code": null, "e": 13836, "s": 13782, "text": "1. Insert all the elements into the set S one by one." }, { "code": null, "e": 13893, "s": 13836, "text": "2. Store the total size s of the set using set::size()." }, { "code": null, "e": 13969, "s": 13893, "text": "3.The total size s is the number of distinct elements present in the array." }, { "code": null, "e": 13973, "s": 13969, "text": "C++" }, { "code": null, "e": 13978, "s": 13973, "text": "Java" }, { "code": null, "e": 13986, "s": 13978, "text": "Python3" }, { "code": null, "e": 13989, "s": 13986, "text": "C#" }, { "code": null, "e": 14000, "s": 13989, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std;// function that accepts the array and it's size and returns// the number of distince elementsint distinct(int* arr, int len){ set<int> S; // declaring a set container using STL for (int i = 0; i < len; i++) { S.insert(arr[i]); // inserting all elements of the // array into set } int ans = S.size(); // calculating the size of the set return ans;}int main(){ int arr[] = { 12, 10, 9, 45, 2, 10, 10, 45}; int l = sizeof(arr) / sizeof( int); // calculating the size of the array int dis_elements = distinct(arr, l); // calling the function on array cout << dis_elements << endl; return 0;}", "e": 14728, "s": 14000, "text": null }, { "code": "import java.util.*;class GFG{ // function that accepts the array and it's size and returns // the number of distince elements static int distinct(int[] arr, int len) { HashSet<Integer> S = new HashSet<>(); // declaring a set container using STL for (int i = 0; i < len; i++) { S.add(arr[i]); // inserting all elements of the // array into set } int ans = S.size(); // calculating the size of the set return ans; } // Driver code public static void main(String[] args) { int arr[] = { 12, 10, 9, 45, 2, 10, 10, 45}; int l = arr.length; // calculating the size of the array int dis_elements = distinct(arr, l); // calling the function on array System.out.print(dis_elements +\"\\n\"); }} // This code is contributed by Rajput-Ji", "e": 15505, "s": 14728, "text": null }, { "code": "# function that accepts the array and it's size and returns# the number of distince elementsdef distinct(arr, l): S = set(); # declaring a set container using STL for i in range(l): S.add(arr[i]); # inserting all elements of the # array into set ans = len(S); # calculating the size of the set return ans; # Driver codeif __name__ == '__main__': arr = [ 12, 10, 9, 45, 2, 10, 10, 45] ; l = len(arr); # calculating the size of the array dis_elements = distinct(arr, l); # calling the function on array print(dis_elements , \"\"); # This code is contributed by Rajput-Ji", "e": 16115, "s": 15505, "text": null }, { "code": "using System;using System.Collections.Generic; public class GFG{ // function that accepts the array and it's size and returns // the number of distince elements static int distinct(int[] arr, int len) { HashSet<int> S = new HashSet<int>(); // declaring a set container using STL for (int i = 0; i < len; i++) { S.Add(arr[i]); // inserting all elements of the // array into set } int ans = S.Count; // calculating the size of the set return ans; } // Driver code public static void Main(String[] args) { int []arr = { 12, 10, 9, 45, 2, 10, 10, 45 }; // calculating the size of the array int l = arr.Length; // calling the function on array int dis_elements = distinct(arr, l); Console.Write(dis_elements + \"\\n\"); }} // This code is contributed by Rajput-Ji", "e": 16939, "s": 16115, "text": null }, { "code": "<script> // function that accepts the array and it's size and returns // the number of distince elements function distinct(arr , len) { var S = new Set(); // declaring a set container using STL var i =0; for (i = 0; i < len; i++) { S.add(arr[i]); // inserting all elements of the // array into set } var ans = S.size; // calculating the size of the set return ans; } // Driver code var arr = [ 12, 10, 9, 45, 2, 10, 10, 45 ]; var l = arr.length; // calculating the size of the array var dis_elements = distinct(arr, l); // calling the function on array document.write(dis_elements); // This code is contributed by Rajput-Ji.</script>", "e": 17691, "s": 16939, "text": null }, { "code": null, "e": 17693, "s": 17691, "text": "5" }, { "code": null, "e": 17743, "s": 17693, "text": "Time Complexity: O(n*log(n))Auxiliary Space: O(n)" }, { "code": null, "e": 17755, "s": 17743, "text": "29AjayKumar" }, { "code": null, "e": 17768, "s": 17755, "text": "Adarsh_Verma" }, { "code": null, "e": 17783, "s": 17768, "text": "mohit kumar 29" }, { "code": null, "e": 17793, "s": 17783, "text": "Code_Mech" }, { "code": null, "e": 17806, "s": 17793, "text": "Akanksha_Rai" }, { "code": null, "e": 17816, "s": 17806, "text": "Rajput-Ji" }, { "code": null, "e": 17830, "s": 17816, "text": "princiraj1992" }, { "code": null, "e": 17843, "s": 17830, "text": "Mithun Kumar" }, { "code": null, "e": 17854, "s": 17843, "text": "nidhi_biet" }, { "code": null, "e": 17869, "s": 17854, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 17883, "s": 17869, "text": "surbhityagi15" }, { "code": null, "e": 17898, "s": 17883, "text": "adityamutharia" }, { "code": null, "e": 17910, "s": 17898, "text": "unknown2108" }, { "code": null, "e": 17920, "s": 17910, "text": "patel2127" }, { "code": null, "e": 17936, "s": 17920, "text": "simranarora5sos" }, { "code": null, "e": 17952, "s": 17936, "text": "pushpeshrajdx01" }, { "code": null, "e": 17970, "s": 17952, "text": "cpp-unordered_set" }, { "code": null, "e": 17977, "s": 17970, "text": "Arrays" }, { "code": null, "e": 17982, "s": 17977, "text": "Hash" }, { "code": null, "e": 17990, "s": 17982, "text": "Sorting" }, { "code": null, "e": 17997, "s": 17990, "text": "Arrays" }, { "code": null, "e": 18002, "s": 17997, "text": "Hash" }, { "code": null, "e": 18010, "s": 18002, "text": "Sorting" } ]
Display Property in Bootstrap with Examples
24 Jan, 2019 The display property in Bootstrap is used to set an element’s display property. The utilities such as block, inline etc are to set the element’s display property. The display property classes of bootstrap help to directly set the CSS display property for an element. The available classes are: .d-block: This class when used with an element, sets it display property to block. Using this class with an element is equivalent to the below styling:style = "display: block;" style = "display: block;" .d-inline: This class when used with an element, sets it display property to inline. Using this class with an element is equivalent to the below styling:style = "display: inline;" style = "display: inline;" .d-inline-block: This class when used with an element, sets it display property to inline-block. Using this class with an element is equivalent to the below styling:style = "display: inline-block;" style = "display: inline-block;" Syntax: <div class=”d-inline”> Inline </div> // for inline display <div class=”d-block”> Block </div> // for block display <div class=”d-inline-block”> Inline Block </div> // for inline-block display Below examples illustrate the use of the display properties classes of bootstrap: Example 1: <!DOCTYPE html><html> <head> <style> div{ font-size: 30px; } </style> <!-- Include Bootstrap CSS and JS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <title>Webpage</title></head> <body> <div class="d-block bg-primary"> GeeksforGeeks </div> <div class="d-block bg-primary"> GeeksforGeeks </div> </body></html> Output: Example 2: <!DOCTYPE html><html> <head> <style> div{ font-size: 30px; } </style> <!-- Add Bootstrap CSS and JS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> <title>Webpage</title></head> <body> <div class="d-inline bg-success"> GeeksforGeeks </div> <div class="d-inline bg-success"> GeeksforGeeks </div> </body></html> Output: Example 3: <!DOCTYPE html><html> <head> <style> body{ font-size: 75px; } </style> <!-- Add Bootstrap CSS and JS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> <title>Webpage</title></head> <body> <div class="d-inline-block bg-warning"> GeeksforGeeks </div> <div class="d-inline-block bg-warning"> GeeksforGeeks </div></body></html> Output: Picked Bootstrap CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to change navigation bar color in Bootstrap ? Form validation using jQuery How to pass data into a bootstrap modal? How to align navbar items to the right in Bootstrap 4 ? How to Show Images on Click using HTML ? How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? CSS to put icon inside an input element in a form
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Jan, 2019" }, { "code": null, "e": 191, "s": 28, "text": "The display property in Bootstrap is used to set an element’s display property. The utilities such as block, inline etc are to set the element’s display property." }, { "code": null, "e": 295, "s": 191, "text": "The display property classes of bootstrap help to directly set the CSS display property for an element." }, { "code": null, "e": 322, "s": 295, "text": "The available classes are:" }, { "code": null, "e": 500, "s": 322, "text": ".d-block: This class when used with an element, sets it display property to block. Using this class with an element is equivalent to the below styling:style = \"display: block;\"\n" }, { "code": null, "e": 527, "s": 500, "text": "style = \"display: block;\"\n" }, { "code": null, "e": 708, "s": 527, "text": ".d-inline: This class when used with an element, sets it display property to inline. Using this class with an element is equivalent to the below styling:style = \"display: inline;\"\n" }, { "code": null, "e": 736, "s": 708, "text": "style = \"display: inline;\"\n" }, { "code": null, "e": 935, "s": 736, "text": ".d-inline-block: This class when used with an element, sets it display property to inline-block. Using this class with an element is equivalent to the below styling:style = \"display: inline-block;\"\n" }, { "code": null, "e": 969, "s": 935, "text": "style = \"display: inline-block;\"\n" }, { "code": null, "e": 977, "s": 969, "text": "Syntax:" }, { "code": null, "e": 1036, "s": 977, "text": "<div class=”d-inline”> Inline </div> // for inline display" }, { "code": null, "e": 1092, "s": 1036, "text": "<div class=”d-block”> Block </div> // for block display" }, { "code": null, "e": 1169, "s": 1092, "text": "<div class=”d-inline-block”> Inline Block </div> // for inline-block display" }, { "code": null, "e": 1251, "s": 1169, "text": "Below examples illustrate the use of the display properties classes of bootstrap:" }, { "code": null, "e": 1262, "s": 1251, "text": "Example 1:" }, { "code": "<!DOCTYPE html><html> <head> <style> div{ font-size: 30px; } </style> <!-- Include Bootstrap CSS and JS --> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js\"></script> <title>Webpage</title></head> <body> <div class=\"d-block bg-primary\"> GeeksforGeeks </div> <div class=\"d-block bg-primary\"> GeeksforGeeks </div> </body></html>", "e": 1897, "s": 1262, "text": null }, { "code": null, "e": 1905, "s": 1897, "text": "Output:" }, { "code": null, "e": 1916, "s": 1905, "text": "Example 2:" }, { "code": "<!DOCTYPE html><html> <head> <style> div{ font-size: 30px; } </style> <!-- Add Bootstrap CSS and JS --> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\" integrity=\"sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm\" crossorigin=\"anonymous\"> <script src=\"https://code.jquery.com/jquery-3.2.1.slim.min.js\" integrity=\"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN\" crossorigin=\"anonymous\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js\" integrity=\"sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q\" crossorigin=\"anonymous\"></script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js\" integrity=\"sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl\" crossorigin=\"anonymous\"></script> <title>Webpage</title></head> <body> <div class=\"d-inline bg-success\"> GeeksforGeeks </div> <div class=\"d-inline bg-success\"> GeeksforGeeks </div> </body></html>", "e": 3064, "s": 1916, "text": null }, { "code": null, "e": 3072, "s": 3064, "text": "Output:" }, { "code": null, "e": 3083, "s": 3072, "text": "Example 3:" }, { "code": "<!DOCTYPE html><html> <head> <style> body{ font-size: 75px; } </style> <!-- Add Bootstrap CSS and JS --> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\" integrity=\"sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm\" crossorigin=\"anonymous\"> <script src=\"https://code.jquery.com/jquery-3.2.1.slim.min.js\" integrity=\"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN\" crossorigin=\"anonymous\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js\" integrity=\"sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q\" crossorigin=\"anonymous\"></script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js\" integrity=\"sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl\" crossorigin=\"anonymous\"></script> <title>Webpage</title></head> <body> <div class=\"d-inline-block bg-warning\"> GeeksforGeeks </div> <div class=\"d-inline-block bg-warning\"> GeeksforGeeks </div></body></html>", "e": 4252, "s": 3083, "text": null }, { "code": null, "e": 4260, "s": 4252, "text": "Output:" }, { "code": null, "e": 4267, "s": 4260, "text": "Picked" }, { "code": null, "e": 4277, "s": 4267, "text": "Bootstrap" }, { "code": null, "e": 4281, "s": 4277, "text": "CSS" }, { "code": null, "e": 4298, "s": 4281, "text": "Web Technologies" }, { "code": null, "e": 4396, "s": 4298, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4446, "s": 4396, "text": "How to change navigation bar color in Bootstrap ?" }, { "code": null, "e": 4475, "s": 4446, "text": "Form validation using jQuery" }, { "code": null, "e": 4516, "s": 4475, "text": "How to pass data into a bootstrap modal?" }, { "code": null, "e": 4572, "s": 4516, "text": "How to align navbar items to the right in Bootstrap 4 ?" }, { "code": null, "e": 4613, "s": 4572, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 4661, "s": 4613, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 4723, "s": 4661, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4773, "s": 4723, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 4831, "s": 4773, "text": "How to create footer to stay at the bottom of a Web page?" } ]
TCL script to create FTP traffic over TCP
09 Mar, 2021 In this article, we are going to know how to write a tool command script to simulate TCP connection between 2 nodes and pass FTP traffic between them in ns2. We will also know how to display throughput packets dropped, received and sent. Introduction :The routing algorithm used in the program is the Distance Vector Routing Protocol. If you are not familiar with the Network Simulator and Tool Command Language you can check this first https://www.geeksforgeeks.org/basics-of-ns2-and-otcltcl-script/. Now, let’s discuss the implementation part of TCL script to create FTP traffic over TCP step by step as follows. Step-1 :Firstly, we need to create a network Simulator object and initialize the routing protocol (rtproto) as Distance Vector Routing Protocol (DV). set ns [new Simulator] $ns rtproto DV Step-2 :Next we create two nodes node 0 and node 1 using the node instance in the network simulator object. set node0 [$ns node] set node1 [$ns node] Step-3 :The next step is to create the trace file and nam file. Here they are named as out.tr and out.nam respectively. All we need to do is to use a trace file object to create a new trace file named out.tr and open the file in write mode. The next step would be trace all the routing information during the simulation to the trace file using trace-all. We do the same in case of the nam file as well using namtrace-all. set tf [open out.tr w] $ns trace-all $tf set nf [open out.nam w] $ns namtrace-all $nf Step-4 :We now create a duplex link between the nodes using the duplex-link instance. Here we need to specify three parameters: the data rate (1Mb), delay (10ms) and the kind of queue (DropTail). $ns duplex-link $node0 $node1 1Mb 10ms DropTail Step-5 :Agents are meant to carry information between nodes in a network. We now need TCP agents to accomplish that task. The agents are initialized as follows. Furthermore, the agents are attached to node 0 and node 1 respectively. Next step is to connect those agents. set tcp2 [new Agent/TCP] $ns attach-agent $node0 $tcp2 set sink2 [new Agent/TCPSink] $ns attach-agent $node1 $sink2 $ns connect $tcp2 $sink2 Step-6 : Our next step is to initialize FTP traffic and attach to the source tcp2. This can be done by creating an FTP object and thus attaching the traffic to tcp2. set traffic_ftp2 [new Application/FTP] $traffic_ftp2 attach-agent $tcp2 Step-7 :Next, we add a finish procedure to flush all data into the trace file and then run the nam file. proc finish {} { global ns nf tf $ns flush-trace close $nf close $tf exec nam out.nam & exit 0 } Step-8 :We finally close the tcl file by scheduling events for the FTP agent and the run command. Here the traffic starts at time 1.0 and stops at 3.0. The simulation ends at time 5.0. It can be customized for longer or shorter durations. The file ends with a run instance. $ns at 1.0 "traffic_ftp2 start" $ns at 3.0 "traffic_ftp2 stop" $ns at 5.0 "finish" $ns run awk file creation :Let’s know how to create an awk file to view the number of packets received, dropped and the overall throughput as follows. Step-1 : Initialization part – The awk file starts with the initialization part which is specified in the BEGIN block. It contains all required initializations of constants or variables. Here we need the variables send, received and dropped to keep track of such sent, received and dropped packets respectively. Next we need the start a stop values to begin and end traffic. BEGIN{ send=0; received=0; dropped=0; start=1.0; stop=3.0; } Step-2 : Content block execution – The next block is the content block. In this part line by line will be executed. There are certain variables $1, $5 which have different meanings. Such conventions map to a certain pattern or logic in the trace file. The expression β€œ/+/” means that the packet was sent, β€œr” means a packet was received and β€œd” means a packet was dropped. For all such actions mapping $1 is used. $5 is a flag which is used to map with the string β€œTCP”. { if($1=="/+/") { send++; } if($5=="tcp") { if($1=="r") { received++; } } if($1=="d"){ dropped++; } } Step-3 : END block – The END block is the last block in the awk file used to print the number of received packets and the overall throughput. If the ftp traffic was not initialized then no packets would be sent or received. In this case the trace file is empty. Otherwise, we can print required parameters. END{ if(send=="0" && received=="0") { print "empty trace file\t" } print "Number of Packets Received " received print "Throughput =" (received*8)/(start-stop) "bits per second" print "Number of Packets Dropped = " dropped } Visualization of network simulator :We can visualize the output in the network simulator as follows. On clicking on the start button highlighted in green in the figure, the traffic flow starts at 1.0 and ends at 3.0. In the meantime the awk file calculates and stores the required values to be computed. Furthermore, to evaluate the traffic we can calculate throughput and dropped packets in the awk file. The following command is used to run an awk file. awk -f filename.awk filename.tr The output obtained will be something like this as follows. Note –Since the connection between nodes was not terminated at any instant, there won’t be any dropped packets. However, the simulation can be customized to include such terminations at certain intervals and in such cases dropped packets may exist. Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GSM in Wireless Communication Wireless Application Protocol Secure Socket Layer (SSL) Mobile Internet Protocol (or Mobile IP) Advanced Encryption Standard (AES) Introduction of Mobile Ad hoc Network (MANET) Cryptography and its Types Intrusion Detection System (IDS) Dynamic Host Configuration Protocol (DHCP) Difference between FDMA, TDMA and CDMA
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Mar, 2021" }, { "code": null, "e": 267, "s": 28, "text": "In this article, we are going to know how to write a tool command script to simulate TCP connection between 2 nodes and pass FTP traffic between them in ns2. We will also know how to display throughput packets dropped, received and sent. " }, { "code": null, "e": 644, "s": 267, "text": "Introduction :The routing algorithm used in the program is the Distance Vector Routing Protocol. If you are not familiar with the Network Simulator and Tool Command Language you can check this first https://www.geeksforgeeks.org/basics-of-ns2-and-otcltcl-script/. Now, let’s discuss the implementation part of TCL script to create FTP traffic over TCP step by step as follows." }, { "code": null, "e": 794, "s": 644, "text": "Step-1 :Firstly, we need to create a network Simulator object and initialize the routing protocol (rtproto) as Distance Vector Routing Protocol (DV)." }, { "code": null, "e": 832, "s": 794, "text": "set ns [new Simulator]\n$ns rtproto DV" }, { "code": null, "e": 940, "s": 832, "text": "Step-2 :Next we create two nodes node 0 and node 1 using the node instance in the network simulator object." }, { "code": null, "e": 982, "s": 940, "text": "set node0 [$ns node]\nset node1 [$ns node]" }, { "code": null, "e": 1404, "s": 982, "text": "Step-3 :The next step is to create the trace file and nam file. Here they are named as out.tr and out.nam respectively. All we need to do is to use a trace file object to create a new trace file named out.tr and open the file in write mode. The next step would be trace all the routing information during the simulation to the trace file using trace-all. We do the same in case of the nam file as well using namtrace-all." }, { "code": null, "e": 1490, "s": 1404, "text": "set tf [open out.tr w]\n$ns trace-all $tf\nset nf [open out.nam w]\n$ns namtrace-all $nf" }, { "code": null, "e": 1686, "s": 1490, "text": "Step-4 :We now create a duplex link between the nodes using the duplex-link instance. Here we need to specify three parameters: the data rate (1Mb), delay (10ms) and the kind of queue (DropTail)." }, { "code": null, "e": 1734, "s": 1686, "text": "$ns duplex-link $node0 $node1 1Mb 10ms DropTail" }, { "code": null, "e": 2005, "s": 1734, "text": "Step-5 :Agents are meant to carry information between nodes in a network. We now need TCP agents to accomplish that task. The agents are initialized as follows. Furthermore, the agents are attached to node 0 and node 1 respectively. Next step is to connect those agents." }, { "code": null, "e": 2146, "s": 2005, "text": "set tcp2 [new Agent/TCP]\n$ns attach-agent $node0 $tcp2\nset sink2 [new Agent/TCPSink]\n$ns attach-agent $node1 $sink2\n$ns connect $tcp2 $sink2" }, { "code": null, "e": 2312, "s": 2146, "text": "Step-6 : Our next step is to initialize FTP traffic and attach to the source tcp2. This can be done by creating an FTP object and thus attaching the traffic to tcp2." }, { "code": null, "e": 2384, "s": 2312, "text": "set traffic_ftp2 [new Application/FTP]\n$traffic_ftp2 attach-agent $tcp2" }, { "code": null, "e": 2489, "s": 2384, "text": "Step-7 :Next, we add a finish procedure to flush all data into the trace file and then run the nam file." }, { "code": null, "e": 2589, "s": 2489, "text": "proc finish {} {\n\nglobal ns nf tf\n$ns flush-trace\nclose $nf\nclose $tf\nexec nam out.nam &\nexit 0\n \n}" }, { "code": null, "e": 2863, "s": 2589, "text": "Step-8 :We finally close the tcl file by scheduling events for the FTP agent and the run command. Here the traffic starts at time 1.0 and stops at 3.0. The simulation ends at time 5.0. It can be customized for longer or shorter durations. The file ends with a run instance." }, { "code": null, "e": 2954, "s": 2863, "text": "$ns at 1.0 \"traffic_ftp2 start\"\n$ns at 3.0 \"traffic_ftp2 stop\"\n$ns at 5.0 \"finish\"\n$ns run" }, { "code": null, "e": 3097, "s": 2954, "text": "awk file creation :Let’s know how to create an awk file to view the number of packets received, dropped and the overall throughput as follows." }, { "code": null, "e": 3128, "s": 3097, "text": "Step-1 : Initialization part –" }, { "code": null, "e": 3472, "s": 3128, "text": "The awk file starts with the initialization part which is specified in the BEGIN block. It contains all required initializations of constants or variables. Here we need the variables send, received and dropped to keep track of such sent, received and dropped packets respectively. Next we need the start a stop values to begin and end traffic." }, { "code": null, "e": 3533, "s": 3472, "text": "BEGIN{\nsend=0;\nreceived=0;\ndropped=0;\nstart=1.0;\nstop=3.0;\n}" }, { "code": null, "e": 3568, "s": 3533, "text": "Step-2 : Content block execution –" }, { "code": null, "e": 4004, "s": 3568, "text": "The next block is the content block. In this part line by line will be executed. There are certain variables $1, $5 which have different meanings. Such conventions map to a certain pattern or logic in the trace file. The expression β€œ/+/” means that the packet was sent, β€œr” means a packet was received and β€œd” means a packet was dropped. For all such actions mapping $1 is used. $5 is a flag which is used to map with the string β€œTCP”." }, { "code": null, "e": 4112, "s": 4004, "text": "{\nif($1==\"/+/\")\n{\nsend++;\n}\n \nif($5==\"tcp\")\n{\nif($1==\"r\")\n{\nreceived++;\n}\n}\n \nif($1==\"d\"){\ndropped++;\n}\n} " }, { "code": null, "e": 4133, "s": 4112, "text": "Step-3 : END block –" }, { "code": null, "e": 4420, "s": 4133, "text": "The END block is the last block in the awk file used to print the number of received packets and the overall throughput. If the ftp traffic was not initialized then no packets would be sent or received. In this case the trace file is empty. Otherwise, we can print required parameters. " }, { "code": null, "e": 4645, "s": 4420, "text": "END{\nif(send==\"0\" && received==\"0\")\n{\nprint \"empty trace file\\t\"\n}\nprint \"Number of Packets Received \" received\nprint \"Throughput =\" (received*8)/(start-stop) \"bits per second\"\nprint \"Number of Packets Dropped = \" dropped\n}" }, { "code": null, "e": 4746, "s": 4645, "text": "Visualization of network simulator :We can visualize the output in the network simulator as follows." }, { "code": null, "e": 4949, "s": 4746, "text": "On clicking on the start button highlighted in green in the figure, the traffic flow starts at 1.0 and ends at 3.0. In the meantime the awk file calculates and stores the required values to be computed." }, { "code": null, "e": 5101, "s": 4949, "text": "Furthermore, to evaluate the traffic we can calculate throughput and dropped packets in the awk file. The following command is used to run an awk file." }, { "code": null, "e": 5133, "s": 5101, "text": "awk -f filename.awk filename.tr" }, { "code": null, "e": 5193, "s": 5133, "text": "The output obtained will be something like this as follows." }, { "code": null, "e": 5442, "s": 5193, "text": "Note –Since the connection between nodes was not terminated at any instant, there won’t be any dropped packets. However, the simulation can be customized to include such terminations at certain intervals and in such cases dropped packets may exist." }, { "code": null, "e": 5460, "s": 5442, "text": "Computer Networks" }, { "code": null, "e": 5478, "s": 5460, "text": "Computer Networks" }, { "code": null, "e": 5576, "s": 5478, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5606, "s": 5576, "text": "GSM in Wireless Communication" }, { "code": null, "e": 5636, "s": 5606, "text": "Wireless Application Protocol" }, { "code": null, "e": 5662, "s": 5636, "text": "Secure Socket Layer (SSL)" }, { "code": null, "e": 5702, "s": 5662, "text": "Mobile Internet Protocol (or Mobile IP)" }, { "code": null, "e": 5737, "s": 5702, "text": "Advanced Encryption Standard (AES)" }, { "code": null, "e": 5783, "s": 5737, "text": "Introduction of Mobile Ad hoc Network (MANET)" }, { "code": null, "e": 5810, "s": 5783, "text": "Cryptography and its Types" }, { "code": null, "e": 5843, "s": 5810, "text": "Intrusion Detection System (IDS)" }, { "code": null, "e": 5886, "s": 5843, "text": "Dynamic Host Configuration Protocol (DHCP)" } ]
Program to print ASCII Value of a character
30 Mar, 2022 Given a character, we need to print its ASCII value in C/C++/Java/Python. Examples : Input : a Output : 97 Input : D Output : 68 Here are few methods in different programming languages to print ASCII value of a given character : Python code using ord function :ord() : It converts the given string of length one, returns an integer representing the Unicode code point of the character. For example, ord(β€˜a’) returns the integer 97.PythonPython# Python program to print # ASCII Value of Character # In c we can assign different# characters of which we want ASCII value c = 'g'# print the ASCII value of assigned character in cprint("The ASCII value of '" + c + "' is", ord(c))Output:The ASCII value of g is 103 C code: We use format specifier here to give numeric value of character. Here %d is used to convert character to its ASCII value.CC// C program to print// ASCII Value of Character#include <stdio.h>int main(){ char c = 'k'; // %d displays the integer value of a character // %c displays the actual character printf("The ASCII value of %c is %d", c, c); return 0;}Output:The ASCII value of k is 107 C++ code: Here int() is used to convert character to its ASCII value.CPPCPP// CPP program to print// ASCII Value of Character#include <iostream>using namespace std;int main(){ char c = 'A'; cout << "The ASCII value of " << c << " is " << int(c); return 0;}Output:The ASCII value of A is 65 Java code : Here, to find the ASCII value of c, we just assign c to an int variable ascii. Internally, Java converts the character value to an ASCII value.JavaJava// Java program to print// ASCII Value of Characterpublic class AsciiValue { public static void main(String[] args) { char c = 'e'; int ascii = c; System.out.println("The ASCII value of " + c + " is: " + ascii); }}C# code : Here, to find the ASCII value of c, we just assign c to an int variable ascii. Internally, C# converts the character value to an ASCII value.CSHARPCSHARP// C# program to print// ASCII Value of Characterusing System; public class AsciiValue { public static void Main() { char c = 'e'; int ascii = c; Console.Write("The ASCII value of " + c + " is: " + ascii); }} // This code is contributed // by nitin mittalOutput:The ASCII value of e is 101 Python code using ord function :ord() : It converts the given string of length one, returns an integer representing the Unicode code point of the character. For example, ord(β€˜a’) returns the integer 97.PythonPython# Python program to print # ASCII Value of Character # In c we can assign different# characters of which we want ASCII value c = 'g'# print the ASCII value of assigned character in cprint("The ASCII value of '" + c + "' is", ord(c))Output:The ASCII value of g is 103 Python # Python program to print # ASCII Value of Character # In c we can assign different# characters of which we want ASCII value c = 'g'# print the ASCII value of assigned character in cprint("The ASCII value of '" + c + "' is", ord(c)) The ASCII value of g is 103 C code: We use format specifier here to give numeric value of character. Here %d is used to convert character to its ASCII value.CC// C program to print// ASCII Value of Character#include <stdio.h>int main(){ char c = 'k'; // %d displays the integer value of a character // %c displays the actual character printf("The ASCII value of %c is %d", c, c); return 0;}Output:The ASCII value of k is 107 C // C program to print// ASCII Value of Character#include <stdio.h>int main(){ char c = 'k'; // %d displays the integer value of a character // %c displays the actual character printf("The ASCII value of %c is %d", c, c); return 0;} The ASCII value of k is 107 C++ code: Here int() is used to convert character to its ASCII value.CPPCPP// CPP program to print// ASCII Value of Character#include <iostream>using namespace std;int main(){ char c = 'A'; cout << "The ASCII value of " << c << " is " << int(c); return 0;}Output:The ASCII value of A is 65 CPP // CPP program to print// ASCII Value of Character#include <iostream>using namespace std;int main(){ char c = 'A'; cout << "The ASCII value of " << c << " is " << int(c); return 0;} The ASCII value of A is 65 Java code : Here, to find the ASCII value of c, we just assign c to an int variable ascii. Internally, Java converts the character value to an ASCII value.JavaJava// Java program to print// ASCII Value of Characterpublic class AsciiValue { public static void main(String[] args) { char c = 'e'; int ascii = c; System.out.println("The ASCII value of " + c + " is: " + ascii); }} Java // Java program to print// ASCII Value of Characterpublic class AsciiValue { public static void main(String[] args) { char c = 'e'; int ascii = c; System.out.println("The ASCII value of " + c + " is: " + ascii); }} C# code : Here, to find the ASCII value of c, we just assign c to an int variable ascii. Internally, C# converts the character value to an ASCII value.CSHARPCSHARP// C# program to print// ASCII Value of Characterusing System; public class AsciiValue { public static void Main() { char c = 'e'; int ascii = c; Console.Write("The ASCII value of " + c + " is: " + ascii); }} // This code is contributed // by nitin mittalOutput:The ASCII value of e is 101 CSHARP // C# program to print// ASCII Value of Characterusing System; public class AsciiValue { public static void Main() { char c = 'e'; int ascii = c; Console.Write("The ASCII value of " + c + " is: " + ascii); }} // This code is contributed // by nitin mittal Output: The ASCII value of e is 101 Here is a method to print the ASCII value of the characters in a string using python: Python3 print("Enter a String: ", end="")text = input()textlength = len(text)for char in text: ascii = ord(char) print(char, "\t", ascii) Input: Enter a String: Aditya Trivedi Output: A 65 d 100 i 105 t 116 y 121 a 97 32 T 84 r 114 i 105 v 118 e 101 d 100 i 105 nitin mittal saurabh1990aror adityatri ASCII C Programs C++ Programs Java Programs Python Programs School Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C Program to read contents of Whole File C++ Program to check Prime Number Producer Consumer Problem in C C Program to Swap two Numbers Set, Clear and Toggle a given bit of a number in C Sorting a Map by value in C++ STL Shallow Copy and Deep Copy in C++ C++ program for hashing with chaining C++ Program to check if a given String is Palindrome or not delete keyword in C++
[ { "code": null, "e": 52, "s": 24, "text": "\n30 Mar, 2022" }, { "code": null, "e": 126, "s": 52, "text": "Given a character, we need to print its ASCII value in C/C++/Java/Python." }, { "code": null, "e": 137, "s": 126, "text": "Examples :" }, { "code": null, "e": 184, "s": 137, "text": "Input : a \nOutput : 97\n\nInput : D\nOutput : 68\n" }, { "code": null, "e": 284, "s": 184, "text": "Here are few methods in different programming languages to print ASCII value of a given character :" }, { "code": null, "e": 2404, "s": 284, "text": "Python code using ord function :ord() : It converts the given string of length one, returns an integer representing the Unicode code point of the character. For example, ord(β€˜a’) returns the integer 97.PythonPython# Python program to print # ASCII Value of Character # In c we can assign different# characters of which we want ASCII value c = 'g'# print the ASCII value of assigned character in cprint(\"The ASCII value of '\" + c + \"' is\", ord(c))Output:The ASCII value of g is 103\nC code: We use format specifier here to give numeric value of character. Here %d is used to convert character to its ASCII value.CC// C program to print// ASCII Value of Character#include <stdio.h>int main(){ char c = 'k'; // %d displays the integer value of a character // %c displays the actual character printf(\"The ASCII value of %c is %d\", c, c); return 0;}Output:The ASCII value of k is 107\nC++ code: Here int() is used to convert character to its ASCII value.CPPCPP// CPP program to print// ASCII Value of Character#include <iostream>using namespace std;int main(){ char c = 'A'; cout << \"The ASCII value of \" << c << \" is \" << int(c); return 0;}Output:The ASCII value of A is 65\nJava code : Here, to find the ASCII value of c, we just assign c to an int variable ascii. Internally, Java converts the character value to an ASCII value.JavaJava// Java program to print// ASCII Value of Characterpublic class AsciiValue { public static void main(String[] args) { char c = 'e'; int ascii = c; System.out.println(\"The ASCII value of \" + c + \" is: \" + ascii); }}C# code : Here, to find the ASCII value of c, we just assign c to an int variable ascii. Internally, C# converts the character value to an ASCII value.CSHARPCSHARP// C# program to print// ASCII Value of Characterusing System; public class AsciiValue { public static void Main() { char c = 'e'; int ascii = c; Console.Write(\"The ASCII value of \" + c + \" is: \" + ascii); }} // This code is contributed // by nitin mittalOutput:The ASCII value of e is 101\n" }, { "code": null, "e": 2889, "s": 2404, "text": "Python code using ord function :ord() : It converts the given string of length one, returns an integer representing the Unicode code point of the character. For example, ord(β€˜a’) returns the integer 97.PythonPython# Python program to print # ASCII Value of Character # In c we can assign different# characters of which we want ASCII value c = 'g'# print the ASCII value of assigned character in cprint(\"The ASCII value of '\" + c + \"' is\", ord(c))Output:The ASCII value of g is 103\n" }, { "code": null, "e": 2896, "s": 2889, "text": "Python" }, { "code": "# Python program to print # ASCII Value of Character # In c we can assign different# characters of which we want ASCII value c = 'g'# print the ASCII value of assigned character in cprint(\"The ASCII value of '\" + c + \"' is\", ord(c))", "e": 3132, "s": 2896, "text": null }, { "code": null, "e": 3161, "s": 3132, "text": "The ASCII value of g is 103\n" }, { "code": null, "e": 3576, "s": 3161, "text": "C code: We use format specifier here to give numeric value of character. Here %d is used to convert character to its ASCII value.CC// C program to print// ASCII Value of Character#include <stdio.h>int main(){ char c = 'k'; // %d displays the integer value of a character // %c displays the actual character printf(\"The ASCII value of %c is %d\", c, c); return 0;}Output:The ASCII value of k is 107\n" }, { "code": null, "e": 3578, "s": 3576, "text": "C" }, { "code": "// C program to print// ASCII Value of Character#include <stdio.h>int main(){ char c = 'k'; // %d displays the integer value of a character // %c displays the actual character printf(\"The ASCII value of %c is %d\", c, c); return 0;}", "e": 3827, "s": 3578, "text": null }, { "code": null, "e": 3856, "s": 3827, "text": "The ASCII value of k is 107\n" }, { "code": null, "e": 4156, "s": 3856, "text": "C++ code: Here int() is used to convert character to its ASCII value.CPPCPP// CPP program to print// ASCII Value of Character#include <iostream>using namespace std;int main(){ char c = 'A'; cout << \"The ASCII value of \" << c << \" is \" << int(c); return 0;}Output:The ASCII value of A is 65\n" }, { "code": null, "e": 4160, "s": 4156, "text": "CPP" }, { "code": "// CPP program to print// ASCII Value of Character#include <iostream>using namespace std;int main(){ char c = 'A'; cout << \"The ASCII value of \" << c << \" is \" << int(c); return 0;}", "e": 4351, "s": 4160, "text": null }, { "code": null, "e": 4379, "s": 4351, "text": "The ASCII value of A is 65\n" }, { "code": null, "e": 4791, "s": 4379, "text": "Java code : Here, to find the ASCII value of c, we just assign c to an int variable ascii. Internally, Java converts the character value to an ASCII value.JavaJava// Java program to print// ASCII Value of Characterpublic class AsciiValue { public static void main(String[] args) { char c = 'e'; int ascii = c; System.out.println(\"The ASCII value of \" + c + \" is: \" + ascii); }}" }, { "code": null, "e": 4796, "s": 4791, "text": "Java" }, { "code": "// Java program to print// ASCII Value of Characterpublic class AsciiValue { public static void main(String[] args) { char c = 'e'; int ascii = c; System.out.println(\"The ASCII value of \" + c + \" is: \" + ascii); }}", "e": 5045, "s": 4796, "text": null }, { "code": null, "e": 5557, "s": 5045, "text": "C# code : Here, to find the ASCII value of c, we just assign c to an int variable ascii. Internally, C# converts the character value to an ASCII value.CSHARPCSHARP// C# program to print// ASCII Value of Characterusing System; public class AsciiValue { public static void Main() { char c = 'e'; int ascii = c; Console.Write(\"The ASCII value of \" + c + \" is: \" + ascii); }} // This code is contributed // by nitin mittalOutput:The ASCII value of e is 101\n" }, { "code": null, "e": 5564, "s": 5557, "text": "CSHARP" }, { "code": "// C# program to print// ASCII Value of Characterusing System; public class AsciiValue { public static void Main() { char c = 'e'; int ascii = c; Console.Write(\"The ASCII value of \" + c + \" is: \" + ascii); }} // This code is contributed // by nitin mittal", "e": 5878, "s": 5564, "text": null }, { "code": null, "e": 5886, "s": 5878, "text": "Output:" }, { "code": null, "e": 5915, "s": 5886, "text": "The ASCII value of e is 101\n" }, { "code": null, "e": 6001, "s": 5915, "text": "Here is a method to print the ASCII value of the characters in a string using python:" }, { "code": null, "e": 6009, "s": 6001, "text": "Python3" }, { "code": "print(\"Enter a String: \", end=\"\")text = input()textlength = len(text)for char in text: ascii = ord(char) print(char, \"\\t\", ascii)", "e": 6145, "s": 6009, "text": null }, { "code": null, "e": 6152, "s": 6145, "text": "Input:" }, { "code": null, "e": 6183, "s": 6152, "text": "Enter a String: Aditya Trivedi" }, { "code": null, "e": 6191, "s": 6183, "text": "Output:" }, { "code": null, "e": 6271, "s": 6191, "text": "A 65\nd 100\ni 105\nt 116\ny 121\na 97\n 32\nT 84\nr 114\ni 105\nv 118\ne 101\nd 100\ni 105" }, { "code": null, "e": 6284, "s": 6271, "text": "nitin mittal" }, { "code": null, "e": 6300, "s": 6284, "text": "saurabh1990aror" }, { "code": null, "e": 6310, "s": 6300, "text": "adityatri" }, { "code": null, "e": 6316, "s": 6310, "text": "ASCII" }, { "code": null, "e": 6327, "s": 6316, "text": "C Programs" }, { "code": null, "e": 6340, "s": 6327, "text": "C++ Programs" }, { "code": null, "e": 6354, "s": 6340, "text": "Java Programs" }, { "code": null, "e": 6370, "s": 6354, "text": "Python Programs" }, { "code": null, "e": 6389, "s": 6370, "text": "School Programming" }, { "code": null, "e": 6487, "s": 6389, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6528, "s": 6487, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 6562, "s": 6528, "text": "C++ Program to check Prime Number" }, { "code": null, "e": 6593, "s": 6562, "text": "Producer Consumer Problem in C" }, { "code": null, "e": 6623, "s": 6593, "text": "C Program to Swap two Numbers" }, { "code": null, "e": 6674, "s": 6623, "text": "Set, Clear and Toggle a given bit of a number in C" }, { "code": null, "e": 6708, "s": 6674, "text": "Sorting a Map by value in C++ STL" }, { "code": null, "e": 6742, "s": 6708, "text": "Shallow Copy and Deep Copy in C++" }, { "code": null, "e": 6780, "s": 6742, "text": "C++ program for hashing with chaining" }, { "code": null, "e": 6840, "s": 6780, "text": "C++ Program to check if a given String is Palindrome or not" } ]
Python sorted containers | An Introduction
11 May, 2020 Sorted Containers is an Apache2 licensed sorted collections library, written in pure-Python, and fast as C-extensions. It was created by Grant Jenks and is an open source library. It is a collection of containers that allow us to insert and remove elements very efficiently while maintaining sorted order. Features: Pure-Python Fully documented Benchmark comparison (alternatives, runtimes, load-factors Performance (often faster than C implementations) Compatible API (nearly identical to popular blist and rbtree modules) Feature-rich (e.g. get the five largest keys in a sorted dict: d.iloc[-5:]) Pragmatic design (e.g. SortedSet is a Python set with a SortedList index) Containers: SortedList SortedDict SortedSet Installation: Mac and Linux users can install via pip command: sudo pip install sortedcontainers Sorted list is a sorted mutable sequence in which the values are maintained in sorted order. Functions to add and remove elements: add(value) : A function that takes one element as parameter and inserts it into the list by maintaining sorted order. Runtime Complexity: O(log(n)) update(iterable): A function that takes an iterable as input and updates the SortedList adding all the values from the iterable Runtime complexity: O(k*log(n)). clear(): Remove all values from sorted list. Runtime complexity: O(n). discard(value): Remove value from sorted list if it is a member. If value is not a member, do nothing. Runtime complexity: O(log(n)). Below is the implementation – # importing librariesfrom sortedcontainers import SortedList, SortedSet, SortedDict # initializing a sorted list with parameters# it takes an iterable as a parameter.sorted_list = SortedList([1, 2, 3, 4]) # initializing a sorted list using default constructorsorted_list = SortedList() # inserting values one by one using add()for i in range(5, 0, -1): sorted_list.add(i) # prints the elements in sorted orderprint('list after adding 5 elements: ', sorted_list) print('list elements are: ', end = '') # iterating through a sorted listfor i in sorted_list: print(i, end = ' ')print() # removing all elements using clear()sorted_list.clear() # adding elements using the update() functionelements = [10, 9, 8, 7, 6] sorted_list.update(elements) # prints the updated list in sorted orderprint('list after updating: ', sorted_list) # removing a particular elementsorted_list.discard(8) print('list after removing one element: ', sorted_list) # removing all elementssorted_list.clear() print('list after removing all elements using clear: ', sorted_list) Output : list after adding 5 elements: SortedList([1, 2, 3, 4, 5], load=1000) list elements are: 1 2 3 4 5 list after updating: SortedList([6, 7, 8, 9, 10], load=1000) list after removing one element: SortedList([6, 7, 9, 10], load=1000) list after removing all elements using clear: SortedList([], load=1000) Sorted set is a sorted mutable set in which values are unique and maintained in sorted order. Sorted set uses a set for set-operations and maintains a sorted list of values. Sorted set values must be hashable and comparable. Functions to add and remove elements: add(value) : A function that takes one element as parameter and inserts it into the set by maintaining sorted order. Runtime Complexity: O(log(n)) clear(): Remove all values from sorted set. Runtime complexity: O(n) discard(value): Remove value from sorted set if it is a member. If value is not a member, do nothing. Runtime complexity: O(log(n)) # importing librariesfrom sortedcontainers import SortedList, SortedSet, SortedDict # initializing a sorted set with parameters# it takes an iterable as an argumentsorted_set = SortedSet([1, 1, 2, 3, 4]) # initializing a sorted set using default constructorsorted_set = SortedSet() # inserting values one by onefor i in range(5, 0, -1): sorted_set.add(i) print('set after adding elements: ', sorted_set) # inserting duplicate valuesorted_set.add(5) print('set after inserting duplicate element: ', sorted_set) # discarding an elementsorted_set.discard(4) print('set after discarding: ', sorted_set) # checking membership using 'in' operatorif(2 in sorted_set): print('2 is present')else: print('2 is not present') print('set elements are: ', end = '') # iterating through a sorted setfor i in sorted_set: print(i, end = ' ')print() Output : set after adding elements: SortedSet([1, 2, 3, 4, 5], key=None, load=1000) set after inserting duplicate element: SortedSet([1, 2, 3, 4, 5], key=None, load=1000) set after discarding: SortedSet([1, 2, 3, 5], key=None, load=1000) 2 is present set elements are: 1 2 3 5 Sorted dict is a sorted mutable mapping in which keys are maintained in sorted order. Sorted dict inherits from dict to store items and maintains a sorted list of keys. Sorted dict keys must be hashable and comparable. Functions to add and remove elements: setdefault(key, default = None) : Return value for item identified by key in sorted dict. If key is in the sorted dict then return its value. If key is not in the sorted dict then insert key with value default and return default. Runtime Complexity: O(log(n)) clear(): Remove all values from sorted dict. Runtime complexity: O(n) get(key, default): Return the value for key if key is in the dictionary, else default. # importing librariesfrom sortedcontainers import SortedList, SortedSet, SortedDict # initializing a sorted dict with parameters# it takes a dictionary object as a parametersorted_dict = SortedDict({'a': 1, 'b': 2, 'c': 3}) # initializing a sorted dictsorted_dict = SortedDict({'a': 1, 'c': 2, 'b':3}) # print the dictprint('sorted dict is: ', sorted_dict) # adding key => value pairssorted_dict['d'] = 3 print('sorted dict after adding an element: ', sorted_dict) # adding element using setdefault()sorted_dict.setdefault('e', 4) print('sorted dict after setdefault(): ', sorted_dict) # using the get functionprint('using the get function to print the value of a: ', sorted_dict.get('a', 0)) # checking membership using 'in' operatorif('a' in sorted_dict): print('a is present')else: print('a is not present') print('dict elements are: ', end = '') # iterating over key => value pairs in a dictionaryfor key in sorted_dict: print('{} -> {}'.format(key, sorted_dict[key]), end = ' ')print() # removing all elements from the dictsorted_dict.clear() print('sorted dict after removing all elements: ', sorted_dict) Output : sorted dict is: SortedDict(None, 1000, {'a': 1, 'b': 3, 'c': 2}) sorted dict after adding an element: SortedDict(None, 1000, {'a': 1, 'b': 3, 'c': 2, 'd': 3}) sorted dict after setdefault(): SortedDict(None, 1000, {'a': 1, 'b': 3, 'c': 2, 'd': 3, 'e': 4}) using the get function to print the value of a: 1 a is present dict elements are: a -> 1 b -> 3 c -> 2 d -> 3 e -> 4 sorted dict after removing all elements: SortedDict(None, 1000, {}) Reference: http://www.grantjenks.com/docs/sortedcontainers/index.html Python-Sorted Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 54, "s": 26, "text": "\n11 May, 2020" }, { "code": null, "e": 360, "s": 54, "text": "Sorted Containers is an Apache2 licensed sorted collections library, written in pure-Python, and fast as C-extensions. It was created by Grant Jenks and is an open source library. It is a collection of containers that allow us to insert and remove elements very efficiently while maintaining sorted order." }, { "code": null, "e": 370, "s": 360, "text": "Features:" }, { "code": null, "e": 382, "s": 370, "text": "Pure-Python" }, { "code": null, "e": 399, "s": 382, "text": "Fully documented" }, { "code": null, "e": 458, "s": 399, "text": "Benchmark comparison (alternatives, runtimes, load-factors" }, { "code": null, "e": 508, "s": 458, "text": "Performance (often faster than C implementations)" }, { "code": null, "e": 578, "s": 508, "text": "Compatible API (nearly identical to popular blist and rbtree modules)" }, { "code": null, "e": 654, "s": 578, "text": "Feature-rich (e.g. get the five largest keys in a sorted dict: d.iloc[-5:])" }, { "code": null, "e": 728, "s": 654, "text": "Pragmatic design (e.g. SortedSet is a Python set with a SortedList index)" }, { "code": null, "e": 740, "s": 728, "text": "Containers:" }, { "code": null, "e": 751, "s": 740, "text": "SortedList" }, { "code": null, "e": 762, "s": 751, "text": "SortedDict" }, { "code": null, "e": 772, "s": 762, "text": "SortedSet" }, { "code": null, "e": 786, "s": 772, "text": "Installation:" }, { "code": null, "e": 835, "s": 786, "text": "Mac and Linux users can install via pip command:" }, { "code": null, "e": 871, "s": 835, "text": " sudo pip install sortedcontainers " }, { "code": null, "e": 964, "s": 871, "text": "Sorted list is a sorted mutable sequence in which the values are maintained in sorted order." }, { "code": null, "e": 1002, "s": 964, "text": "Functions to add and remove elements:" }, { "code": null, "e": 1150, "s": 1002, "text": "add(value) : A function that takes one element as parameter and inserts it into the list by maintaining sorted order. Runtime Complexity: O(log(n))" }, { "code": null, "e": 1311, "s": 1150, "text": "update(iterable): A function that takes an iterable as input and updates the SortedList adding all the values from the iterable Runtime complexity: O(k*log(n))." }, { "code": null, "e": 1382, "s": 1311, "text": "clear(): Remove all values from sorted list. Runtime complexity: O(n)." }, { "code": null, "e": 1516, "s": 1382, "text": "discard(value): Remove value from sorted list if it is a member. If value is not a member, do nothing. Runtime complexity: O(log(n))." }, { "code": null, "e": 1546, "s": 1516, "text": "Below is the implementation –" }, { "code": "# importing librariesfrom sortedcontainers import SortedList, SortedSet, SortedDict # initializing a sorted list with parameters# it takes an iterable as a parameter.sorted_list = SortedList([1, 2, 3, 4]) # initializing a sorted list using default constructorsorted_list = SortedList() # inserting values one by one using add()for i in range(5, 0, -1): sorted_list.add(i) # prints the elements in sorted orderprint('list after adding 5 elements: ', sorted_list) print('list elements are: ', end = '') # iterating through a sorted listfor i in sorted_list: print(i, end = ' ')print() # removing all elements using clear()sorted_list.clear() # adding elements using the update() functionelements = [10, 9, 8, 7, 6] sorted_list.update(elements) # prints the updated list in sorted orderprint('list after updating: ', sorted_list) # removing a particular elementsorted_list.discard(8) print('list after removing one element: ', sorted_list) # removing all elementssorted_list.clear() print('list after removing all elements using clear: ', sorted_list)", "e": 2615, "s": 1546, "text": null }, { "code": null, "e": 2624, "s": 2615, "text": "Output :" }, { "code": null, "e": 2935, "s": 2624, "text": "list after adding 5 elements: SortedList([1, 2, 3, 4, 5], load=1000)\n\nlist elements are: 1 2 3 4 5 \n\nlist after updating: SortedList([6, 7, 8, 9, 10], load=1000)\n\nlist after removing one element: SortedList([6, 7, 9, 10], load=1000)\n\nlist after removing all elements using clear: SortedList([], load=1000)\n" }, { "code": null, "e": 3160, "s": 2935, "text": "Sorted set is a sorted mutable set in which values are unique and maintained in sorted order. Sorted set uses a set for set-operations and maintains a sorted list of values. Sorted set values must be hashable and comparable." }, { "code": null, "e": 3198, "s": 3160, "text": "Functions to add and remove elements:" }, { "code": null, "e": 3345, "s": 3198, "text": "add(value) : A function that takes one element as parameter and inserts it into the set by maintaining sorted order. Runtime Complexity: O(log(n))" }, { "code": null, "e": 3414, "s": 3345, "text": "clear(): Remove all values from sorted set. Runtime complexity: O(n)" }, { "code": null, "e": 3546, "s": 3414, "text": "discard(value): Remove value from sorted set if it is a member. If value is not a member, do nothing. Runtime complexity: O(log(n))" }, { "code": "# importing librariesfrom sortedcontainers import SortedList, SortedSet, SortedDict # initializing a sorted set with parameters# it takes an iterable as an argumentsorted_set = SortedSet([1, 1, 2, 3, 4]) # initializing a sorted set using default constructorsorted_set = SortedSet() # inserting values one by onefor i in range(5, 0, -1): sorted_set.add(i) print('set after adding elements: ', sorted_set) # inserting duplicate valuesorted_set.add(5) print('set after inserting duplicate element: ', sorted_set) # discarding an elementsorted_set.discard(4) print('set after discarding: ', sorted_set) # checking membership using 'in' operatorif(2 in sorted_set): print('2 is present')else: print('2 is not present') print('set elements are: ', end = '') # iterating through a sorted setfor i in sorted_set: print(i, end = ' ')print()", "e": 4401, "s": 3546, "text": null }, { "code": null, "e": 4410, "s": 4401, "text": "Output :" }, { "code": null, "e": 4686, "s": 4410, "text": "set after adding elements: SortedSet([1, 2, 3, 4, 5], key=None, load=1000)\n\nset after inserting duplicate element: SortedSet([1, 2, 3, 4, 5], key=None, load=1000)\n\nset after discarding: SortedSet([1, 2, 3, 5], key=None, load=1000)\n\n2 is present\n\nset elements are: 1 2 3 5\n" }, { "code": null, "e": 4905, "s": 4686, "text": "Sorted dict is a sorted mutable mapping in which keys are maintained in sorted order. Sorted dict inherits from dict to store items and maintains a sorted list of keys. Sorted dict keys must be hashable and comparable." }, { "code": null, "e": 4943, "s": 4905, "text": "Functions to add and remove elements:" }, { "code": null, "e": 5203, "s": 4943, "text": "setdefault(key, default = None) : Return value for item identified by key in sorted dict. If key is in the sorted dict then return its value. If key is not in the sorted dict then insert key with value default and return default. Runtime Complexity: O(log(n))" }, { "code": null, "e": 5273, "s": 5203, "text": "clear(): Remove all values from sorted dict. Runtime complexity: O(n)" }, { "code": null, "e": 5360, "s": 5273, "text": "get(key, default): Return the value for key if key is in the dictionary, else default." }, { "code": "# importing librariesfrom sortedcontainers import SortedList, SortedSet, SortedDict # initializing a sorted dict with parameters# it takes a dictionary object as a parametersorted_dict = SortedDict({'a': 1, 'b': 2, 'c': 3}) # initializing a sorted dictsorted_dict = SortedDict({'a': 1, 'c': 2, 'b':3}) # print the dictprint('sorted dict is: ', sorted_dict) # adding key => value pairssorted_dict['d'] = 3 print('sorted dict after adding an element: ', sorted_dict) # adding element using setdefault()sorted_dict.setdefault('e', 4) print('sorted dict after setdefault(): ', sorted_dict) # using the get functionprint('using the get function to print the value of a: ', sorted_dict.get('a', 0)) # checking membership using 'in' operatorif('a' in sorted_dict): print('a is present')else: print('a is not present') print('dict elements are: ', end = '') # iterating over key => value pairs in a dictionaryfor key in sorted_dict: print('{} -> {}'.format(key, sorted_dict[key]), end = ' ')print() # removing all elements from the dictsorted_dict.clear() print('sorted dict after removing all elements: ', sorted_dict)", "e": 6494, "s": 5360, "text": null }, { "code": null, "e": 6503, "s": 6494, "text": "Output :" }, { "code": null, "e": 6957, "s": 6503, "text": "sorted dict is: SortedDict(None, 1000, {'a': 1, 'b': 3, 'c': 2})\n\nsorted dict after adding an element: SortedDict(None, 1000, {'a': 1, 'b': 3, 'c': 2, 'd': 3})\n\nsorted dict after setdefault(): SortedDict(None, 1000, {'a': 1, 'b': 3, 'c': 2, 'd': 3, 'e': 4})\n\nusing the get function to print the value of a: 1\n\na is present\n\ndict elements are: a -> 1 b -> 3 c -> 2 d -> 3 e -> 4 \n\nsorted dict after removing all elements: SortedDict(None, 1000, {})\n" }, { "code": null, "e": 7027, "s": 6957, "text": "Reference: http://www.grantjenks.com/docs/sortedcontainers/index.html" }, { "code": null, "e": 7041, "s": 7027, "text": "Python-Sorted" }, { "code": null, "e": 7048, "s": 7041, "text": "Python" }, { "code": null, "e": 7146, "s": 7048, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7164, "s": 7146, "text": "Python Dictionary" }, { "code": null, "e": 7206, "s": 7164, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 7228, "s": 7206, "text": "Enumerate() in Python" }, { "code": null, "e": 7263, "s": 7228, "text": "Read a file line by line in Python" }, { "code": null, "e": 7289, "s": 7263, "text": "Python String | replace()" }, { "code": null, "e": 7321, "s": 7289, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 7350, "s": 7321, "text": "*args and **kwargs in Python" }, { "code": null, "e": 7377, "s": 7350, "text": "Python Classes and Objects" }, { "code": null, "e": 7407, "s": 7377, "text": "Iterate over a list in Python" } ]
Python Dictionary | Check if binary representations of two numbers are anagram
27 Jul, 2020 Given two numbers you are required to check whether they are anagrams of each other or not in binary representation. Examples: Input : a = 8, b = 4 Output : Yes Binary representations of both numbers have same 0s and 1s. Input : a = 4, b = 5 Output : No We have existing solution for this problem please refer Check if binary representations of two numbers are anagram link. We can solve this problem quickly in python using Counter(iterable) method and Dictionary Comparison. Approach is simple, Convert both number into it’s binary using bin() function.Since binary representation of both numbers could differ in length so we will append zeros in start of shorter string to make both string of equal length. ie.; append zeros = abs(len(bin1)-len(bin2)).Convert both output string containing 0 and 1 returned by bin function into dictionary using Counter() function, having 0 and 1 keys and their count as value. Compare both dictionaries, if value of 0’s and 1’s in both dictionaries are equal then binary representations of two numbers are anagram otherwise not. Convert both number into it’s binary using bin() function. Since binary representation of both numbers could differ in length so we will append zeros in start of shorter string to make both string of equal length. ie.; append zeros = abs(len(bin1)-len(bin2)). Convert both output string containing 0 and 1 returned by bin function into dictionary using Counter() function, having 0 and 1 keys and their count as value. Compare both dictionaries, if value of 0’s and 1’s in both dictionaries are equal then binary representations of two numbers are anagram otherwise not. # function to Check if binary representations# of two numbers are anagramfrom collections import Counter def checkAnagram(num1,num2): # convert numbers into in binary # and remove first two characters of # output string because bin function # '0b' as prefix in output string bin1 = bin(num1)[2:] bin2 = bin(num2)[2:] # append zeros in shorter string zeros = abs(len(bin1)-len(bin2)) if (len(bin1)>len(bin2)): bin2 = zeros * '0' + bin2 else: bin1 = zeros * '0' + bin1 # convert binary representations # into dictionary dict1 = Counter(bin1) dict2 = Counter(bin2) # compare both dictionaries if dict1 == dict2: print('Yes') else: print('No') # Driver programif __name__ == "__main__": num1 = 8 num2 = 4 checkAnagram(num1,num2) Output: Yes Akanksha_Rai base-conversion Python dictionary-programs python-dict Python python-dict Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Jul, 2020" }, { "code": null, "e": 145, "s": 28, "text": "Given two numbers you are required to check whether they are anagrams of each other or not in binary representation." }, { "code": null, "e": 155, "s": 145, "text": "Examples:" }, { "code": null, "e": 285, "s": 155, "text": "Input : a = 8, b = 4 \nOutput : Yes\nBinary representations of both\nnumbers have same 0s and 1s.\n\nInput : a = 4, b = 5\nOutput : No\n" }, { "code": null, "e": 528, "s": 285, "text": "We have existing solution for this problem please refer Check if binary representations of two numbers are anagram link. We can solve this problem quickly in python using Counter(iterable) method and Dictionary Comparison. Approach is simple," }, { "code": null, "e": 1097, "s": 528, "text": "Convert both number into it’s binary using bin() function.Since binary representation of both numbers could differ in length so we will append zeros in start of shorter string to make both string of equal length. ie.; append zeros = abs(len(bin1)-len(bin2)).Convert both output string containing 0 and 1 returned by bin function into dictionary using Counter() function, having 0 and 1 keys and their count as value. Compare both dictionaries, if value of 0’s and 1’s in both dictionaries are equal then binary representations of two numbers are anagram otherwise not." }, { "code": null, "e": 1156, "s": 1097, "text": "Convert both number into it’s binary using bin() function." }, { "code": null, "e": 1357, "s": 1156, "text": "Since binary representation of both numbers could differ in length so we will append zeros in start of shorter string to make both string of equal length. ie.; append zeros = abs(len(bin1)-len(bin2))." }, { "code": null, "e": 1668, "s": 1357, "text": "Convert both output string containing 0 and 1 returned by bin function into dictionary using Counter() function, having 0 and 1 keys and their count as value. Compare both dictionaries, if value of 0’s and 1’s in both dictionaries are equal then binary representations of two numbers are anagram otherwise not." }, { "code": "# function to Check if binary representations# of two numbers are anagramfrom collections import Counter def checkAnagram(num1,num2): # convert numbers into in binary # and remove first two characters of # output string because bin function # '0b' as prefix in output string bin1 = bin(num1)[2:] bin2 = bin(num2)[2:] # append zeros in shorter string zeros = abs(len(bin1)-len(bin2)) if (len(bin1)>len(bin2)): bin2 = zeros * '0' + bin2 else: bin1 = zeros * '0' + bin1 # convert binary representations # into dictionary dict1 = Counter(bin1) dict2 = Counter(bin2) # compare both dictionaries if dict1 == dict2: print('Yes') else: print('No') # Driver programif __name__ == \"__main__\": num1 = 8 num2 = 4 checkAnagram(num1,num2) ", "e": 2503, "s": 1668, "text": null }, { "code": null, "e": 2511, "s": 2503, "text": "Output:" }, { "code": null, "e": 2516, "s": 2511, "text": "Yes\n" }, { "code": null, "e": 2529, "s": 2516, "text": "Akanksha_Rai" }, { "code": null, "e": 2545, "s": 2529, "text": "base-conversion" }, { "code": null, "e": 2572, "s": 2545, "text": "Python dictionary-programs" }, { "code": null, "e": 2584, "s": 2572, "text": "python-dict" }, { "code": null, "e": 2591, "s": 2584, "text": "Python" }, { "code": null, "e": 2603, "s": 2591, "text": "python-dict" }, { "code": null, "e": 2701, "s": 2603, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2719, "s": 2701, "text": "Python Dictionary" }, { "code": null, "e": 2761, "s": 2719, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2783, "s": 2761, "text": "Enumerate() in Python" }, { "code": null, "e": 2818, "s": 2783, "text": "Read a file line by line in Python" }, { "code": null, "e": 2844, "s": 2818, "text": "Python String | replace()" }, { "code": null, "e": 2876, "s": 2844, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2905, "s": 2876, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2932, "s": 2905, "text": "Python Classes and Objects" }, { "code": null, "e": 2962, "s": 2932, "text": "Iterate over a list in Python" } ]
BabelJS - Transpile ES7 features to ES5
In this chapter, we will learn how to transpile ES7 features to ES5. ECMA Script 7 has the following new features added to it βˆ’ Async-Await Exponentiation Operator Array.prototype.includes() We will compile them to ES5 using babeljs. Depending on your project requirements, it is also possible to compile the code in any ecma version ie ES7 to ES6 or ES7 to ES5. Since ES5 version is the most stable and works fine on all modern and old browsers, we will compile the code to ES5. Async is an asynchronous function, which returns an implicit promise. The promise is either resolved or rejected. Async function is same as a normal standard function. The function can have await expression which pauses the execution till it returns a promise and once it gets it, the execution continues. Await will only work if the function is async. Here is a working example on async and await. let timer = () => { return new Promise(resolve => { setTimeout(() => { resolve("Promise resolved after 5 seconds"); }, 5000); }); }; let out = async () => { let msg = await timer(); console.log(msg); console.log("hello after await"); }; out(); Promise resolved after 5 seconds hello after await The await expression is added before the timer function is called. The timer function will return the promise after 5 seconds. So await will halt the execution until the promise on timer function is resolved or rejected and later continue. Let us now transpile the above code to ES5 using babel. let timer = () => { return new Promise(resolve => { setTimeout(() => { resolve("Promise resolved after 5 seconds"); }, 5000); }); }; let out = async () => { let msg = await timer(); console.log(msg); console.log("hello after await"); }; out(); npx babel asyncawait.js --out-file asyncawait_es5.js "use strict"; var timer = function timer() { return new Promise(function (resolve) { setTimeout(function () { resolve("Promise resolved after 5 seconds"); }, 5000); }); }; var out = async function out() { var msg = await timer(); console.log(msg); console.log("hello after await"); }; out(); Babeljs does not compile object or methods; so here promises used will not be transpiled and will be shown as it is. To support promises on old browsers, we need to add code, which will have support for promises. For now, let us install babel-polyfill as follows βˆ’ npm install --save babel-polyfill It should be saved as a dependency and not dev-dependency. To run the code in the browser, we will use the polyfill file from node_modules\babel-polyfill\dist\polyfill.min.js and call it using the script tag as shown below βˆ’ <!DOCTYPE html> <html> <head> <title>BabelJs Testing</title> </head> <body> <script src="node_modules\babel-polyfill\dist\polyfill.min.js" type="text/javascript"></script> <script type="text/javascript" src="aynscawait_es5.js"></script> </body> </html> When you run the above test page, you will see the output in the console as shown below ** is the operator used for exponentiation in ES7. Following example shows the working of the same in ES7 and the code is transpiled using babeljs. let sqr = 9 ** 2; console.log(sqr); 81 let sqr = 9 ** 2; console.log(sqr); To transpile the exponentiation operator, we need to install a plugin to be installed as follows βˆ’ npm install --save-dev babel-plugin-transform-exponentiation-operator Add the plugin details to .babelrc file as follows βˆ’ { "presets":[ "es2015" ], "plugins": ["transform-exponentiation-operator"] } npx babel exponeniation.js --out-file exponeniation_es5.js "use strict"; var sqr = Math.pow(9, 2); console.log(sqr); This feature gives true if the element passed to it is present in the array and false if otherwise. let arr1 = [10, 6, 3, 9, 17]; console.log(arr1.includes(9)); let names = ['Siya', 'Tom', 'Jerry', 'Bean', 'Ben']; console.log(names.includes('Tom')); console.log(names.includes('Be')); true true false We have to use babel-polyfill again here as includes is a method on an array and it will not get transpiled. We need additional step to include polyfill to make it work in older browsers. let arr1 = [10, 6, 3, 9, 17]; console.log(arr1.includes(9)); let names = ['Siya', 'Tom', 'Jerry', 'Bean', 'Ben']; console.log(names.includes('Tom')); console.log(names.includes('Be')); npx babel array_include.js --out-file array_include_es5.js 'use strict'; var arr1 = [10, 6, 3, 9, 17]; console.log(arr1.includes(9)); var names = ['Siya', 'Tom', 'Jerry', 'Bean', 'Ben']; console.log(names.includes('Tom')); console.log(names.includes('Be')); To test it in older browser, we need to use polyfill as shown below βˆ’ <!DOCTYPE html> <html> <head> <title>BabelJs Testing</title> </head> <body> <script src="node_modules\babel-polyfill\dist\polyfill.min.js" type="text/javascript"></script> <script type="text/javascript" src="array_include_es5.js"></script> </body> </html> Print Add Notes Bookmark this page
[ { "code": null, "e": 2164, "s": 2095, "text": "In this chapter, we will learn how to transpile ES7 features to ES5." }, { "code": null, "e": 2223, "s": 2164, "text": "ECMA Script 7 has the following new features added to it βˆ’" }, { "code": null, "e": 2235, "s": 2223, "text": "Async-Await" }, { "code": null, "e": 2259, "s": 2235, "text": "Exponentiation Operator" }, { "code": null, "e": 2286, "s": 2259, "text": "Array.prototype.includes()" }, { "code": null, "e": 2575, "s": 2286, "text": "We will compile them to ES5 using babeljs. Depending on your project requirements, it is also possible to compile the code in any ecma version ie ES7 to ES6 or ES7 to ES5. Since ES5 version is the most stable and works fine on all modern and old browsers, we will compile the code to ES5." }, { "code": null, "e": 2928, "s": 2575, "text": "Async is an asynchronous function, which returns an implicit promise. The promise is either resolved or rejected. Async function is same as a normal standard function. The function can have await expression which pauses the execution till it returns a promise and once it gets it, the execution continues. Await will only work if the function is async." }, { "code": null, "e": 2974, "s": 2928, "text": "Here is a working example on async and await." }, { "code": null, "e": 3254, "s": 2974, "text": "let timer = () => {\n return new Promise(resolve => {\n setTimeout(() => {\n resolve(\"Promise resolved after 5 seconds\");\n }, 5000);\n });\n};\nlet out = async () => {\n let msg = await timer();\n console.log(msg);\n console.log(\"hello after await\");\n};\nout();" }, { "code": null, "e": 3306, "s": 3254, "text": "Promise resolved after 5 seconds\nhello after await\n" }, { "code": null, "e": 3546, "s": 3306, "text": "The await expression is added before the timer function is called. The timer function will return the promise after 5 seconds. So await will halt the execution until the promise on timer function is resolved or rejected and later continue." }, { "code": null, "e": 3602, "s": 3546, "text": "Let us now transpile the above code to ES5 using babel." }, { "code": null, "e": 3882, "s": 3602, "text": "let timer = () => {\n return new Promise(resolve => {\n setTimeout(() => {\n resolve(\"Promise resolved after 5 seconds\");\n }, 5000);\n });\n};\nlet out = async () => {\n let msg = await timer();\n console.log(msg);\n console.log(\"hello after await\");\n};\nout();" }, { "code": null, "e": 3936, "s": 3882, "text": "npx babel asyncawait.js --out-file asyncawait_es5.js\n" }, { "code": null, "e": 4266, "s": 3936, "text": "\"use strict\";\n\nvar timer = function timer() {\n return new Promise(function (resolve) {\n setTimeout(function () {\n resolve(\"Promise resolved after 5 seconds\");\n }, 5000);\n });\n};\nvar out = async function out() {\n var msg = await timer();\n console.log(msg);\n console.log(\"hello after await\");\n};\n\nout();" }, { "code": null, "e": 4531, "s": 4266, "text": "Babeljs does not compile object or methods; so here promises used will not be transpiled and will be shown as it is. To support promises on old browsers, we need to add code, which will have support for promises. For now, let us install babel-polyfill as follows βˆ’" }, { "code": null, "e": 4566, "s": 4531, "text": "npm install --save babel-polyfill\n" }, { "code": null, "e": 4625, "s": 4566, "text": "It should be saved as a dependency and not dev-dependency." }, { "code": null, "e": 4791, "s": 4625, "text": "To run the code in the browser, we will use the polyfill file from node_modules\\babel-polyfill\\dist\\polyfill.min.js and call it using the script tag as shown below βˆ’" }, { "code": null, "e": 5074, "s": 4791, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>BabelJs Testing</title>\n </head>\n <body>\n <script src=\"node_modules\\babel-polyfill\\dist\\polyfill.min.js\" type=\"text/javascript\"></script>\n <script type=\"text/javascript\" src=\"aynscawait_es5.js\"></script>\n </body>\n</html>" }, { "code": null, "e": 5162, "s": 5074, "text": "When you run the above test page, you will see the output in the console as shown below" }, { "code": null, "e": 5310, "s": 5162, "text": "** is the operator used for exponentiation in ES7. Following example shows the working of the same in ES7 and the code is transpiled using babeljs." }, { "code": null, "e": 5346, "s": 5310, "text": "let sqr = 9 ** 2;\nconsole.log(sqr);" }, { "code": null, "e": 5350, "s": 5346, "text": "81\n" }, { "code": null, "e": 5386, "s": 5350, "text": "let sqr = 9 ** 2;\nconsole.log(sqr);" }, { "code": null, "e": 5485, "s": 5386, "text": "To transpile the exponentiation operator, we need to install a plugin to be installed as follows βˆ’" }, { "code": null, "e": 5556, "s": 5485, "text": "npm install --save-dev babel-plugin-transform-exponentiation-operator\n" }, { "code": null, "e": 5609, "s": 5556, "text": "Add the plugin details to .babelrc file as follows βˆ’" }, { "code": null, "e": 5701, "s": 5609, "text": "{\n \"presets\":[\n \"es2015\"\n ],\n \"plugins\": [\"transform-exponentiation-operator\"]\n}" }, { "code": null, "e": 5761, "s": 5701, "text": "npx babel exponeniation.js --out-file exponeniation_es5.js\n" }, { "code": null, "e": 5820, "s": 5761, "text": "\"use strict\";\n\nvar sqr = Math.pow(9, 2);\nconsole.log(sqr);" }, { "code": null, "e": 5920, "s": 5820, "text": "This feature gives true if the element passed to it is present in the array and false if otherwise." }, { "code": null, "e": 6105, "s": 5920, "text": "let arr1 = [10, 6, 3, 9, 17];\nconsole.log(arr1.includes(9));\nlet names = ['Siya', 'Tom', 'Jerry', 'Bean', 'Ben'];\nconsole.log(names.includes('Tom'));\nconsole.log(names.includes('Be'));" }, { "code": null, "e": 6122, "s": 6105, "text": "true\ntrue\nfalse\n" }, { "code": null, "e": 6310, "s": 6122, "text": "We have to use babel-polyfill again here as includes is a method on an array and it will not get transpiled. We need additional step to include polyfill to make it work in older browsers." }, { "code": null, "e": 6495, "s": 6310, "text": "let arr1 = [10, 6, 3, 9, 17];\nconsole.log(arr1.includes(9));\nlet names = ['Siya', 'Tom', 'Jerry', 'Bean', 'Ben'];\nconsole.log(names.includes('Tom'));\nconsole.log(names.includes('Be'));" }, { "code": null, "e": 6555, "s": 6495, "text": "npx babel array_include.js --out-file array_include_es5.js\n" }, { "code": null, "e": 6755, "s": 6555, "text": "'use strict';\n\nvar arr1 = [10, 6, 3, 9, 17];\nconsole.log(arr1.includes(9));\nvar names = ['Siya', 'Tom', 'Jerry', 'Bean', 'Ben'];\nconsole.log(names.includes('Tom'));\nconsole.log(names.includes('Be'));" }, { "code": null, "e": 6825, "s": 6755, "text": "To test it in older browser, we need to use polyfill as shown below βˆ’" }, { "code": null, "e": 7111, "s": 6825, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>BabelJs Testing</title>\n </head>\n <body>\n <script src=\"node_modules\\babel-polyfill\\dist\\polyfill.min.js\" type=\"text/javascript\"></script>\n <script type=\"text/javascript\" src=\"array_include_es5.js\"></script>\n </body>\n</html>" }, { "code": null, "e": 7118, "s": 7111, "text": " Print" }, { "code": null, "e": 7129, "s": 7118, "text": " Add Notes" } ]
The Right Way to Access a Dictionary | by Radian Krisno | Towards Data Science
The dictionary is one of the data structures that are ready to use when programming in Python. Dictionary is an unordered and unordered Python collection that maps unique keys to some values. In Python, dictionaries are written by using curly brackets {} . The key is separated from the key by a colon : and every key-value pair is separated by a comma ,. Here’s how dictionaries are declared in Python. #A dictionary containing basketball players with their heights in mplayersHeight = {"Lebron James": 2.06, "Kevin Durant": 2.08, "Luka Doncic": 2.01, "James Harden": 1.96} We have created the dictionary, however, what’s good about it if we cannot retrieve the data again right? This is where a lot of people do it wrong. I should admit, I was among them not long ago. After I realize the advantage, I never turn back even once. That’s why I am motivated to share it with you guys. The well-known, or I should say the traditional way to access a value in a dictionary is by referring to its key name, inside a square bracket. print(playersHeight["Lebron James"]) #print 2.06print(playersHeight["Kevin Durant"]) #print 2.08print(playersHeight["Luka Doncic"]) #print 2.01print(playersHeight["James Harden"]) #print 1.96 Everything seems OK, right? Not so fast! What do you think will happen if you type a basketball player’s name that is not in the dictionary? Look closely playersHeight["Kyrie Irving"] #KeyError 'Kyrie Irving' Notice that when you want to access the value of the key that doesn’t exist in the dictionary will result in a KeyError. This could quickly escalate into a major problem, especially when you are building a huge project. Fret not! There are certainly one or two ways to go around this. Using If if "Kyrie Irving" is in playersHeight: print(playersHeight["Kyrie Irving"]) Using Try-Except try: print("Kyrie Irving")except KeyError as message: print(message) #'Kyrie Irving' Both snippets will run with no problem. For now, it seems okay, we can tolerate writing more lines to deal with the possibility of KeyError. Nevertheless, it will become annoying when the code you are writing is wrong. Luckily, there are better ways to do it. Not one, but two better ways! Buckle up your seat and get ready! Using get() Method Using the get method is one of the best choices you can make when dealing with a dictionary. This method has 2 parameters, the first 1 is required while the second one is optional. However, to use the full potential of the get() method, I suggest you fill both parameters. First: the name of the key which value you want to retrieve Second: the value used if the key we are searching does not exist in the #A dictionary containing basketball players with their heights in mplayersHeight = {"Lebron James": 2.06, "Kevin Durant": 2.08, "Luka Doncic": 2.01, "James Harden": 1.96}#If the key existsprint(playersHeight.get("Lebron James", 0)) #print 2.06print(playersHeight.get("Kevin Durant", 0)) #print 2.08#If the key does not existprint(playersHeight.get("Kyrie Irving", 0)) #print 0print(playersHeight.get("Trae Young", 0)) #print 0 When the key exists, get() method works exactly the same to referencing the name of the key in a square bracket. But, when the key does not exist, using get() method will print the default value we enter as the second argument. If you don’t specify the second value, a None value will be returned. You should also note that using the get() method will not modify the original dictionary. We will discuss it further later in this article. Using setdefault() method What? There is another way? Yes of course! You can use setdefault() method when you not only want to skip the try-except step but also overwrite the original dictionary. #A dictionary containing basketball players with their heights in mplayersHeight = {"Lebron James": 2.06, "Kevin Durant": 2.08, "Luka Doncic": 2.01, "James Harden": 1.96}#If the key existsprint(playersHeight.setdefault("Lebron James", 0)) #print 2.06print(playersHeight.setdefault("Kevin Durant", 0)) #print 2.08#If the key does not existprint(playersHeight.setdefault("Kyrie Irving", 0)) #print 0print(playersHeight.setdefault("Trae Young", 0)) #print 0 What I mean by overwriting is this, when you see the original dictionary again, you will see this. print(playersHeight)"""print{"Lebron James": 2.06, "Kevin Durant": 2.08, "Luka Doncic": 2.01, "James Harden": 1.96, "Kyrie Irving": 0, "Trae Young": 0} Other than this feature, the setdefault() method is exactly similar to the get() method. Both get() and setdefault() are advanced techniques that you all must familiarize with. Implementing it is not hard and straightforward. The only barrier for you now is to break those old habits. However, I believe that as you use it, you will experience the difference immediately. After a while, you will no longer hesitate to change and start using get() and setdefault() methods. Remember, when you don’t want to overwrite the original dictionary, go with get() method. When you want to make changes to the original dictionary, setdefault() will be the better choice for you.
[ { "code": null, "e": 267, "s": 172, "text": "The dictionary is one of the data structures that are ready to use when programming in Python." }, { "code": null, "e": 576, "s": 267, "text": "Dictionary is an unordered and unordered Python collection that maps unique keys to some values. In Python, dictionaries are written by using curly brackets {} . The key is separated from the key by a colon : and every key-value pair is separated by a comma ,. Here’s how dictionaries are declared in Python." }, { "code": null, "e": 796, "s": 576, "text": "#A dictionary containing basketball players with their heights in mplayersHeight = {\"Lebron James\": 2.06, \"Kevin Durant\": 2.08, \"Luka Doncic\": 2.01, \"James Harden\": 1.96}" }, { "code": null, "e": 1105, "s": 796, "text": "We have created the dictionary, however, what’s good about it if we cannot retrieve the data again right? This is where a lot of people do it wrong. I should admit, I was among them not long ago. After I realize the advantage, I never turn back even once. That’s why I am motivated to share it with you guys." }, { "code": null, "e": 1249, "s": 1105, "text": "The well-known, or I should say the traditional way to access a value in a dictionary is by referring to its key name, inside a square bracket." }, { "code": null, "e": 1441, "s": 1249, "text": "print(playersHeight[\"Lebron James\"]) #print 2.06print(playersHeight[\"Kevin Durant\"]) #print 2.08print(playersHeight[\"Luka Doncic\"]) #print 2.01print(playersHeight[\"James Harden\"]) #print 1.96" }, { "code": null, "e": 1595, "s": 1441, "text": "Everything seems OK, right? Not so fast! What do you think will happen if you type a basketball player’s name that is not in the dictionary? Look closely" }, { "code": null, "e": 1650, "s": 1595, "text": "playersHeight[\"Kyrie Irving\"] #KeyError 'Kyrie Irving'" }, { "code": null, "e": 1935, "s": 1650, "text": "Notice that when you want to access the value of the key that doesn’t exist in the dictionary will result in a KeyError. This could quickly escalate into a major problem, especially when you are building a huge project. Fret not! There are certainly one or two ways to go around this." }, { "code": null, "e": 1944, "s": 1935, "text": "Using If" }, { "code": null, "e": 2023, "s": 1944, "text": "if \"Kyrie Irving\" is in playersHeight: print(playersHeight[\"Kyrie Irving\"])" }, { "code": null, "e": 2040, "s": 2023, "text": "Using Try-Except" }, { "code": null, "e": 2131, "s": 2040, "text": "try: print(\"Kyrie Irving\")except KeyError as message: print(message) #'Kyrie Irving'" }, { "code": null, "e": 2350, "s": 2131, "text": "Both snippets will run with no problem. For now, it seems okay, we can tolerate writing more lines to deal with the possibility of KeyError. Nevertheless, it will become annoying when the code you are writing is wrong." }, { "code": null, "e": 2456, "s": 2350, "text": "Luckily, there are better ways to do it. Not one, but two better ways! Buckle up your seat and get ready!" }, { "code": null, "e": 2475, "s": 2456, "text": "Using get() Method" }, { "code": null, "e": 2748, "s": 2475, "text": "Using the get method is one of the best choices you can make when dealing with a dictionary. This method has 2 parameters, the first 1 is required while the second one is optional. However, to use the full potential of the get() method, I suggest you fill both parameters." }, { "code": null, "e": 2808, "s": 2748, "text": "First: the name of the key which value you want to retrieve" }, { "code": null, "e": 2881, "s": 2808, "text": "Second: the value used if the key we are searching does not exist in the" }, { "code": null, "e": 3356, "s": 2881, "text": "#A dictionary containing basketball players with their heights in mplayersHeight = {\"Lebron James\": 2.06, \"Kevin Durant\": 2.08, \"Luka Doncic\": 2.01, \"James Harden\": 1.96}#If the key existsprint(playersHeight.get(\"Lebron James\", 0)) #print 2.06print(playersHeight.get(\"Kevin Durant\", 0)) #print 2.08#If the key does not existprint(playersHeight.get(\"Kyrie Irving\", 0)) #print 0print(playersHeight.get(\"Trae Young\", 0)) #print 0" }, { "code": null, "e": 3584, "s": 3356, "text": "When the key exists, get() method works exactly the same to referencing the name of the key in a square bracket. But, when the key does not exist, using get() method will print the default value we enter as the second argument." }, { "code": null, "e": 3654, "s": 3584, "text": "If you don’t specify the second value, a None value will be returned." }, { "code": null, "e": 3794, "s": 3654, "text": "You should also note that using the get() method will not modify the original dictionary. We will discuss it further later in this article." }, { "code": null, "e": 3820, "s": 3794, "text": "Using setdefault() method" }, { "code": null, "e": 3863, "s": 3820, "text": "What? There is another way? Yes of course!" }, { "code": null, "e": 3990, "s": 3863, "text": "You can use setdefault() method when you not only want to skip the try-except step but also overwrite the original dictionary." }, { "code": null, "e": 4493, "s": 3990, "text": "#A dictionary containing basketball players with their heights in mplayersHeight = {\"Lebron James\": 2.06, \"Kevin Durant\": 2.08, \"Luka Doncic\": 2.01, \"James Harden\": 1.96}#If the key existsprint(playersHeight.setdefault(\"Lebron James\", 0)) #print 2.06print(playersHeight.setdefault(\"Kevin Durant\", 0)) #print 2.08#If the key does not existprint(playersHeight.setdefault(\"Kyrie Irving\", 0)) #print 0print(playersHeight.setdefault(\"Trae Young\", 0)) #print 0" }, { "code": null, "e": 4592, "s": 4493, "text": "What I mean by overwriting is this, when you see the original dictionary again, you will see this." }, { "code": null, "e": 4744, "s": 4592, "text": "print(playersHeight)\"\"\"print{\"Lebron James\": 2.06, \"Kevin Durant\": 2.08, \"Luka Doncic\": 2.01, \"James Harden\": 1.96, \"Kyrie Irving\": 0, \"Trae Young\": 0}" }, { "code": null, "e": 4833, "s": 4744, "text": "Other than this feature, the setdefault() method is exactly similar to the get() method." }, { "code": null, "e": 5029, "s": 4833, "text": "Both get() and setdefault() are advanced techniques that you all must familiarize with. Implementing it is not hard and straightforward. The only barrier for you now is to break those old habits." }, { "code": null, "e": 5217, "s": 5029, "text": "However, I believe that as you use it, you will experience the difference immediately. After a while, you will no longer hesitate to change and start using get() and setdefault() methods." }, { "code": null, "e": 5307, "s": 5217, "text": "Remember, when you don’t want to overwrite the original dictionary, go with get() method." } ]
Loading models into tensorflow.js via react.js | by Manfye Goh | Towards Data Science
You had trained your image classification model well in TensorFlow and you eagerly want to integrate it into production and use by your users. However, you found out the problem as below: Due to privacy concern, your user doesn’t want to upload their photo into your server You are poor and you don’t want to create a whole new server just to host a model You need a high latency for your model Thanks to Tensorflow.js (TF.js), the client-side solution that will solve the problems mentioned above. Now you can integrate it with your favorite javascript framework such as React.js and have all the benefits from both sides. The figure below shows the steps required to use your trained model in python into TF.js and this article will mainly focus on the highlighted part in the figure. Importing a TensorFlow model into TensorFlow.js is a two-step process. First, convert an existing model to the TensorFlow.js web format. Use the tensorflowjs package for conversion pip install tensorflowjs Then run the script provided by the package: # Your model format can be: | tf_saved_model | keras | tf_frozen_model | tf_hubtensorflowjs_converter \ --input_format=<"Your model format"> \ --output_node_names=<"Output name"> \ <path/to/your_model> \ <path/to/tfjs_target_dir>* Replace < > with your settings For more information, you can refer to: www.tensorflow.org www.tensorflow.org At the end of this step, you should have a tf.js model which end in β€œ.json” in your path direction. Setup your react application and start the application in the command prompt: #Initiate the react appsnpx create-react-app tfjs-reactcd tfjs-react#Install the required packagenpm install @tensorflow/tfjsnpm install @tensorflow/tfjs-converter#Start the applicationnpm start *for more information, you can refer to the official create react app documentation here Yes, you need to host the model and load it online to be able to use the model. You cannot load from your local directory directly (unless you host it with a server locally) My favorite hosting spot is amazon s3 and CDN services such as BunnyCDN. You must put the model (.json) and the weight (.bin) in the same folder of the hosting in order to get your model working. Import the required packages: import * as tf from '@tensorflow/tfjs';import {loadGraphModel} from '@tensorflow/tfjs-converter'; Define your model URL: const url = {model: '<your model location e.g https://orangerx.b-cdn.net/model/model.json>',}; Load the model via react hook async function loadModel(url) {try {// For layered model// const model = await tf.loadLayersModel(url.model);// For graph model// const model = await tf.loadGraphModel(url.model);setModel(model);console.log("Load model success")}catch (err) {console.log(err);}}//React Hookconst [model, setModel] = useState();useEffect(()=>{tf.ready().then(()=>{loadModel(url)});},[]) If you get the console log of β€œLoad model success” means your model is successfully loaded into TF.js. If you just downloaded the Tf.js model online via anonymous tutorial, the most important part is you have to distinguish the model type, noticed above we have 2 ways to loads the model depends on the model types: Layered model, and Graph Model. The easiest way of distinguishing them is directly open the model file (.json) to see the file structure: A graph model normally will have node information which under model Topology while the layered model doesn’t have the node information: A short answer is, the origin of the model A longer answer is illustrated in the table below: By able to import the model into the client-side powered up my existing react application to achieve better results and user experiences. Many things that can’t be done last time such as client-side sentiment analysis, image classification are now possible thanks to Tf.js. I hope that this article can give you a guide on how to use TF.js and enter the TF.js community. Let’s start building! Next article I will be writing on how do we load media into Tf.js and preprocess it for model predictions. Stay tuned! Thank you, I appreciate your time for reading.
[ { "code": null, "e": 359, "s": 171, "text": "You had trained your image classification model well in TensorFlow and you eagerly want to integrate it into production and use by your users. However, you found out the problem as below:" }, { "code": null, "e": 445, "s": 359, "text": "Due to privacy concern, your user doesn’t want to upload their photo into your server" }, { "code": null, "e": 527, "s": 445, "text": "You are poor and you don’t want to create a whole new server just to host a model" }, { "code": null, "e": 566, "s": 527, "text": "You need a high latency for your model" }, { "code": null, "e": 795, "s": 566, "text": "Thanks to Tensorflow.js (TF.js), the client-side solution that will solve the problems mentioned above. Now you can integrate it with your favorite javascript framework such as React.js and have all the benefits from both sides." }, { "code": null, "e": 958, "s": 795, "text": "The figure below shows the steps required to use your trained model in python into TF.js and this article will mainly focus on the highlighted part in the figure." }, { "code": null, "e": 1139, "s": 958, "text": "Importing a TensorFlow model into TensorFlow.js is a two-step process. First, convert an existing model to the TensorFlow.js web format. Use the tensorflowjs package for conversion" }, { "code": null, "e": 1164, "s": 1139, "text": "pip install tensorflowjs" }, { "code": null, "e": 1209, "s": 1164, "text": "Then run the script provided by the package:" }, { "code": null, "e": 1483, "s": 1209, "text": "# Your model format can be: | tf_saved_model | keras | tf_frozen_model | tf_hubtensorflowjs_converter \\ --input_format=<\"Your model format\"> \\ --output_node_names=<\"Output name\"> \\ <path/to/your_model> \\ <path/to/tfjs_target_dir>* Replace < > with your settings" }, { "code": null, "e": 1523, "s": 1483, "text": "For more information, you can refer to:" }, { "code": null, "e": 1542, "s": 1523, "text": "www.tensorflow.org" }, { "code": null, "e": 1561, "s": 1542, "text": "www.tensorflow.org" }, { "code": null, "e": 1661, "s": 1561, "text": "At the end of this step, you should have a tf.js model which end in β€œ.json” in your path direction." }, { "code": null, "e": 1739, "s": 1661, "text": "Setup your react application and start the application in the command prompt:" }, { "code": null, "e": 1934, "s": 1739, "text": "#Initiate the react appsnpx create-react-app tfjs-reactcd tfjs-react#Install the required packagenpm install @tensorflow/tfjsnpm install @tensorflow/tfjs-converter#Start the applicationnpm start" }, { "code": null, "e": 2023, "s": 1934, "text": "*for more information, you can refer to the official create react app documentation here" }, { "code": null, "e": 2197, "s": 2023, "text": "Yes, you need to host the model and load it online to be able to use the model. You cannot load from your local directory directly (unless you host it with a server locally)" }, { "code": null, "e": 2393, "s": 2197, "text": "My favorite hosting spot is amazon s3 and CDN services such as BunnyCDN. You must put the model (.json) and the weight (.bin) in the same folder of the hosting in order to get your model working." }, { "code": null, "e": 2423, "s": 2393, "text": "Import the required packages:" }, { "code": null, "e": 2521, "s": 2423, "text": "import * as tf from '@tensorflow/tfjs';import {loadGraphModel} from '@tensorflow/tfjs-converter';" }, { "code": null, "e": 2544, "s": 2521, "text": "Define your model URL:" }, { "code": null, "e": 2639, "s": 2544, "text": "const url = {model: '<your model location e.g https://orangerx.b-cdn.net/model/model.json>',};" }, { "code": null, "e": 2669, "s": 2639, "text": "Load the model via react hook" }, { "code": null, "e": 3038, "s": 2669, "text": "async function loadModel(url) {try {// For layered model// const model = await tf.loadLayersModel(url.model);// For graph model// const model = await tf.loadGraphModel(url.model);setModel(model);console.log(\"Load model success\")}catch (err) {console.log(err);}}//React Hookconst [model, setModel] = useState();useEffect(()=>{tf.ready().then(()=>{loadModel(url)});},[])" }, { "code": null, "e": 3141, "s": 3038, "text": "If you get the console log of β€œLoad model success” means your model is successfully loaded into TF.js." }, { "code": null, "e": 3386, "s": 3141, "text": "If you just downloaded the Tf.js model online via anonymous tutorial, the most important part is you have to distinguish the model type, noticed above we have 2 ways to loads the model depends on the model types: Layered model, and Graph Model." }, { "code": null, "e": 3492, "s": 3386, "text": "The easiest way of distinguishing them is directly open the model file (.json) to see the file structure:" }, { "code": null, "e": 3628, "s": 3492, "text": "A graph model normally will have node information which under model Topology while the layered model doesn’t have the node information:" }, { "code": null, "e": 3671, "s": 3628, "text": "A short answer is, the origin of the model" }, { "code": null, "e": 3722, "s": 3671, "text": "A longer answer is illustrated in the table below:" }, { "code": null, "e": 4093, "s": 3722, "text": "By able to import the model into the client-side powered up my existing react application to achieve better results and user experiences. Many things that can’t be done last time such as client-side sentiment analysis, image classification are now possible thanks to Tf.js. I hope that this article can give you a guide on how to use TF.js and enter the TF.js community." }, { "code": null, "e": 4115, "s": 4093, "text": "Let’s start building!" }, { "code": null, "e": 4234, "s": 4115, "text": "Next article I will be writing on how do we load media into Tf.js and preprocess it for model predictions. Stay tuned!" } ]
PHP | Interface - GeeksforGeeks
03 Nov, 2018 An Interface allows the users to create programs, specifying the public methods that a class must implement, without involving the complexities and details of how the particular methods are implemented. It is generally referred to as the next level of abstraction. It resembles the abstract methods, resembling the abstract classes. An Interface is defined just like a class is defined but with the class keyword replaced by the interface keyword and just the function prototypes. The interface contains no data variables. The interface is helpful in a way that it ensures to maintain a sort of metadata for all the methods a programmer wishes to work on. Creating an Interface Following is an example of how to define an interface using the interface keyword. <?php interface MyInterfaceName { public function methodA(); public function methodB();} ?> Few characteristics of an Interface are: An interface consists of methods that have no implementations, which means the interface methods are abstract methods. All the methods in interfaces must have public visibility scope. Interfaces are different from classes as the class can inherit from one class only whereas the class can implement one or more interfaces. To implement an interface, use the implements operator as follows: <?php class MyClassName implements MyInterfaceName{ public function methodA() { // method A implementation } public function methodB(){ // method B implementation } } ?> Concrete Class: The class which implements an interface is called the Concrete Class. It must implement all the methods defined in an interface. Interfaces of the same name can’t be implemented because of ambiguity error. Just like any class, an interface can be extended using the extends operator as follows: <?php interface MyInterfaceName1{ public function methodA(); } interface MyInterfaceName2 extends MyInterfaceName1{ public function methodB();} ?> Example: <?php interface MyInterfaceName{ public function method1(); public function method2(); } class MyClassName implements MyInterfaceName{ public function method1(){ echo "Method1 Called" . "\n"; } public function method2(){ echo "Method2 Called". "\n"; }} $obj = new MyClassName;$obj->method1();$obj->method2(); ?> Method1 Called Method2 Called Advantages of PHP Interface An interface allows unrelated classes to implement the same set of methods, regardless of their positions in the class inheritance hierarchy. An interface can model multiple inheritances because a class can implement more than one interface whereas it can extend only one class. The implementation of an inheritance will save the caller from full implementation of object methods and focus on just he objects interface, therefore, the caller interface remains unaffected. PHP-OOP PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to convert array to string in PHP ? PHP | Converting string to Date and DateTime Download file from URL using PHP Split a comma delimited string into an array in PHP How to fetch data from localserver database and display on HTML table using PHP ? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24483, "s": 24455, "text": "\n03 Nov, 2018" }, { "code": null, "e": 25139, "s": 24483, "text": "An Interface allows the users to create programs, specifying the public methods that a class must implement, without involving the complexities and details of how the particular methods are implemented. It is generally referred to as the next level of abstraction. It resembles the abstract methods, resembling the abstract classes. An Interface is defined just like a class is defined but with the class keyword replaced by the interface keyword and just the function prototypes. The interface contains no data variables. The interface is helpful in a way that it ensures to maintain a sort of metadata for all the methods a programmer wishes to work on." }, { "code": null, "e": 25161, "s": 25139, "text": "Creating an Interface" }, { "code": null, "e": 25244, "s": 25161, "text": "Following is an example of how to define an interface using the interface keyword." }, { "code": "<?php interface MyInterfaceName { public function methodA(); public function methodB();} ?>", "e": 25346, "s": 25244, "text": null }, { "code": null, "e": 25387, "s": 25346, "text": "Few characteristics of an Interface are:" }, { "code": null, "e": 25506, "s": 25387, "text": "An interface consists of methods that have no implementations, which means the interface methods are abstract methods." }, { "code": null, "e": 25571, "s": 25506, "text": "All the methods in interfaces must have public visibility scope." }, { "code": null, "e": 25710, "s": 25571, "text": "Interfaces are different from classes as the class can inherit from one class only whereas the class can implement one or more interfaces." }, { "code": null, "e": 25777, "s": 25710, "text": "To implement an interface, use the implements operator as follows:" }, { "code": "<?php class MyClassName implements MyInterfaceName{ public function methodA() { // method A implementation } public function methodB(){ // method B implementation } } ?>", "e": 25974, "s": 25777, "text": null }, { "code": null, "e": 26285, "s": 25974, "text": "Concrete Class: The class which implements an interface is called the Concrete Class. It must implement all the methods defined in an interface. Interfaces of the same name can’t be implemented because of ambiguity error. Just like any class, an interface can be extended using the extends operator as follows:" }, { "code": "<?php interface MyInterfaceName1{ public function methodA(); } interface MyInterfaceName2 extends MyInterfaceName1{ public function methodB();} ?>", "e": 26450, "s": 26285, "text": null }, { "code": null, "e": 26459, "s": 26450, "text": "Example:" }, { "code": "<?php interface MyInterfaceName{ public function method1(); public function method2(); } class MyClassName implements MyInterfaceName{ public function method1(){ echo \"Method1 Called\" . \"\\n\"; } public function method2(){ echo \"Method2 Called\". \"\\n\"; }} $obj = new MyClassName;$obj->method1();$obj->method2(); ?>", "e": 26816, "s": 26459, "text": null }, { "code": null, "e": 26847, "s": 26816, "text": "Method1 Called\nMethod2 Called\n" }, { "code": null, "e": 26875, "s": 26847, "text": "Advantages of PHP Interface" }, { "code": null, "e": 27017, "s": 26875, "text": "An interface allows unrelated classes to implement the same set of methods, regardless of their positions in the class inheritance hierarchy." }, { "code": null, "e": 27154, "s": 27017, "text": "An interface can model multiple inheritances because a class can implement more than one interface whereas it can extend only one class." }, { "code": null, "e": 27347, "s": 27154, "text": "The implementation of an inheritance will save the caller from full implementation of object methods and focus on just he objects interface, therefore, the caller interface remains unaffected." }, { "code": null, "e": 27355, "s": 27347, "text": "PHP-OOP" }, { "code": null, "e": 27359, "s": 27355, "text": "PHP" }, { "code": null, "e": 27376, "s": 27359, "text": "Web Technologies" }, { "code": null, "e": 27380, "s": 27376, "text": "PHP" }, { "code": null, "e": 27478, "s": 27380, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27487, "s": 27478, "text": "Comments" }, { "code": null, "e": 27500, "s": 27487, "text": "Old Comments" }, { "code": null, "e": 27540, "s": 27500, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 27585, "s": 27540, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 27618, "s": 27585, "text": "Download file from URL using PHP" }, { "code": null, "e": 27670, "s": 27618, "text": "Split a comma delimited string into an array in PHP" }, { "code": null, "e": 27752, "s": 27670, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 27808, "s": 27752, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 27841, "s": 27808, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27903, "s": 27841, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27946, "s": 27903, "text": "How to fetch data from an API in ReactJS ?" } ]
Groovy - size()
Obtains the number of elements in this List. int size() None The size of the list. Following is an example of the usage of this method βˆ’ class Example { static void main(String[] args) { def lst = [11, 12, 13, 14]; println(lst.size); } } When we run the above program, we will get the following result βˆ’ 4 52 Lectures 8 hours Krishna Sakinala 49 Lectures 2.5 hours Packt Publishing Print Add Notes Bookmark this page
[ { "code": null, "e": 2283, "s": 2238, "text": "Obtains the number of elements in this List." }, { "code": null, "e": 2295, "s": 2283, "text": "int size()\n" }, { "code": null, "e": 2300, "s": 2295, "text": "None" }, { "code": null, "e": 2322, "s": 2300, "text": "The size of the list." }, { "code": null, "e": 2376, "s": 2322, "text": "Following is an example of the usage of this method βˆ’" }, { "code": null, "e": 2496, "s": 2376, "text": "class Example {\n static void main(String[] args) {\n def lst = [11, 12, 13, 14];\n println(lst.size);\n } \n}" }, { "code": null, "e": 2562, "s": 2496, "text": "When we run the above program, we will get the following result βˆ’" }, { "code": null, "e": 2565, "s": 2562, "text": "4\n" }, { "code": null, "e": 2598, "s": 2565, "text": "\n 52 Lectures \n 8 hours \n" }, { "code": null, "e": 2616, "s": 2598, "text": " Krishna Sakinala" }, { "code": null, "e": 2651, "s": 2616, "text": "\n 49 Lectures \n 2.5 hours \n" }, { "code": null, "e": 2669, "s": 2651, "text": " Packt Publishing" }, { "code": null, "e": 2676, "s": 2669, "text": " Print" }, { "code": null, "e": 2687, "s": 2676, "text": " Add Notes" } ]
SAP ABAP - Basic Syntax
ABAP source program consists of comments and ABAP statements. Every statement in ABAP begins with a keyword and ends with a period, and ABAP is β€˜Not’ case sensitive. The first non-comment line in a program begins with the word REPORT. The Report will always be the first line of any executable program created. The statement is followed by the program name which was created previously. The line is then terminated with a full stop. The syntax is βˆ’ REPORT [Program_Name]. [Statements...]. This allows the statement to take up as many lines in the editor as it needs. For example, the REPORT may look like this βˆ’ REPORT Z_Test123_01. Statements consist of a command and any variables and options, ending with a period. As long as the period appears at the end of the statement, no problems will arise. It is this period that marks where the statement finishes. Let’s write the code. On the line below the REPORT statement, just type this statement: Write β€˜ABAP Tutorial’. REPORT Z_Test123_01. Write 'This is ABAP Tutorial'. Four things to consider while writing statements βˆ’ The write statement writes whatever is in quotes to the output window. The write statement writes whatever is in quotes to the output window. The ABAP editor converts all text to uppercase except text strings, which are surrounded by single quotation marks. The ABAP editor converts all text to uppercase except text strings, which are surrounded by single quotation marks. Unlike some older programming languages, ABAP does not care where a statement begins on a line. You may take advantage of this and improve the readability of your program by using indentation to indicate blocks of code. Unlike some older programming languages, ABAP does not care where a statement begins on a line. You may take advantage of this and improve the readability of your program by using indentation to indicate blocks of code. ABAP has no restrictions on the layout of statements. That is, multiple statements can be placed on a single line, or a single statement may stretch across multiple lines. ABAP has no restrictions on the layout of statements. That is, multiple statements can be placed on a single line, or a single statement may stretch across multiple lines. Consecutive statements can be chained together if the beginning of each statement is identical. This is done with the colon (:) operator and commas, which are used to terminate the individual statements, much as periods end normal statements. Following is an example of a program that could save some key stroking βˆ’ WRITE 'Hello'. WRITE 'ABAP'. WRITE 'World'. Using the colon notation, it could be rewritten this way βˆ’ WRITE: 'Hello', 'ABAP', 'World'. Like any other ABAP statement, the layout doesn’t matter. This is an equally correct statement βˆ’ WRITE: 'Hello', 'ABAP', 'World'. Inline comments may be declared anywhere in a program by one of the two methods βˆ’ Full line comments are indicated by placing an asterisk (*) in the first position of the line, in which case the entire line is considered by the system to be a comment. Comments don’t need to be terminated by a period because they may not extend across more than one line βˆ’ Full line comments are indicated by placing an asterisk (*) in the first position of the line, in which case the entire line is considered by the system to be a comment. Comments don’t need to be terminated by a period because they may not extend across more than one line βˆ’ * This is the comment line Partial line comments are indicated by entering a double quote (") after a statement. All text following the double quote is considered by the system to be a comment. You need not terminate partial line comments by a period because they may not extend across more than one line βˆ’ Partial line comments are indicated by entering a double quote (") after a statement. All text following the double quote is considered by the system to be a comment. You need not terminate partial line comments by a period because they may not extend across more than one line βˆ’ WRITE 'Hello'. "Here is the partial comment Note βˆ’ Commented code is not capitalized by the ABAP editor. The NO-ZERO command follows the DATA statement. It suppresses all leading zeros of a number field containing blanks. The output is usually easier for the users to read. REPORT Z_Test123_01. DATA: W_NUR(10) TYPE N. MOVE 50 TO W_NUR. WRITE W_NUR NO-ZERO. The above code produces the following output βˆ’ 50 Note βˆ’ Without NO-ZERO command, the output is: 0000000050 The SKIP command helps in inserting blank lines on the page. The message command is as follows βˆ’ WRITE 'This is the 1st line'. SKIP. WRITE 'This is the 2nd line'. The above message command produces the following output βˆ’ This is the 1st line This is the 2nd line We may use the SKIP command to insert multiple blank lines. SKIP number_of_lines. The output would be several blank lines defined by the number of lines. The SKIP command can also position the cursor on a desired line on the page. SKIP TO LINE line_number. This command is used to dynamically move the cursor up and down the page. Usually, a WRITE statement occurs after this command to put output on that desired line. The ULINE command automatically inserts a horizontal line across the output. It’s also possible to control the position and length of the line. The syntax is pretty simple βˆ’ ULINE. The message command is as follows βˆ’ WRITE 'This is Underlined'. ULINE. The above code produces the following output βˆ’ This is Underlined (and a horizontal line below this). The MESSAGE command displays messages defined by a message ID specified in the REPORT statement at the beginning of the program. The message ID is a 2 character code that defines which set of 1,000 messages the program will access when the MESSAGE command is used. The messages are numbered from 000 to 999. Associated with each number is a message text up to a maximum of 80 characters. When message number is called, the corresponding text is displayed. Following are the characters for use with the Message command βˆ’ Error messages are normally used to stop users from doing things they are not supposed to do. Warning messages are generally used to remind the users of the consequences of their actions. Information messages give the users useful information. When we create a message for message the ID AB, the MESSAGE command - MESSAGE E011 gives the following output βˆ’ EAB011 This report does not support sub-number summarization. 25 Lectures 6 hours Sanjo Thomas 26 Lectures 2 hours Neha Gupta 30 Lectures 2.5 hours Sumit Agarwal 30 Lectures 4 hours Sumit Agarwal 14 Lectures 1.5 hours Neha Malik 13 Lectures 1.5 hours Neha Malik Print Add Notes Bookmark this page
[ { "code": null, "e": 3064, "s": 2898, "text": "ABAP source program consists of comments and ABAP statements. Every statement in ABAP begins with a keyword and ends with a period, and ABAP is β€˜Not’ case sensitive." }, { "code": null, "e": 3331, "s": 3064, "text": "The first non-comment line in a program begins with the word REPORT. The Report will always be the first line of any executable program created. The statement is followed by the program name which was created previously. The line is then terminated with a full stop." }, { "code": null, "e": 3347, "s": 3331, "text": "The syntax is βˆ’" }, { "code": null, "e": 3392, "s": 3347, "text": "REPORT [Program_Name]. \n \n[Statements...]. \n" }, { "code": null, "e": 3515, "s": 3392, "text": "This allows the statement to take up as many lines in the editor as it needs. For example, the REPORT may look like this βˆ’" }, { "code": null, "e": 3537, "s": 3515, "text": "REPORT Z_Test123_01. " }, { "code": null, "e": 3764, "s": 3537, "text": "Statements consist of a command and any variables and options, ending with a period. As long as the period appears at the end of the statement, no problems will arise. It is this period that marks where the statement finishes." }, { "code": null, "e": 3786, "s": 3764, "text": "Let’s write the code." }, { "code": null, "e": 3875, "s": 3786, "text": "On the line below the REPORT statement, just type this statement: Write β€˜ABAP Tutorial’." }, { "code": null, "e": 3929, "s": 3875, "text": "REPORT Z_Test123_01.\n\nWrite 'This is ABAP Tutorial'. " }, { "code": null, "e": 3980, "s": 3929, "text": "Four things to consider while writing statements βˆ’" }, { "code": null, "e": 4051, "s": 3980, "text": "The write statement writes whatever is in quotes to the output window." }, { "code": null, "e": 4122, "s": 4051, "text": "The write statement writes whatever is in quotes to the output window." }, { "code": null, "e": 4238, "s": 4122, "text": "The ABAP editor converts all text to uppercase except text strings, which are surrounded by single quotation marks." }, { "code": null, "e": 4354, "s": 4238, "text": "The ABAP editor converts all text to uppercase except text strings, which are surrounded by single quotation marks." }, { "code": null, "e": 4574, "s": 4354, "text": "Unlike some older programming languages, ABAP does not care where a statement begins on a line. You may take advantage of this and improve the readability of your program by using indentation to indicate blocks of code." }, { "code": null, "e": 4794, "s": 4574, "text": "Unlike some older programming languages, ABAP does not care where a statement begins on a line. You may take advantage of this and improve the readability of your program by using indentation to indicate blocks of code." }, { "code": null, "e": 4966, "s": 4794, "text": "ABAP has no restrictions on the layout of statements. That is, multiple statements can be placed on a single line, or a single statement may stretch across multiple lines." }, { "code": null, "e": 5138, "s": 4966, "text": "ABAP has no restrictions on the layout of statements. That is, multiple statements can be placed on a single line, or a single statement may stretch across multiple lines." }, { "code": null, "e": 5381, "s": 5138, "text": "Consecutive statements can be chained together if the beginning of each statement is identical. This is done with the colon (:) operator and commas, which are used to terminate the individual statements, much as periods end normal statements." }, { "code": null, "e": 5454, "s": 5381, "text": "Following is an example of a program that could save some key stroking βˆ’" }, { "code": null, "e": 5501, "s": 5454, "text": "WRITE 'Hello'. \nWRITE 'ABAP'. \nWRITE 'World'. " }, { "code": null, "e": 5560, "s": 5501, "text": "Using the colon notation, it could be rewritten this way βˆ’" }, { "code": null, "e": 5609, "s": 5560, "text": "WRITE: 'Hello', \n 'ABAP', \n 'World'." }, { "code": null, "e": 5706, "s": 5609, "text": "Like any other ABAP statement, the layout doesn’t matter. This is an equally correct statement βˆ’" }, { "code": null, "e": 5739, "s": 5706, "text": "WRITE: 'Hello', 'ABAP', 'World'." }, { "code": null, "e": 5821, "s": 5739, "text": "Inline comments may be declared anywhere in a program by one of the two methods βˆ’" }, { "code": null, "e": 6096, "s": 5821, "text": "Full line comments are indicated by placing an asterisk (*) in the first position of the line, in which case the entire line is considered by the system to be a comment. Comments don’t need to be terminated by a period because they may not extend across more than one line βˆ’" }, { "code": null, "e": 6371, "s": 6096, "text": "Full line comments are indicated by placing an asterisk (*) in the first position of the line, in which case the entire line is considered by the system to be a comment. Comments don’t need to be terminated by a period because they may not extend across more than one line βˆ’" }, { "code": null, "e": 6399, "s": 6371, "text": "* This is the comment line\n" }, { "code": null, "e": 6679, "s": 6399, "text": "Partial line comments are indicated by entering a double quote (\") after a statement. All text following the double quote is considered by the system to be a comment. You need not terminate partial line comments by a period because they may not extend across more than one line βˆ’" }, { "code": null, "e": 6959, "s": 6679, "text": "Partial line comments are indicated by entering a double quote (\") after a statement. All text following the double quote is considered by the system to be a comment. You need not terminate partial line comments by a period because they may not extend across more than one line βˆ’" }, { "code": null, "e": 7003, "s": 6959, "text": "WRITE 'Hello'. \"Here is the partial comment" }, { "code": null, "e": 7064, "s": 7003, "text": "Note βˆ’ Commented code is not capitalized by the ABAP editor." }, { "code": null, "e": 7233, "s": 7064, "text": "The NO-ZERO command follows the DATA statement. It suppresses all leading zeros of a number field containing blanks. The output is usually easier for the users to read." }, { "code": null, "e": 7331, "s": 7233, "text": "REPORT Z_Test123_01. \n\nDATA: W_NUR(10) TYPE N.\n MOVE 50 TO W_NUR.\n WRITE W_NUR NO-ZERO." }, { "code": null, "e": 7378, "s": 7331, "text": "The above code produces the following output βˆ’" }, { "code": null, "e": 7382, "s": 7378, "text": "50\n" }, { "code": null, "e": 7440, "s": 7382, "text": "Note βˆ’ Without NO-ZERO command, the output is: 0000000050" }, { "code": null, "e": 7501, "s": 7440, "text": "The SKIP command helps in inserting blank lines on the page." }, { "code": null, "e": 7537, "s": 7501, "text": "The message command is as follows βˆ’" }, { "code": null, "e": 7606, "s": 7537, "text": "WRITE 'This is the 1st line'. \nSKIP. \nWRITE 'This is the 2nd line'. " }, { "code": null, "e": 7664, "s": 7606, "text": "The above message command produces the following output βˆ’" }, { "code": null, "e": 7707, "s": 7664, "text": "This is the 1st line \nThis is the 2nd line" }, { "code": null, "e": 7767, "s": 7707, "text": "We may use the SKIP command to insert multiple blank lines." }, { "code": null, "e": 7790, "s": 7767, "text": "SKIP number_of_lines. " }, { "code": null, "e": 7939, "s": 7790, "text": "The output would be several blank lines defined by the number of lines. The SKIP command can also position the cursor on a desired line on the page." }, { "code": null, "e": 7966, "s": 7939, "text": "SKIP TO LINE line_number. " }, { "code": null, "e": 8129, "s": 7966, "text": "This command is used to dynamically move the cursor up and down the page. Usually, a WRITE statement occurs after this command to put output on that desired line." }, { "code": null, "e": 8303, "s": 8129, "text": "The ULINE command automatically inserts a horizontal line across the output. It’s also possible to control the position and length of the line. The syntax is pretty simple βˆ’" }, { "code": null, "e": 8311, "s": 8303, "text": "ULINE.\n" }, { "code": null, "e": 8347, "s": 8311, "text": "The message command is as follows βˆ’" }, { "code": null, "e": 8382, "s": 8347, "text": "WRITE 'This is Underlined'.\nULINE." }, { "code": null, "e": 8429, "s": 8382, "text": "The above code produces the following output βˆ’" }, { "code": null, "e": 8485, "s": 8429, "text": "This is Underlined (and a horizontal line below this).\n" }, { "code": null, "e": 8750, "s": 8485, "text": "The MESSAGE command displays messages defined by a message ID specified in the REPORT statement at the beginning of the program. The message ID is a 2 character code that defines which set of 1,000 messages the program will access when the MESSAGE command is used." }, { "code": null, "e": 8941, "s": 8750, "text": "The messages are numbered from 000 to 999. Associated with each number is a message text up to a maximum of 80 characters. When message number is called, the corresponding text is displayed." }, { "code": null, "e": 9005, "s": 8941, "text": "Following are the characters for use with the Message command βˆ’" }, { "code": null, "e": 9249, "s": 9005, "text": "Error messages are normally used to stop users from doing things they are not supposed to do. Warning messages are generally used to remind the users of the consequences of their actions. Information messages give the users useful information." }, { "code": null, "e": 9361, "s": 9249, "text": "When we create a message for message the ID AB, the MESSAGE command - MESSAGE E011 gives the following output βˆ’" }, { "code": null, "e": 9424, "s": 9361, "text": "EAB011 This report does not support sub-number summarization.\n" }, { "code": null, "e": 9457, "s": 9424, "text": "\n 25 Lectures \n 6 hours \n" }, { "code": null, "e": 9471, "s": 9457, "text": " Sanjo Thomas" }, { "code": null, "e": 9504, "s": 9471, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 9516, "s": 9504, "text": " Neha Gupta" }, { "code": null, "e": 9551, "s": 9516, "text": "\n 30 Lectures \n 2.5 hours \n" }, { "code": null, "e": 9566, "s": 9551, "text": " Sumit Agarwal" }, { "code": null, "e": 9599, "s": 9566, "text": "\n 30 Lectures \n 4 hours \n" }, { "code": null, "e": 9614, "s": 9599, "text": " Sumit Agarwal" }, { "code": null, "e": 9649, "s": 9614, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 9661, "s": 9649, "text": " Neha Malik" }, { "code": null, "e": 9696, "s": 9661, "text": "\n 13 Lectures \n 1.5 hours \n" }, { "code": null, "e": 9708, "s": 9696, "text": " Neha Malik" }, { "code": null, "e": 9715, "s": 9708, "text": " Print" }, { "code": null, "e": 9726, "s": 9715, "text": " Add Notes" } ]
Tryit Editor v3.6 - Show Python
mydb = mysql.connector.connect( host="localhost", user="myusername", password="mypassword", database="mydatabase" ) ​ mycursor = mydb.cursor()
[ { "code": null, "e": 57, "s": 25, "text": "mydb = mysql.connector.connect(" }, { "code": null, "e": 77, "s": 57, "text": " host=\"localhost\"," }, { "code": null, "e": 98, "s": 77, "text": " user=\"myusername\"," }, { "code": null, "e": 123, "s": 98, "text": " password=\"mypassword\"," }, { "code": null, "e": 147, "s": 123, "text": " database=\"mydatabase\"" }, { "code": null, "e": 149, "s": 147, "text": ")" }, { "code": null, "e": 151, "s": 149, "text": "​" } ]
Swing Examples - Add Border to JLabel
Following example showcase how to add border to a JLabel in a Java Swing application. We are using the following APIs. BorderFactory.createLineBorder() βˆ’ To create a line border. BorderFactory.createLineBorder() βˆ’ To create a line border. JLabel.setBorder(border) βˆ’ To set the desired border to the JLabel. JLabel.setBorder(border) βˆ’ To set the desired border to the JLabel. import java.awt.BorderLayout; import java.awt.Color; import java.awt.FlowLayout; import java.awt.LayoutManager; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.border.Border; public class SwingTester { public static void main(String[] args) { createWindow(); } private static void createWindow() { JFrame frame = new JFrame("Swing Tester"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); createUI(frame); frame.setSize(560, 200); frame.setLocationRelativeTo(null); frame.setVisible(true); } private static void createUI(JFrame frame){ //Create a border Border blackline = BorderFactory.createLineBorder(Color.black); JPanel panel = new JPanel(); LayoutManager layout = new FlowLayout(); panel.setLayout(layout); JPanel panel1 = new JPanel(); String spaces = " "; JLabel label = new JLabel(spaces + "Border to JLabel" + spaces); label.setBorder(blackline); panel1.add(label); panel1.add( new JLabel(spaces + "JLabel with no border" + spaces)); panel.add(panel1); frame.getContentPane().add(panel, BorderLayout.CENTER); } } Print Add Notes Bookmark this page
[ { "code": null, "e": 2125, "s": 2039, "text": "Following example showcase how to add border to a JLabel in a Java Swing application." }, { "code": null, "e": 2158, "s": 2125, "text": "We are using the following APIs." }, { "code": null, "e": 2218, "s": 2158, "text": "BorderFactory.createLineBorder() βˆ’ To create a line border." }, { "code": null, "e": 2278, "s": 2218, "text": "BorderFactory.createLineBorder() βˆ’ To create a line border." }, { "code": null, "e": 2346, "s": 2278, "text": "JLabel.setBorder(border) βˆ’ To set the desired border to the JLabel." }, { "code": null, "e": 2414, "s": 2346, "text": "JLabel.setBorder(border) βˆ’ To set the desired border to the JLabel." }, { "code": null, "e": 3719, "s": 2414, "text": "import java.awt.BorderLayout;\nimport java.awt.Color;\nimport java.awt.FlowLayout;\nimport java.awt.LayoutManager;\n\nimport javax.swing.BorderFactory;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JPanel;\nimport javax.swing.border.Border;\n\npublic class SwingTester {\n public static void main(String[] args) {\n createWindow();\n }\n\n private static void createWindow() { \n JFrame frame = new JFrame(\"Swing Tester\");\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\n createUI(frame);\n frame.setSize(560, 200); \n frame.setLocationRelativeTo(null); \n frame.setVisible(true);\n }\n\n private static void createUI(JFrame frame){\n //Create a border\n Border blackline = BorderFactory.createLineBorder(Color.black);\n JPanel panel = new JPanel();\n LayoutManager layout = new FlowLayout(); \n panel.setLayout(layout); \n JPanel panel1 = new JPanel();\n String spaces = \" \";\n JLabel label = new JLabel(spaces + \"Border to JLabel\" + spaces);\n label.setBorder(blackline);\n panel1.add(label); \n panel1.add( new JLabel(spaces + \"JLabel with no border\" + spaces)); \n panel.add(panel1);\n frame.getContentPane().add(panel, BorderLayout.CENTER); \n }\n}" }, { "code": null, "e": 3726, "s": 3719, "text": " Print" }, { "code": null, "e": 3737, "s": 3726, "text": " Add Notes" } ]
How to Simply Deploy a Smart Contract on Ethereum? - GeeksforGeeks
06 Aug, 2021 Smart contracts are blocks of code that reside on the blockchain. It is like an Ethereum account but there is a critical difference between an external account and a smart contract. Unlike a smart contract, an external account can connect to multiple Ethereum networks (Rinkebey, Kovan, main, etc.) whereas a smart contract is only specific to one individual network (the network it is deployed on). When a smart contract is deployed, it creates an instance (contract account) on the network. One can create multiple instances of a smart contract on the network or multiple networks. Deployment of a smart contract is done by sending a transaction to the network with bytecode. An emulator can be used to deploy a smart contract on a local network eg. Ganache-cli. It takes care of everything and the user doesn’t have to worry about the security and the gas amount required for transactions since everything is happening on a local test network. All one has to do is pass the ganache provider as an argument to the web3 instance(web3 facilitates the connection between the blockchain network and the js application). Before deploying a smart contract to an actual Ethereum network make sure the account has some ether in it. Deploying a contract is like sending a transaction and it needs some gas amount to process. Unlike deploying on a local network, transactions will take some time to complete (anywhere between 15 seconds to 5 minutes). Web3 is used to interact with the network the same way it is done in local deployment except customize the provider that will be passed into the web3 instance. Instead of creating our own node that connects to the Ethereum network, one can use Infura. It is a public API that gives access to the Infura node that is already hosted on the Ethereum network. Simply sign-up for Infura and get an endpoint that will be used in the code to deploy the smart contract. example.sol- Below is the sample solidity code used for testing. All it does is set a public variable as the address of the sender. Solidity // Solidity program to implement// the above approachpragma solidity ^0.8.4; // Creating a contract named Examplecontract Example{ // Public variable of type address address public manager; // Constructor function to set manager // as address of sender constructor() { manager = msg.sender; }} Step 1- Install the required dependencies by running the following commands- npm i [email protected] [email protected] [email protected] Make sure to install the same versions for the following scripts to run successfully. Step 2- Sign up for Infura and create a project on a particular Ethereum network to get access to the endpoint. The endpoint will be required to deploy the smart contract on the infura node that is already hosted on the Ethereum network. To create a project on infura- Click on create a new project. Give it a name. Select the network to deploy the smart contract on. A maximum of 3 projects can be created on infura for free. Step 3 – Get access to Bytecode and ABI (Compile the smart contract). Solidity compiler gives a huge piece of code as output, one can print the output to console if required. Only the relevant part (relevant for deployment) i.e., bytecode and interface are extracted from the output in the following script. Compile.js- Below is the javascript file. Javascript // Javascript file to implement// the above approachconst path = require("path");const fs = require("fs");const solc = require("solc"); // remember to change line 8 to your// own file path. Make sure you have your// own file name or contract name in line// 13, 28 and 30 as well. const examplePath = path.resolve(__dirname, "contracts", "example.sol");const source = fs.readFileSync(examplePath, "utf-8"); var input = { language: 'Solidity', sources: { 'example.sol': { content: source } }, settings: { outputSelection: { '*': { '*': ['*'] } } }}; var output = JSON.parse(solc.compile(JSON.stringify(input))); var interface = output.contracts["example.sol"]["example"].abi; var bytecode = output.contracts['example.sol']["example"].evm.bytecode.object; module.exports = { interface, bytecode }; Step 4 – Add Metamask extension to google chrome from the chrome web store. Step 5 – Once have access to bytecode and interface, all that is required is to create a provider with own mnemonic phrase and infura endpoint using the truffle-hdwallet-provider that was installed earlier. Create a web3 instance and pass the provider as an argument. Finally, use the deploy method with bytecode as an argument to deploy the smart contract. deploy.js Javascript const HDWalletProvider = require("truffle-hdwallet-provider"); // Web3 constructor function.const Web3 = require("web3"); // Get bytecode and ABI after compiling// solidity code.const { interface, bytecode } = require("file-path"); const provider = new HDWalletProvider( "mnemonic phrase", // Remember to change this to your own phrase! "-" // Remember to change this to your own endpoint!); // Create an instance of Web3 and pass the// provider as an argument.const web3 = new Web3(provider); const deploy = async () => { // Get access to all accounts linked to mnemonic // Make sure you have metamask installed. const accounts = await web3.eth.getAccounts(); console.log("Attempting to deploy from account", accounts[0]); // Pass initial gas and account to use in the send function const result = await new web3.eth.Contract(interface) .deploy({ data: bytecode }) .send({ gas: "1000000", from: accounts[0]}); console.log("Contract deployed to", result.options.address);}; deploy(); // The purpose of creating a function and// calling it at the end -// so that we can use async await instead// of using promises Output: Contract is deployed to 0x8716443863c87ee791C1ee15289e61503Ad4443c Now the contract is deployed on the network, its functionality can be tested using remix IDE or one can create an interface to interact with the smart contract on the network. Remix can be used to connect to actual Ethereum networks and interact with deployed smart contracts. It is the easiest way to interact with a deployed smart contract without having to make a fancy frontend. Step 1- Open Remix IDE in chrome browser and copy the solidity code of the deployed smart contract and paste it in the Ballot.sol file in the IDE. Switch to the solidity compiler by clicking on the β€œS” icon on the sidebar and compile it. Step 2- Navigate to Deploy and run transactions from the sidebar and select injected web3 from environment dropdown. It is the instance of web3 injected by metamask into your browser. It also has access to all the accounts. Step 3- Instead of deploying the smart contract, copy the address of the already deployed smart contract in the β€œAt Address” field. This button is disabled until you put in a valid address. Once the button is clicked, the list of functions from your smart contracts can be seen. One can interact with a deployed smart contract using these function buttons. Since the β€œexample.sol” has only one variable, manager. Clicking this button will give the address of the account it was deployed from as the output. BlockChain Picked Blockchain Solidity Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Set up Ganche with Metamask? Blockchain Merkle Trees How to connect ReactJS with MetaMask ? How to Setup Your Own Private Ethereum Network? Advantages and Disadvantages of Blockchain Storage vs Memory in Solidity Mathematical Operations in Solidity Dynamic Arrays and its Operations in Solidity Solidity - Inheritance How to Install Solidity in Windows?
[ { "code": null, "e": 24247, "s": 24219, "text": "\n06 Aug, 2021" }, { "code": null, "e": 24925, "s": 24247, "text": "Smart contracts are blocks of code that reside on the blockchain. It is like an Ethereum account but there is a critical difference between an external account and a smart contract. Unlike a smart contract, an external account can connect to multiple Ethereum networks (Rinkebey, Kovan, main, etc.) whereas a smart contract is only specific to one individual network (the network it is deployed on). When a smart contract is deployed, it creates an instance (contract account) on the network. One can create multiple instances of a smart contract on the network or multiple networks. Deployment of a smart contract is done by sending a transaction to the network with bytecode." }, { "code": null, "e": 25366, "s": 24925, "text": "An emulator can be used to deploy a smart contract on a local network eg. Ganache-cli. It takes care of everything and the user doesn’t have to worry about the security and the gas amount required for transactions since everything is happening on a local test network. All one has to do is pass the ganache provider as an argument to the web3 instance(web3 facilitates the connection between the blockchain network and the js application). " }, { "code": null, "e": 26154, "s": 25366, "text": "Before deploying a smart contract to an actual Ethereum network make sure the account has some ether in it. Deploying a contract is like sending a transaction and it needs some gas amount to process. Unlike deploying on a local network, transactions will take some time to complete (anywhere between 15 seconds to 5 minutes). Web3 is used to interact with the network the same way it is done in local deployment except customize the provider that will be passed into the web3 instance. Instead of creating our own node that connects to the Ethereum network, one can use Infura. It is a public API that gives access to the Infura node that is already hosted on the Ethereum network. Simply sign-up for Infura and get an endpoint that will be used in the code to deploy the smart contract." }, { "code": null, "e": 26286, "s": 26154, "text": "example.sol- Below is the sample solidity code used for testing. All it does is set a public variable as the address of the sender." }, { "code": null, "e": 26295, "s": 26286, "text": "Solidity" }, { "code": "// Solidity program to implement// the above approachpragma solidity ^0.8.4; // Creating a contract named Examplecontract Example{ // Public variable of type address address public manager; // Constructor function to set manager // as address of sender constructor() { manager = msg.sender; }}", "e": 26621, "s": 26295, "text": null }, { "code": null, "e": 26698, "s": 26621, "text": "Step 1- Install the required dependencies by running the following commands-" }, { "code": null, "e": 26759, "s": 26698, "text": "npm i [email protected] [email protected] [email protected]" }, { "code": null, "e": 26845, "s": 26759, "text": "Make sure to install the same versions for the following scripts to run successfully." }, { "code": null, "e": 27114, "s": 26845, "text": "Step 2- Sign up for Infura and create a project on a particular Ethereum network to get access to the endpoint. The endpoint will be required to deploy the smart contract on the infura node that is already hosted on the Ethereum network. To create a project on infura-" }, { "code": null, "e": 27145, "s": 27114, "text": "Click on create a new project." }, { "code": null, "e": 27161, "s": 27145, "text": "Give it a name." }, { "code": null, "e": 27214, "s": 27161, "text": "Select the network to deploy the smart contract on. " }, { "code": null, "e": 27273, "s": 27214, "text": "A maximum of 3 projects can be created on infura for free." }, { "code": null, "e": 27581, "s": 27273, "text": "Step 3 – Get access to Bytecode and ABI (Compile the smart contract). Solidity compiler gives a huge piece of code as output, one can print the output to console if required. Only the relevant part (relevant for deployment) i.e., bytecode and interface are extracted from the output in the following script." }, { "code": null, "e": 27623, "s": 27581, "text": "Compile.js- Below is the javascript file." }, { "code": null, "e": 27634, "s": 27623, "text": "Javascript" }, { "code": "// Javascript file to implement// the above approachconst path = require(\"path\");const fs = require(\"fs\");const solc = require(\"solc\"); // remember to change line 8 to your// own file path. Make sure you have your// own file name or contract name in line// 13, 28 and 30 as well. const examplePath = path.resolve(__dirname, \"contracts\", \"example.sol\");const source = fs.readFileSync(examplePath, \"utf-8\"); var input = { language: 'Solidity', sources: { 'example.sol': { content: source } }, settings: { outputSelection: { '*': { '*': ['*'] } } }}; var output = JSON.parse(solc.compile(JSON.stringify(input))); var interface = output.contracts[\"example.sol\"][\"example\"].abi; var bytecode = output.contracts['example.sol'][\"example\"].evm.bytecode.object; module.exports = { interface, bytecode };", "e": 28520, "s": 27634, "text": null }, { "code": null, "e": 28598, "s": 28522, "text": "Step 4 – Add Metamask extension to google chrome from the chrome web store." }, { "code": null, "e": 28956, "s": 28598, "text": "Step 5 – Once have access to bytecode and interface, all that is required is to create a provider with own mnemonic phrase and infura endpoint using the truffle-hdwallet-provider that was installed earlier. Create a web3 instance and pass the provider as an argument. Finally, use the deploy method with bytecode as an argument to deploy the smart contract." }, { "code": null, "e": 28966, "s": 28956, "text": "deploy.js" }, { "code": null, "e": 28977, "s": 28966, "text": "Javascript" }, { "code": "const HDWalletProvider = require(\"truffle-hdwallet-provider\"); // Web3 constructor function.const Web3 = require(\"web3\"); // Get bytecode and ABI after compiling// solidity code.const { interface, bytecode } = require(\"file-path\"); const provider = new HDWalletProvider( \"mnemonic phrase\", // Remember to change this to your own phrase! \"-\" // Remember to change this to your own endpoint!); // Create an instance of Web3 and pass the// provider as an argument.const web3 = new Web3(provider); const deploy = async () => { // Get access to all accounts linked to mnemonic // Make sure you have metamask installed. const accounts = await web3.eth.getAccounts(); console.log(\"Attempting to deploy from account\", accounts[0]); // Pass initial gas and account to use in the send function const result = await new web3.eth.Contract(interface) .deploy({ data: bytecode }) .send({ gas: \"1000000\", from: accounts[0]}); console.log(\"Contract deployed to\", result.options.address);}; deploy(); // The purpose of creating a function and// calling it at the end -// so that we can use async await instead// of using promises", "e": 30110, "s": 28977, "text": null }, { "code": null, "e": 30119, "s": 30110, "text": "Output: " }, { "code": null, "e": 30186, "s": 30119, "text": "Contract is deployed to 0x8716443863c87ee791C1ee15289e61503Ad4443c" }, { "code": null, "e": 30362, "s": 30186, "text": "Now the contract is deployed on the network, its functionality can be tested using remix IDE or one can create an interface to interact with the smart contract on the network." }, { "code": null, "e": 30570, "s": 30362, "text": "Remix can be used to connect to actual Ethereum networks and interact with deployed smart contracts. It is the easiest way to interact with a deployed smart contract without having to make a fancy frontend. " }, { "code": null, "e": 30808, "s": 30570, "text": "Step 1- Open Remix IDE in chrome browser and copy the solidity code of the deployed smart contract and paste it in the Ballot.sol file in the IDE. Switch to the solidity compiler by clicking on the β€œS” icon on the sidebar and compile it." }, { "code": null, "e": 31032, "s": 30808, "text": "Step 2- Navigate to Deploy and run transactions from the sidebar and select injected web3 from environment dropdown. It is the instance of web3 injected by metamask into your browser. It also has access to all the accounts." }, { "code": null, "e": 31539, "s": 31032, "text": "Step 3- Instead of deploying the smart contract, copy the address of the already deployed smart contract in the β€œAt Address” field. This button is disabled until you put in a valid address. Once the button is clicked, the list of functions from your smart contracts can be seen. One can interact with a deployed smart contract using these function buttons. Since the β€œexample.sol” has only one variable, manager. Clicking this button will give the address of the account it was deployed from as the output." }, { "code": null, "e": 31550, "s": 31539, "text": "BlockChain" }, { "code": null, "e": 31557, "s": 31550, "text": "Picked" }, { "code": null, "e": 31568, "s": 31557, "text": "Blockchain" }, { "code": null, "e": 31577, "s": 31568, "text": "Solidity" }, { "code": null, "e": 31675, "s": 31577, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31684, "s": 31675, "text": "Comments" }, { "code": null, "e": 31697, "s": 31684, "text": "Old Comments" }, { "code": null, "e": 31733, "s": 31697, "text": "How to Set up Ganche with Metamask?" }, { "code": null, "e": 31757, "s": 31733, "text": "Blockchain Merkle Trees" }, { "code": null, "e": 31796, "s": 31757, "text": "How to connect ReactJS with MetaMask ?" }, { "code": null, "e": 31844, "s": 31796, "text": "How to Setup Your Own Private Ethereum Network?" }, { "code": null, "e": 31887, "s": 31844, "text": "Advantages and Disadvantages of Blockchain" }, { "code": null, "e": 31917, "s": 31887, "text": "Storage vs Memory in Solidity" }, { "code": null, "e": 31953, "s": 31917, "text": "Mathematical Operations in Solidity" }, { "code": null, "e": 31999, "s": 31953, "text": "Dynamic Arrays and its Operations in Solidity" }, { "code": null, "e": 32022, "s": 31999, "text": "Solidity - Inheritance" } ]
How to view the complete output of tibble in R?
Tibbles are created when we analyze data using dplyr package and if the data size is large then only 10 values are printed in R. If we want to display the complete output of tibble then View function needs to be used. For example, if we want to perform calculation of counts then we should add View() at the end of the code with pipe operator. Live Demo Consider the below data frame βˆ’ Group<βˆ’rep(c("A","B","C","D","E"),times=10) Rating<βˆ’sample(1:10,50,replace=TRUE) df<βˆ’data.frame(Group,Rating) head(df,20) Group Rating 1 A 4 2 B 2 3 C 8 4 D 3 5 E 3 6 A 1 7 B 8 8 C 8 9 D 1 10 E 2 11 A 2 12 B 8 13 C 10 14 D 4 15 E 6 16 A 3 17 B 7 18 C 1 19 D 5 20 E 10 tail(df,20) Group Rating 31 A 2 32 B 5 33 C 4 34 D 1 35 E 4 36 A 8 37 B 2 38 C 6 39 D 2 40 E 5 41 A 1 42 B 4 43 C 9 44 D 5 45 E 2 46 A 7 47 B 10 48 C 9 49 D 1 50 E 6 Loading dplyr package βˆ’ library(dplyr) Finding the counts for Group and Rating and viewing the whole output using View() βˆ’ df%>%group_by(Group,Rating)%>%mutate(count=n())%>%View()
[ { "code": null, "e": 1406, "s": 1062, "text": "Tibbles are created when we analyze data using dplyr package and if the data size is large then only 10 values are printed in R. If we want to display the complete output of tibble then View function needs to be used. For example, if we want to perform calculation of counts then we should add View() at the end of the code with pipe operator." }, { "code": null, "e": 1417, "s": 1406, "text": " Live Demo" }, { "code": null, "e": 1449, "s": 1417, "text": "Consider the below data frame βˆ’" }, { "code": null, "e": 1571, "s": 1449, "text": "Group<βˆ’rep(c(\"A\",\"B\",\"C\",\"D\",\"E\"),times=10)\nRating<βˆ’sample(1:10,50,replace=TRUE)\ndf<βˆ’data.frame(Group,Rating)\nhead(df,20)" }, { "code": null, "e": 1717, "s": 1571, "text": "Group Rating\n1 A 4\n2 B 2\n3 C 8\n4 D 3\n5 E 3\n6 A 1\n7 B 8\n8 C 8\n9 D 1\n10 E 2\n11 A 2\n12 B 8\n13 C 10\n14 D 4\n15 E 6\n16 A 3\n17 B 7\n18 C 1\n19 D 5\n20 E 10" }, { "code": null, "e": 1729, "s": 1717, "text": "tail(df,20)" }, { "code": null, "e": 1883, "s": 1729, "text": "Group Rating\n31 A 2\n32 B 5\n33 C 4\n34 D 1\n35 E 4\n36 A 8\n37 B 2\n38 C 6\n39 D 2\n40 E 5\n41 A 1\n42 B 4\n43 C 9\n44 D 5\n45 E 2\n46 A 7\n47 B 10\n48 C 9\n49 D 1\n50 E 6" }, { "code": null, "e": 1907, "s": 1883, "text": "Loading dplyr package βˆ’" }, { "code": null, "e": 1923, "s": 1907, "text": "library(dplyr)\n" }, { "code": null, "e": 2007, "s": 1923, "text": "Finding the counts for Group and Rating and viewing the whole output using View() βˆ’" }, { "code": null, "e": 2064, "s": 2007, "text": "df%>%group_by(Group,Rating)%>%mutate(count=n())%>%View()" } ]
Rendering Static HTML page using Django - onlinetutorialspoint
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws In this tutorial, we will learn how to render static HTML pages in a Django application. Python 3.7, 3.8 Django 3.1 HTML 5 The first step of beginning any python project is creating a virtual environment. Follow this tutorial to set up and activate a virtualenvand then install Django. virtualenv env source env/bin/activate pip install Django Start a Django project (here, project name:django_html) and create an app named home. Check this tutorial for more details. django-admin startproject django_html cd django_html/ python manage.py startapp home Django uses templates to generate HTML dynamically. A template contains the static part as well some static syntax for displaying the dynamic content of the desired HTML page. Django has the Django template language for its own template system. Create a directory named templates inside the newly created home apps directory. By convention, Django’s template engine looks for a β€˜templates’ subdirectory in each of the INSTALLED_APPS. mkdir home/templates Inside the templates dir, create a file named index.html with the following content. <!DOCTYPE html> <html lang="en"> <head> <title>Home Page</title> </head> <body> <h1>Home Page</h1> <p>This page is rendered as a Django Template</p> <h3>Happy Learning :)</h3> </body> </html> Add the name of the newly created app home to the INSTALLED_APPS list in settings.py. # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home', ] Have a look at the TEMPLATES settings in the settings.py file, which contains the configurations for the templates engines and describes how Django will load and render templates. TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] BACKEND: Path to the default Django Template engine class. DIRS: List of directories where the engine should look for source files, in given search order. APP_DIRS: If True, the engine will look for templates inside installed applications. OPTIONS: contains backend-specific settings. We do not have to make any changes in these settings. As we have listed our app in the INSTALLED_APPS list, other things are taken care of by Django’s template engine. Next, create a view in home/views.py for the template. from django.shortcuts import render def index(request): return render(request, 'index.html') The index() method renders the HTML page. This is made possible using the render helper function from the django.shortcuts package. Here, the render() function takes the request object and the template_name as the arguments and returns an HttpResponse object with the rendered text. Create a file urls.py inside app directory home/ with the following content. from django.urls import path from . import views urlpatterns = [ path('', views.index), ] Next, create a URL pattern for this app in the URL patterns for our project, ie. in the file django_html/urls.py. from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('home.urls')), path('admin/', admin.site.urls), ] Now, run the application using python manage.py runserver Navigate to http://localhost:8000/ and you can see the HTML page create being rendered. Django Templates Documentation Django Template Language Django Shortcut functions Django Official Tutorial Happy Learning πŸ™‚ Python Django Helloworld Example AngularJs Directive Example Tutorials How to setup Python VirtualEnv How to Create own Spring Boot Error Page Java Static Variable Method Block Class Example Java Main Method – public static void main(String args[]) How to push docker image to docker hub ? Default Static methods in Interface Java 8 JQuery Events Example Tutorials Different ways to use Lambdas in Python Spring MVC Tiles Example (Apache Tiles) Java Swing JOptionPane Html Content Example Python Selenium Automate the Login Form Implementing Stack in Python Angularjs Custom Filter Example Python Django Helloworld Example AngularJs Directive Example Tutorials How to setup Python VirtualEnv How to Create own Spring Boot Error Page Java Static Variable Method Block Class Example Java Main Method – public static void main(String args[]) How to push docker image to docker hub ? Default Static methods in Interface Java 8 JQuery Events Example Tutorials Different ways to use Lambdas in Python Spring MVC Tiles Example (Apache Tiles) Java Swing JOptionPane Html Content Example Python Selenium Automate the Login Form Implementing Stack in Python Angularjs Custom Filter Example Ξ” Python – Introduction Python – Features Python – Install on Windows Python – Modes of Program Python – Number System Python – Identifiers Python – Operators Python – Ternary Operator Python – Command Line Arguments Python – Keywords Python – Data Types Python – Upgrade Python PIP Python – Virtual Environment Pyhton – Type Casting Python – String to Int Python – Conditional Statements Python – if statement Python – *args and **kwargs Python – Date Formatting Python – Read input from keyboard Python – raw_input Python – List In Depth Python – List Comprehension Python – Set in Depth Python – Dictionary in Depth Python – Tuple in Depth Python – Stack Datastructure Python – Classes and Objects Python – Constructors Python – Object Introspection Python – Inheritance Python – Decorators Python – Serialization with Pickle Python – Exceptions Handling Python – User defined Exceptions Python – Multiprocessing Python – Default function parameters Python – Lambdas Functions Python – NumPy Library Python – MySQL Connector Python – MySQL Create Database Python – MySQL Read Data Python – MySQL Insert Data Python – MySQL Update Records Python – MySQL Delete Records Python – String Case Conversion Howto – Find biggest of 2 numbers Howto – Remove duplicates from List Howto – Convert any Number to Binary Howto – Merge two Lists Howto – Merge two dicts Howto – Get Characters Count in a File Howto – Get Words Count in a File Howto – Remove Spaces from String Howto – Read Env variables Howto – Read a text File Howto – Read a JSON File Howto – Read Config.ini files Howto – Iterate Dictionary Howto – Convert List Of Objects to CSV Howto – Merge two dict in Python Howto – create Zip File Howto – Get OS info Howto – Get size of Directory Howto – Check whether a file exists Howto – Remove key from dictionary Howto – Sort Objects Howto – Create or Delete Directories Howto – Read CSV File Howto – Create Python Iterable class Howto – Access for loop index Howto – Clear all elements from List Howto – Remove empty lists from a List Howto – Remove special characters from String Howto – Sort dictionary by key Howto – Filter a list
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 487, "s": 398, "text": "In this tutorial, we will learn how to render static HTML pages in a Django application." }, { "code": null, "e": 503, "s": 487, "text": "Python 3.7, 3.8" }, { "code": null, "e": 514, "s": 503, "text": "Django 3.1" }, { "code": null, "e": 521, "s": 514, "text": "HTML 5" }, { "code": null, "e": 684, "s": 521, "text": "The first step of beginning any python project is creating a virtual environment. Follow this tutorial to set up and activate a virtualenvand then install Django." }, { "code": null, "e": 742, "s": 684, "text": "virtualenv env\nsource env/bin/activate\npip install Django" }, { "code": null, "e": 866, "s": 742, "text": "Start a Django project (here, project name:django_html) and create an app named home. Check this tutorial for more details." }, { "code": null, "e": 951, "s": 866, "text": "django-admin startproject django_html\ncd django_html/\npython manage.py startapp home" }, { "code": null, "e": 1196, "s": 951, "text": "Django uses templates to generate HTML dynamically. A template contains the static part as well some static syntax for displaying the dynamic content of the desired HTML page. Django has the Django template language for its own template system." }, { "code": null, "e": 1277, "s": 1196, "text": "Create a directory named templates inside the newly created home apps directory." }, { "code": null, "e": 1385, "s": 1277, "text": "By convention, Django’s template engine looks for a β€˜templates’ subdirectory in each of the INSTALLED_APPS." }, { "code": null, "e": 1406, "s": 1385, "text": "mkdir home/templates" }, { "code": null, "e": 1491, "s": 1406, "text": "Inside the templates dir, create a file named index.html with the following content." }, { "code": null, "e": 1699, "s": 1491, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <title>Home Page</title>\n</head>\n<body>\n <h1>Home Page</h1>\n <p>This page is rendered as a Django Template</p>\n <h3>Happy Learning :)</h3>\n</body>\n</html>" }, { "code": null, "e": 1785, "s": 1699, "text": "Add the name of the newly created app home to the INSTALLED_APPS list in settings.py." }, { "code": null, "e": 2030, "s": 1785, "text": "# Application definition\n\nINSTALLED_APPS = [\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'home',\n]" }, { "code": null, "e": 2210, "s": 2030, "text": "Have a look at the TEMPLATES settings in the settings.py file, which contains the configurations for the templates engines and describes how Django will load and render templates." }, { "code": null, "e": 2694, "s": 2210, "text": "TEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [],\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n ],\n },\n },\n]" }, { "code": null, "e": 2753, "s": 2694, "text": "BACKEND: Path to the default Django Template engine class." }, { "code": null, "e": 2849, "s": 2753, "text": "DIRS: List of directories where the engine should look for source files, in given search order." }, { "code": null, "e": 2934, "s": 2849, "text": "APP_DIRS: If True, the engine will look for templates inside installed applications." }, { "code": null, "e": 2979, "s": 2934, "text": "OPTIONS: contains backend-specific settings." }, { "code": null, "e": 3147, "s": 2979, "text": "We do not have to make any changes in these settings. As we have listed our app in the INSTALLED_APPS list, other things are taken care of by Django’s template engine." }, { "code": null, "e": 3202, "s": 3147, "text": "Next, create a view in home/views.py for the template." }, { "code": null, "e": 3300, "s": 3202, "text": "from django.shortcuts import render\n\ndef index(request):\n return render(request, 'index.html')" }, { "code": null, "e": 3432, "s": 3300, "text": "The index() method renders the HTML page. This is made possible using the render helper function from the django.shortcuts package." }, { "code": null, "e": 3583, "s": 3432, "text": "Here, the render() function takes the request object and the template_name as the arguments and returns an HttpResponse object with the rendered text." }, { "code": null, "e": 3660, "s": 3583, "text": "Create a file urls.py inside app directory home/ with the following content." }, { "code": null, "e": 3754, "s": 3660, "text": "from django.urls import path\nfrom . import views\nurlpatterns = [\n path('', views.index),\n]" }, { "code": null, "e": 3868, "s": 3754, "text": "Next, create a URL pattern for this app in the URL patterns for our project, ie. in the file django_html/urls.py." }, { "code": null, "e": 4032, "s": 3868, "text": "from django.contrib import admin\nfrom django.urls import path, include\n\nurlpatterns = [\n path('', include('home.urls')),\n path('admin/', admin.site.urls),\n]\n" }, { "code": null, "e": 4063, "s": 4032, "text": "Now, run the application using" }, { "code": null, "e": 4090, "s": 4063, "text": "python manage.py runserver" }, { "code": null, "e": 4178, "s": 4090, "text": "Navigate to http://localhost:8000/ and you can see the HTML page create being rendered." }, { "code": null, "e": 4209, "s": 4178, "text": "Django Templates Documentation" }, { "code": null, "e": 4234, "s": 4209, "text": "Django Template Language" }, { "code": null, "e": 4260, "s": 4234, "text": "Django Shortcut functions" }, { "code": null, "e": 4285, "s": 4260, "text": "Django Official Tutorial" }, { "code": null, "e": 4302, "s": 4285, "text": "Happy Learning πŸ™‚" }, { "code": null, "e": 4894, "s": 4302, "text": "\nPython Django Helloworld Example\nAngularJs Directive Example Tutorials\nHow to setup Python VirtualEnv\nHow to Create own Spring Boot Error Page\nJava Static Variable Method Block Class Example\nJava Main Method – public static void main(String args[])\nHow to push docker image to docker hub ?\nDefault Static methods in Interface Java 8\nJQuery Events Example Tutorials\nDifferent ways to use Lambdas in Python\nSpring MVC Tiles Example (Apache Tiles)\nJava Swing JOptionPane Html Content Example\nPython Selenium Automate the Login Form\nImplementing Stack in Python\nAngularjs Custom Filter Example\n" }, { "code": null, "e": 4927, "s": 4894, "text": "Python Django Helloworld Example" }, { "code": null, "e": 4965, "s": 4927, "text": "AngularJs Directive Example Tutorials" }, { "code": null, "e": 4996, "s": 4965, "text": "How to setup Python VirtualEnv" }, { "code": null, "e": 5037, "s": 4996, "text": "How to Create own Spring Boot Error Page" }, { "code": null, "e": 5085, "s": 5037, "text": "Java Static Variable Method Block Class Example" }, { "code": null, "e": 5143, "s": 5085, "text": "Java Main Method – public static void main(String args[])" }, { "code": null, "e": 5184, "s": 5143, "text": "How to push docker image to docker hub ?" }, { "code": null, "e": 5227, "s": 5184, "text": "Default Static methods in Interface Java 8" }, { "code": null, "e": 5259, "s": 5227, "text": "JQuery Events Example Tutorials" }, { "code": null, "e": 5299, "s": 5259, "text": "Different ways to use Lambdas in Python" }, { "code": null, "e": 5339, "s": 5299, "text": "Spring MVC Tiles Example (Apache Tiles)" }, { "code": null, "e": 5383, "s": 5339, "text": "Java Swing JOptionPane Html Content Example" }, { "code": null, "e": 5423, "s": 5383, "text": "Python Selenium Automate the Login Form" }, { "code": null, "e": 5452, "s": 5423, "text": "Implementing Stack in Python" }, { "code": null, "e": 5484, "s": 5452, "text": "Angularjs Custom Filter Example" }, { "code": null, "e": 5490, "s": 5488, "text": "Ξ”" }, { "code": null, "e": 5513, "s": 5490, "text": " Python – Introduction" }, { "code": null, "e": 5532, "s": 5513, "text": " Python – Features" }, { "code": null, "e": 5561, "s": 5532, "text": " Python – Install on Windows" }, { "code": null, "e": 5588, "s": 5561, "text": " Python – Modes of Program" }, { "code": null, "e": 5612, "s": 5588, "text": " Python – Number System" }, { "code": null, "e": 5634, "s": 5612, "text": " Python – Identifiers" }, { "code": null, "e": 5654, "s": 5634, "text": " Python – Operators" }, { "code": null, "e": 5681, "s": 5654, "text": " Python – Ternary Operator" }, { "code": null, "e": 5714, "s": 5681, "text": " Python – Command Line Arguments" }, { "code": null, "e": 5733, "s": 5714, "text": " Python – Keywords" }, { "code": null, "e": 5754, "s": 5733, "text": " Python – Data Types" }, { "code": null, "e": 5783, "s": 5754, "text": " Python – Upgrade Python PIP" }, { "code": null, "e": 5813, "s": 5783, "text": " Python – Virtual Environment" }, { "code": null, "e": 5836, "s": 5813, "text": " Pyhton – Type Casting" }, { "code": null, "e": 5860, "s": 5836, "text": " Python – String to Int" }, { "code": null, "e": 5893, "s": 5860, "text": " Python – Conditional Statements" }, { "code": null, "e": 5916, "s": 5893, "text": " Python – if statement" }, { "code": null, "e": 5945, "s": 5916, "text": " Python – *args and **kwargs" }, { "code": null, "e": 5971, "s": 5945, "text": " Python – Date Formatting" }, { "code": null, "e": 6006, "s": 5971, "text": " Python – Read input from keyboard" }, { "code": null, "e": 6026, "s": 6006, "text": " Python – raw_input" }, { "code": null, "e": 6050, "s": 6026, "text": " Python – List In Depth" }, { "code": null, "e": 6079, "s": 6050, "text": " Python – List Comprehension" }, { "code": null, "e": 6102, "s": 6079, "text": " Python – Set in Depth" }, { "code": null, "e": 6132, "s": 6102, "text": " Python – Dictionary in Depth" }, { "code": null, "e": 6157, "s": 6132, "text": " Python – Tuple in Depth" }, { "code": null, "e": 6187, "s": 6157, "text": " Python – Stack Datastructure" }, { "code": null, "e": 6217, "s": 6187, "text": " Python – Classes and Objects" }, { "code": null, "e": 6240, "s": 6217, "text": " Python – Constructors" }, { "code": null, "e": 6271, "s": 6240, "text": " Python – Object Introspection" }, { "code": null, "e": 6293, "s": 6271, "text": " Python – Inheritance" }, { "code": null, "e": 6314, "s": 6293, "text": " Python – Decorators" }, { "code": null, "e": 6350, "s": 6314, "text": " Python – Serialization with Pickle" }, { "code": null, "e": 6380, "s": 6350, "text": " Python – Exceptions Handling" }, { "code": null, "e": 6414, "s": 6380, "text": " Python – User defined Exceptions" }, { "code": null, "e": 6440, "s": 6414, "text": " Python – Multiprocessing" }, { "code": null, "e": 6478, "s": 6440, "text": " Python – Default function parameters" }, { "code": null, "e": 6506, "s": 6478, "text": " Python – Lambdas Functions" }, { "code": null, "e": 6530, "s": 6506, "text": " Python – NumPy Library" }, { "code": null, "e": 6556, "s": 6530, "text": " Python – MySQL Connector" }, { "code": null, "e": 6588, "s": 6556, "text": " Python – MySQL Create Database" }, { "code": null, "e": 6614, "s": 6588, "text": " Python – MySQL Read Data" }, { "code": null, "e": 6642, "s": 6614, "text": " Python – MySQL Insert Data" }, { "code": null, "e": 6673, "s": 6642, "text": " Python – MySQL Update Records" }, { "code": null, "e": 6704, "s": 6673, "text": " Python – MySQL Delete Records" }, { "code": null, "e": 6737, "s": 6704, "text": " Python – String Case Conversion" }, { "code": null, "e": 6772, "s": 6737, "text": " Howto – Find biggest of 2 numbers" }, { "code": null, "e": 6809, "s": 6772, "text": " Howto – Remove duplicates from List" }, { "code": null, "e": 6847, "s": 6809, "text": " Howto – Convert any Number to Binary" }, { "code": null, "e": 6873, "s": 6847, "text": " Howto – Merge two Lists" }, { "code": null, "e": 6898, "s": 6873, "text": " Howto – Merge two dicts" }, { "code": null, "e": 6938, "s": 6898, "text": " Howto – Get Characters Count in a File" }, { "code": null, "e": 6973, "s": 6938, "text": " Howto – Get Words Count in a File" }, { "code": null, "e": 7008, "s": 6973, "text": " Howto – Remove Spaces from String" }, { "code": null, "e": 7037, "s": 7008, "text": " Howto – Read Env variables" }, { "code": null, "e": 7063, "s": 7037, "text": " Howto – Read a text File" }, { "code": null, "e": 7089, "s": 7063, "text": " Howto – Read a JSON File" }, { "code": null, "e": 7121, "s": 7089, "text": " Howto – Read Config.ini files" }, { "code": null, "e": 7149, "s": 7121, "text": " Howto – Iterate Dictionary" }, { "code": null, "e": 7189, "s": 7149, "text": " Howto – Convert List Of Objects to CSV" }, { "code": null, "e": 7223, "s": 7189, "text": " Howto – Merge two dict in Python" }, { "code": null, "e": 7248, "s": 7223, "text": " Howto – create Zip File" }, { "code": null, "e": 7269, "s": 7248, "text": " Howto – Get OS info" }, { "code": null, "e": 7300, "s": 7269, "text": " Howto – Get size of Directory" }, { "code": null, "e": 7337, "s": 7300, "text": " Howto – Check whether a file exists" }, { "code": null, "e": 7374, "s": 7337, "text": " Howto – Remove key from dictionary" }, { "code": null, "e": 7396, "s": 7374, "text": " Howto – Sort Objects" }, { "code": null, "e": 7434, "s": 7396, "text": " Howto – Create or Delete Directories" }, { "code": null, "e": 7457, "s": 7434, "text": " Howto – Read CSV File" }, { "code": null, "e": 7495, "s": 7457, "text": " Howto – Create Python Iterable class" }, { "code": null, "e": 7526, "s": 7495, "text": " Howto – Access for loop index" }, { "code": null, "e": 7564, "s": 7526, "text": " Howto – Clear all elements from List" }, { "code": null, "e": 7604, "s": 7564, "text": " Howto – Remove empty lists from a List" }, { "code": null, "e": 7651, "s": 7604, "text": " Howto – Remove special characters from String" }, { "code": null, "e": 7683, "s": 7651, "text": " Howto – Sort dictionary by key" } ]
C Program to find whether a no is power of two - GeeksforGeeks
19 Jul, 2021 Given a positive integer, write a function to find if it is a power of two or not.Examples : Input : n = 4 Output : Yes 22 = 4 Input : n = 7 Output : No Input : n = 32 Output : Yes 25 = 32 1. A simple method for this is to simply take the log of the number on base 2 and if you get an integer then number is power of 2. C // C Program to find whether a// no is power of two#include <math.h>#include <stdbool.h>#include <stdio.h> /* Function to check if x is power of 2*/bool isPowerOfTwo(int n){ return (ceil(log2(n)) == floor(log2(n)));} // Driver programint main(){ isPowerOfTwo(31) ? printf("Yes\n") : printf("No\n"); isPowerOfTwo(64) ? printf("Yes\n") : printf("No\n"); return 0;} // This code is contributed by bibhudhendra No Yes Time Complexity: O(log2n) Auxiliary Space: O(1) 2. Another solution is to keep dividing the number by two, i.e, do n = n/2 iteratively. In any iteration, if n%2 becomes non-zero and n is not 1 then n is not a power of 2. If n becomes 1 then it is a power of 2. C #include <stdbool.h>#include <stdio.h> /* Function to check if x is power of 2*/bool isPowerOfTwo(int n){ if (n == 0) return 0; while (n != 1) { if (n % 2 != 0) return 0; n = n / 2; } return 1;} /*Driver program to test above function*/int main(){ isPowerOfTwo(31) ? printf("Yes\n") : printf("No\n"); isPowerOfTwo(64) ? printf("Yes\n") : printf("No\n"); return 0;} No Yes 3. All power of two numbers have only one bit set. So count the no. of set bits and if you get 1 then number is a power of 2. Please see Count set bits in an integer for counting set bits.4. If we subtract a power of 2 numbers by 1 then all unset bits after the only set bit become set; and the set bit become unset.For example for 4 ( 100) and 16(10000), we get following after subtracting 1 3 –> 011 15 –> 01111So, if a number n is a power of 2 then bitwise & of n and n-1 will be zero. We can say n is a power of 2 or not based on value of n&(n-1). The expression n&(n-1) will not work when n is 0. To handle this case also, our expression will become n& (!n&(n-1)) (thanks to https://www.geeksforgeeks.org/program-to-find-whether-a-no-is-power-of-two/Mohammad for adding this case). Below is the implementation of this method. C #include <stdio.h>#define bool int /* Function to check if x is power of 2*/bool isPowerOfTwo(int x){ /* First x in the below expression is for the case when x is 0 */ return x && (!(x & (x - 1)));} /*Driver program to test above function*/int main(){ isPowerOfTwo(31) ? printf("Yes\n") : printf("No\n"); isPowerOfTwo(64) ? printf("Yes\n") : printf("No\n"); return 0;} No Yes Please refer complete article on Program to find whether a no is power of two for more details! souravmahato348 C Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C Program to read contents of Whole File Regular expressions in C C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7 Producer Consumer Problem in C Handling multiple clients on server with multithreading using Socket Programming in C/C++ Lex program to implement a simple Calculator How to return a Pointer from a Function in C Implementing upper_bound() and lower_bound() in C Lamport's logical clock Conditional wait and signal in multi-threading
[ { "code": null, "e": 24539, "s": 24511, "text": "\n19 Jul, 2021" }, { "code": null, "e": 24634, "s": 24539, "text": "Given a positive integer, write a function to find if it is a power of two or not.Examples : " }, { "code": null, "e": 24732, "s": 24634, "text": "Input : n = 4\nOutput : Yes\n22 = 4\n\nInput : n = 7\nOutput : No\n\nInput : n = 32\nOutput : Yes\n25 = 32" }, { "code": null, "e": 24865, "s": 24732, "text": "1. A simple method for this is to simply take the log of the number on base 2 and if you get an integer then number is power of 2. " }, { "code": null, "e": 24867, "s": 24865, "text": "C" }, { "code": "// C Program to find whether a// no is power of two#include <math.h>#include <stdbool.h>#include <stdio.h> /* Function to check if x is power of 2*/bool isPowerOfTwo(int n){ return (ceil(log2(n)) == floor(log2(n)));} // Driver programint main(){ isPowerOfTwo(31) ? printf(\"Yes\\n\") : printf(\"No\\n\"); isPowerOfTwo(64) ? printf(\"Yes\\n\") : printf(\"No\\n\"); return 0;} // This code is contributed by bibhudhendra", "e": 25286, "s": 24867, "text": null }, { "code": null, "e": 25293, "s": 25286, "text": "No\nYes" }, { "code": null, "e": 25321, "s": 25295, "text": "Time Complexity: O(log2n)" }, { "code": null, "e": 25343, "s": 25321, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 25557, "s": 25343, "text": "2. Another solution is to keep dividing the number by two, i.e, do n = n/2 iteratively. In any iteration, if n%2 becomes non-zero and n is not 1 then n is not a power of 2. If n becomes 1 then it is a power of 2. " }, { "code": null, "e": 25559, "s": 25557, "text": "C" }, { "code": "#include <stdbool.h>#include <stdio.h> /* Function to check if x is power of 2*/bool isPowerOfTwo(int n){ if (n == 0) return 0; while (n != 1) { if (n % 2 != 0) return 0; n = n / 2; } return 1;} /*Driver program to test above function*/int main(){ isPowerOfTwo(31) ? printf(\"Yes\\n\") : printf(\"No\\n\"); isPowerOfTwo(64) ? printf(\"Yes\\n\") : printf(\"No\\n\"); return 0;}", "e": 25977, "s": 25559, "text": null }, { "code": null, "e": 25984, "s": 25977, "text": "No\nYes" }, { "code": null, "e": 26819, "s": 25986, "text": "3. All power of two numbers have only one bit set. So count the no. of set bits and if you get 1 then number is a power of 2. Please see Count set bits in an integer for counting set bits.4. If we subtract a power of 2 numbers by 1 then all unset bits after the only set bit become set; and the set bit become unset.For example for 4 ( 100) and 16(10000), we get following after subtracting 1 3 –> 011 15 –> 01111So, if a number n is a power of 2 then bitwise & of n and n-1 will be zero. We can say n is a power of 2 or not based on value of n&(n-1). The expression n&(n-1) will not work when n is 0. To handle this case also, our expression will become n& (!n&(n-1)) (thanks to https://www.geeksforgeeks.org/program-to-find-whether-a-no-is-power-of-two/Mohammad for adding this case). Below is the implementation of this method. " }, { "code": null, "e": 26821, "s": 26819, "text": "C" }, { "code": "#include <stdio.h>#define bool int /* Function to check if x is power of 2*/bool isPowerOfTwo(int x){ /* First x in the below expression is for the case when x is 0 */ return x && (!(x & (x - 1)));} /*Driver program to test above function*/int main(){ isPowerOfTwo(31) ? printf(\"Yes\\n\") : printf(\"No\\n\"); isPowerOfTwo(64) ? printf(\"Yes\\n\") : printf(\"No\\n\"); return 0;}", "e": 27205, "s": 26821, "text": null }, { "code": null, "e": 27212, "s": 27205, "text": "No\nYes" }, { "code": null, "e": 27311, "s": 27214, "text": "Please refer complete article on Program to find whether a no is power of two for more details! " }, { "code": null, "e": 27327, "s": 27311, "text": "souravmahato348" }, { "code": null, "e": 27338, "s": 27327, "text": "C Programs" }, { "code": null, "e": 27436, "s": 27338, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27445, "s": 27436, "text": "Comments" }, { "code": null, "e": 27458, "s": 27445, "text": "Old Comments" }, { "code": null, "e": 27499, "s": 27458, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 27524, "s": 27499, "text": "Regular expressions in C" }, { "code": null, "e": 27595, "s": 27524, "text": "C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 27626, "s": 27595, "text": "Producer Consumer Problem in C" }, { "code": null, "e": 27716, "s": 27626, "text": "Handling multiple clients on server with multithreading using Socket Programming in C/C++" }, { "code": null, "e": 27761, "s": 27716, "text": "Lex program to implement a simple Calculator" }, { "code": null, "e": 27806, "s": 27761, "text": "How to return a Pointer from a Function in C" }, { "code": null, "e": 27856, "s": 27806, "text": "Implementing upper_bound() and lower_bound() in C" }, { "code": null, "e": 27880, "s": 27856, "text": "Lamport's logical clock" } ]
explode() function in PHP
The explode() function is used to split a string by string. explode(delimiter, str, limit) delimiter βˆ’ The boundary string delimiter βˆ’ The boundary string str βˆ’ String to split str βˆ’ String to split limit βˆ’ Specifies the number of array elements to return. limit βˆ’ Specifies the number of array elements to return. The following are possible values βˆ’Greater than 0 - Returns an array with a maximum of limit element(s)Less than 0 - Returns an array except for the last -limit elements()0 - Returns an array with one element The following are possible values βˆ’ Greater than 0 - Returns an array with a maximum of limit element(s) Greater than 0 - Returns an array with a maximum of limit element(s) Less than 0 - Returns an array except for the last -limit elements() Less than 0 - Returns an array except for the last -limit elements() 0 - Returns an array with one element 0 - Returns an array with one element The explode() function returns an array of strings. The following is an example βˆ’ Live Demo <?php $s = "This is demo text!"; print_r (explode(" ",$s)); ?> The following is the output βˆ’ Array ( [0] => This [1] => is [2] => demo [3] => text! ) Let us see another example βˆ’ Live Demo <?php $str = 'car,bus,motorbike,cycle'; print_r(explode(',',$str,0)); print "<br>"; ?> The following is the output βˆ’ Array ( [0] => car,bus,motorbike,cycle ) Let us see another example βˆ’ Live Demo <?php $str = 'car,bus,motorbike,cycle'; print_r(explode(',',$str,2)); ?> The following is the output βˆ’ Array ( [0] => car [1] => bus,motorbike,cycle ) Let us see another example βˆ’ Live Demo <?php $str = 'car,bus,motorbike,cycle'; print_r(explode(',',$str,-1)); ?> The following is the output βˆ’ Array ( [0] => car [1] => bus [2] => motorbike )
[ { "code": null, "e": 1122, "s": 1062, "text": "The explode() function is used to split a string by string." }, { "code": null, "e": 1153, "s": 1122, "text": "explode(delimiter, str, limit)" }, { "code": null, "e": 1185, "s": 1153, "text": "delimiter βˆ’ The boundary string" }, { "code": null, "e": 1217, "s": 1185, "text": "delimiter βˆ’ The boundary string" }, { "code": null, "e": 1239, "s": 1217, "text": "str βˆ’ String to split" }, { "code": null, "e": 1261, "s": 1239, "text": "str βˆ’ String to split" }, { "code": null, "e": 1319, "s": 1261, "text": "limit βˆ’ Specifies the number of array elements to return." }, { "code": null, "e": 1377, "s": 1319, "text": "limit βˆ’ Specifies the number of array elements to return." }, { "code": null, "e": 1586, "s": 1377, "text": "The following are possible values βˆ’Greater than 0 - Returns an array with a maximum of limit element(s)Less than 0 - Returns an array except for the last -limit elements()0 - Returns an array with one element" }, { "code": null, "e": 1622, "s": 1586, "text": "The following are possible values βˆ’" }, { "code": null, "e": 1691, "s": 1622, "text": "Greater than 0 - Returns an array with a maximum of limit element(s)" }, { "code": null, "e": 1760, "s": 1691, "text": "Greater than 0 - Returns an array with a maximum of limit element(s)" }, { "code": null, "e": 1829, "s": 1760, "text": "Less than 0 - Returns an array except for the last -limit elements()" }, { "code": null, "e": 1898, "s": 1829, "text": "Less than 0 - Returns an array except for the last -limit elements()" }, { "code": null, "e": 1936, "s": 1898, "text": "0 - Returns an array with one element" }, { "code": null, "e": 1974, "s": 1936, "text": "0 - Returns an array with one element" }, { "code": null, "e": 2026, "s": 1974, "text": "The explode() function returns an array of strings." }, { "code": null, "e": 2056, "s": 2026, "text": "The following is an example βˆ’" }, { "code": null, "e": 2067, "s": 2056, "text": " Live Demo" }, { "code": null, "e": 2130, "s": 2067, "text": "<?php\n$s = \"This is demo text!\";\nprint_r (explode(\" \",$s));\n?>" }, { "code": null, "e": 2160, "s": 2130, "text": "The following is the output βˆ’" }, { "code": null, "e": 2229, "s": 2160, "text": "Array\n(\n [0] => This\n [1] => is\n [2] => demo\n [3] => text!\n)" }, { "code": null, "e": 2258, "s": 2229, "text": "Let us see another example βˆ’" }, { "code": null, "e": 2269, "s": 2258, "text": " Live Demo" }, { "code": null, "e": 2356, "s": 2269, "text": "<?php\n$str = 'car,bus,motorbike,cycle';\nprint_r(explode(',',$str,0));\nprint \"<br>\";\n?>" }, { "code": null, "e": 2386, "s": 2356, "text": "The following is the output βˆ’" }, { "code": null, "e": 2430, "s": 2386, "text": "Array\n(\n [0] => car,bus,motorbike,cycle\n)" }, { "code": null, "e": 2459, "s": 2430, "text": "Let us see another example βˆ’" }, { "code": null, "e": 2470, "s": 2459, "text": " Live Demo" }, { "code": null, "e": 2543, "s": 2470, "text": "<?php\n$str = 'car,bus,motorbike,cycle';\nprint_r(explode(',',$str,2));\n?>" }, { "code": null, "e": 2573, "s": 2543, "text": "The following is the output βˆ’" }, { "code": null, "e": 2627, "s": 2573, "text": "Array\n(\n [0] => car\n [1] => bus,motorbike,cycle\n)" }, { "code": null, "e": 2656, "s": 2627, "text": "Let us see another example βˆ’" }, { "code": null, "e": 2667, "s": 2656, "text": " Live Demo" }, { "code": null, "e": 2741, "s": 2667, "text": "<?php\n$str = 'car,bus,motorbike,cycle';\nprint_r(explode(',',$str,-1));\n?>" }, { "code": null, "e": 2771, "s": 2741, "text": "The following is the output βˆ’" }, { "code": null, "e": 2829, "s": 2771, "text": "Array\n(\n [0] => car\n [1] => bus\n [2] => motorbike\n)" } ]
Absolute distinct count in a sorted array - GeeksforGeeks
02 Mar, 2022 Given a sorted array of integers, return the number of distinct absolute values among the elements of the array. The input can contain duplicates values. Examples: Input: [-3, -2, 0, 3, 4, 5] Output: 5 There are 5 distinct absolute values among the elements of this array, i.e. 0, 2, 3, 4 and 5) Input: [-1, -1, -1, -1, 0, 1, 1, 1, 1] Output: 2 Input: [-1, -1, -1, -1, 0] Output: 2 Input: [0, 0, 0] Output: 1 The solution should do only one scan of the input array and should not use any extra space. i.e. expected time complexity is O(n) and auxiliary space is O(1). One simple solution is to use set. For each element of the input array, we insert its absolute value in the set. As set doesn’t support duplicate elements, the element’s absolute value will be inserted only once. Therefore, the required count is size of the set.Below is the implementation of the idea. C++ Java Python3 C# Javascript // C++ program to find absolute distinct// count of an array in O(n) time.#include <bits/stdc++.h>using namespace std; // The function returns number of// distinct absolute values among// the elements of the arrayint distinctCount(int arr[], int n){ unordered_set<int> s; // Note that set keeps only one // copy even if we try to insert // multiple values for (int i = 0 ; i < n; i++) s.insert(abs(arr[i])); return s.size();} // Driver codeint main(){ int arr[] = {-2, -1, 0, 1, 1}; int n = sizeof(arr)/sizeof(arr[0]); cout << "Count of absolute distinct values : " << distinctCount(arr, n); return 0;} // java code to find absolute distinct// count of an array in O(n) time.import java.util.*; class GFG{ // The function returns number of // distinct absolute values among // the elements of the array static int distinctCount(int arr[], int n) { Set<Integer> s = new HashSet<Integer> (); // Note that set keeps only one // copy even if we try to insert // multiple values for (int i = 0 ; i < n; i++) s.add(Math.abs(arr[i])); return s.size(); } // Driver code public static void main(String[] args) { int arr[] = {-2, -1, 0, 1, 1}; int n = arr.length; System.out.println("Count of absolute distinct values : " + distinctCount(arr, n)); }} // This code is contributed by prerna saini # Python3 code to find absolute distinct# count of an array in O(n) time. # This function returns number of# distinct absolute values among# the elements of the arraydef distinctCount(arr, n): s = set() # set keeps all unique elements for i in range(n): s.add(abs(arr[i])) return len(s) # Driver Codearr = [-2, -1, 0, 1, 1]n = len(arr)print("Count of absolute distinct values:", distinctCount(arr, n)) # This code is contributed# by Adarsh_Verma // C# code to find absolute distinct// count of an array in O(n) time.using System;using System.Collections.Generic; class GFG{ // The function returns number of // distinct absolute values among // the elements of the array static int distinctCount(int []arr, int n) { HashSet<int> s = new HashSet<int>(); // Note that set keeps only one // copy even if we try to insert // multiple values for (int i = 0 ; i < n; i++) s.Add(Math.Abs(arr[i])); return s.Count; } // Driver code public static void Main() { int []arr = {-2, -1, 0, 1, 1}; int n = arr.Length; Console.Write("Count of absolute distinct values : " + distinctCount(arr, n)); }} // This code is contributed by PrinciRaj1992 <script> // Javascript code to find absolute distinct // count of an array in O(n) time. // The function returns number of // distinct absolute values among // the elements of the array function distinctCount(arr, n) { let s = new Set(); // Note that set keeps only one // copy even if we try to insert // multiple values for (let i = 0 ; i < n; i++) s.add(Math.abs(arr[i])); return s.size; } let arr = [-2, -1, 0, 1, 1]; let n = arr.length; document.write("Count of absolute distinct values : " + distinctCount(arr, n)); </script> Output : Count of absolute distinct values : 3 Time Complexity : O(n) Auxiliary Space : O(n)The above implementation takes O(n) extra space, how to do in O(1) extra space? The idea is to take advantage of the fact that the array is already Sorted. We initialize the count of distinct elements to number of elements in the array. We start with two index variables from two corners of the array and check for pair in the input array with sum as 0. If pair with 0 sum is found or duplicates are encountered, we decrement the count of distinct elements.Finally we return the updated count.Below is the implementation of above approach. C++ Java Python3 C# PHP Javascript // C++ program to find absolute distinct// count of an array using O(1) space.#include <bits/stdc++.h>using namespace std; // The function returns return number// of distinct absolute values// among the elements of the arrayint distinctCount(int arr[], int n){ // initialize count as number of elements int count = n; int i = 0, j = n - 1, sum = 0; while (i < j) { // Remove duplicate elements from the // left of the current window (i, j) // and also decrease the count while (i != j && arr[i] == arr[i + 1]) count--, i++; // Remove duplicate elements from the // right of the current window (i, j) // and also decrease the count while (i != j && arr[j] == arr[j - 1]) count--, j--; // break if only one element is left if (i == j) break; // Now look for the zero sum pair // in current window (i, j) sum = arr[i] + arr[j]; if (sum == 0) { // decrease the count if (positive, // negative) pair is encountered count--; i++, j--; } else if(sum < 0) i++; else j--; } return count;} // Driver codeint main(){ int arr[] = {-2, -1, 0, 1, 1}; int n = sizeof(arr)/sizeof(arr[0]); cout << "Count of absolute distinct values : " << distinctCount(arr, n); return 0;} // Java program to find absolute distinct// count of an array using O(1) space. import java.io.*; class GFG { // The function returns return number// of distinct absolute values// among the elements of the arraystatic int distinctCount(int arr[], int n){ // initialize count as number of elements int count = n; int i = 0, j = n - 1, sum = 0; while (i < j) { // Remove duplicate elements from the // left of the current window (i, j) // and also decrease the count while (i != j && arr[i] == arr[i + 1]) { count--; i++; } // Remove duplicate elements from the // right of the current window (i, j) // and also decrease the count while (i != j && arr[j] == arr[j - 1]) { count--; j--; } // break if only one element is left if (i == j) break; // Now look for the zero sum pair // in current window (i, j) sum = arr[i] + arr[j]; if (sum == 0) { // decrease the count if (positive, // negative) pair is encountered count--; i++; j--; } else if(sum < 0) i++; else j--; } return count;} // Driver code public static void main (String[] args) { int arr[] = {-2, -1, 0, 1, 1}; int n = arr.length; System.out.println ("Count of absolute distinct values : "+ distinctCount(arr, n)); }} # Python3 program to find absolute distinct# count of an array using O(1) space. # The function returns return number# of distinct absolute values# among the elements of the arraydef distinctCount(arr, n): # initialize count as number of elements count = n; i = 0; j = n - 1; sum = 0; while (i < j): # Remove duplicate elements from the # left of the current window (i, j) # and also decrease the count while (i != j and arr[i] == arr[i + 1]): count = count - 1; i = i + 1; # Remove duplicate elements from the # right of the current window (i, j) # and also decrease the count while (i != j and arr[j] == arr[j - 1]): count = count - 1; j = j - 1; # break if only one element is left if (i == j): break; # Now look for the zero sum pair # in current window (i, j) sum = arr[i] + arr[j]; if (sum == 0): # decrease the count if (positive, # negative) pair is encountered count = count - 1; i = i + 1; j = j - 1; else if(sum < 0): i = i + 1; else: j = j - 1; return count; # Driver codearr = [-2, -1, 0, 1, 1];n = len(arr); print("Count of absolute distinct values : ", distinctCount(arr, n)); # This code is contributed# by Akanksha Rai //C# program to find absolute distinct// count of an array using O(1) space.using System; class GFG { // The function returns return number// of distinct absolute values// among the elements of the arraystatic int distinctCount(int []arr, int n){ // initialize count as number of elements int count = n; int i = 0, j = n - 1, sum = 0; while (i < j) { // Remove duplicate elements from the // left of the current window (i, j) // and also decrease the count while (i != j && arr[i] == arr[i + 1]) { count--; i++; } // Remove duplicate elements from the // right of the current window (i, j) // and also decrease the count while (i != j && arr[j] == arr[j - 1]) { count--; j--; } // break if only one element is left if (i == j) break; // Now look for the zero sum pair // in current window (i, j) sum = arr[i] + arr[j]; if (sum == 0) { // decrease the count if (positive, // negative) pair is encountered count--; i++; j--; } else if(sum < 0) i++; else j--; } return count;} // Driver code public static void Main () { int []arr = {-2, -1, 0, 1, 1}; int n = arr.Length; Console.WriteLine("Count of absolute distinct values : "+ distinctCount(arr, n)); // This code is contributed by inder_verma }} <?php// PHP program to find absolute distinct// count of an array using O(1) space. // The function returns return number// of distinct absolute values// among the elements of the arrayfunction distinctCount($arr, $n){ // initialize count as number // of elements $count = $n; $i = 0; $j = $n - 1; $sum = 0; while ($i < $j) { // Remove duplicate elements from the // left of the current window (i, j) // and also decrease the count while ($i != $j && $arr[$i] == $arr[$i + 1]) {$count--; $i++;} // Remove duplicate elements from the // right of the current window (i, j) // and also decrease the count while ($i != $j && $arr[$j] == $arr[$j - 1]) {$count--; $j--;} // break if only one element is left if ($i == $j) break; // Now look for the zero sum pair // in current window (i, j) $sum = $arr[$i] + $arr[$j]; if ($sum == 0) { // decrease the count if (positive, // negative) pair is encountered $count--; $i++; $j--; } else if($sum < 0) $i++; else $j--; } return $count;} // Driver code$arr = array(-2, -1, 0, 1, 1);$n = sizeof($arr); echo "Count of absolute distinct values : " . distinctCount($arr, $n); // This code is contributed// by Akanksha Rai?> <script> // Javascript program to find absolute distinct // count of an array using O(1) space. // The function returns return number // of distinct absolute values // among the elements of the array function distinctCount(arr, n) { // initialize count as number of elements let count = n; let i = 0, j = n - 1, sum = 0; while (i < j) { // Remove duplicate elements from the // left of the current window (i, j) // and also decrease the count while (i != j && arr[i] == arr[i + 1]) count--, i++; // Remove duplicate elements from the // right of the current window (i, j) // and also decrease the count while (i != j && arr[j] == arr[j - 1]) count--, j--; // break if only one element is left if (i == j) break; // Now look for the zero sum pair // in current window (i, j) sum = arr[i] + arr[j]; if (sum == 0) { // decrease the count if (positive, // negative) pair is encountered count--; i++, j--; } else if(sum < 0) i++; else j--; } return count; } let arr = [-2, -1, 0, 1, 1]; let n = arr.length; document.write( "Count of absolute distinct values : " + distinctCount(arr, n)); </script> Output : Count of absolute distinct values : 3 Time Complexity: O(n) Auxiliary Space: O(1)This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above jit_t inderDuMCA princiraj1992 Adarsh_Verma Akanksha_Rai divyesh072019 mukesh07 surinderdawra388 Arrays Sorting Arrays Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Introduction to Arrays Multidimensional Arrays in Java
[ { "code": null, "e": 25181, "s": 25153, "text": "\n02 Mar, 2022" }, { "code": null, "e": 25347, "s": 25181, "text": "Given a sorted array of integers, return the number of distinct absolute values among the elements of the array. The input can contain duplicates values. Examples: " }, { "code": null, "e": 25599, "s": 25347, "text": "Input: [-3, -2, 0, 3, 4, 5]\nOutput: 5\nThere are 5 distinct absolute values\namong the elements of this array, i.e.\n0, 2, 3, 4 and 5)\n\nInput: [-1, -1, -1, -1, 0, 1, 1, 1, 1]\nOutput: 2\n\nInput: [-1, -1, -1, -1, 0]\nOutput: 2\n\nInput: [0, 0, 0]\nOutput: 1 " }, { "code": null, "e": 25759, "s": 25599, "text": "The solution should do only one scan of the input array and should not use any extra space. i.e. expected time complexity is O(n) and auxiliary space is O(1). " }, { "code": null, "e": 26064, "s": 25759, "text": "One simple solution is to use set. For each element of the input array, we insert its absolute value in the set. As set doesn’t support duplicate elements, the element’s absolute value will be inserted only once. Therefore, the required count is size of the set.Below is the implementation of the idea. " }, { "code": null, "e": 26068, "s": 26064, "text": "C++" }, { "code": null, "e": 26073, "s": 26068, "text": "Java" }, { "code": null, "e": 26081, "s": 26073, "text": "Python3" }, { "code": null, "e": 26084, "s": 26081, "text": "C#" }, { "code": null, "e": 26095, "s": 26084, "text": "Javascript" }, { "code": "// C++ program to find absolute distinct// count of an array in O(n) time.#include <bits/stdc++.h>using namespace std; // The function returns number of// distinct absolute values among// the elements of the arrayint distinctCount(int arr[], int n){ unordered_set<int> s; // Note that set keeps only one // copy even if we try to insert // multiple values for (int i = 0 ; i < n; i++) s.insert(abs(arr[i])); return s.size();} // Driver codeint main(){ int arr[] = {-2, -1, 0, 1, 1}; int n = sizeof(arr)/sizeof(arr[0]); cout << \"Count of absolute distinct values : \" << distinctCount(arr, n); return 0;}", "e": 26747, "s": 26095, "text": null }, { "code": "// java code to find absolute distinct// count of an array in O(n) time.import java.util.*; class GFG{ // The function returns number of // distinct absolute values among // the elements of the array static int distinctCount(int arr[], int n) { Set<Integer> s = new HashSet<Integer> (); // Note that set keeps only one // copy even if we try to insert // multiple values for (int i = 0 ; i < n; i++) s.add(Math.abs(arr[i])); return s.size(); } // Driver code public static void main(String[] args) { int arr[] = {-2, -1, 0, 1, 1}; int n = arr.length; System.out.println(\"Count of absolute distinct values : \" + distinctCount(arr, n)); }} // This code is contributed by prerna saini", "e": 27589, "s": 26747, "text": null }, { "code": "# Python3 code to find absolute distinct# count of an array in O(n) time. # This function returns number of# distinct absolute values among# the elements of the arraydef distinctCount(arr, n): s = set() # set keeps all unique elements for i in range(n): s.add(abs(arr[i])) return len(s) # Driver Codearr = [-2, -1, 0, 1, 1]n = len(arr)print(\"Count of absolute distinct values:\", distinctCount(arr, n)) # This code is contributed# by Adarsh_Verma", "e": 28079, "s": 27589, "text": null }, { "code": " // C# code to find absolute distinct// count of an array in O(n) time.using System;using System.Collections.Generic; class GFG{ // The function returns number of // distinct absolute values among // the elements of the array static int distinctCount(int []arr, int n) { HashSet<int> s = new HashSet<int>(); // Note that set keeps only one // copy even if we try to insert // multiple values for (int i = 0 ; i < n; i++) s.Add(Math.Abs(arr[i])); return s.Count; } // Driver code public static void Main() { int []arr = {-2, -1, 0, 1, 1}; int n = arr.Length; Console.Write(\"Count of absolute distinct values : \" + distinctCount(arr, n)); }} // This code is contributed by PrinciRaj1992", "e": 28925, "s": 28079, "text": null }, { "code": "<script> // Javascript code to find absolute distinct // count of an array in O(n) time. // The function returns number of // distinct absolute values among // the elements of the array function distinctCount(arr, n) { let s = new Set(); // Note that set keeps only one // copy even if we try to insert // multiple values for (let i = 0 ; i < n; i++) s.add(Math.abs(arr[i])); return s.size; } let arr = [-2, -1, 0, 1, 1]; let n = arr.length; document.write(\"Count of absolute distinct values : \" + distinctCount(arr, n)); </script>", "e": 29617, "s": 28925, "text": null }, { "code": null, "e": 29628, "s": 29617, "text": "Output : " }, { "code": null, "e": 29666, "s": 29628, "text": "Count of absolute distinct values : 3" }, { "code": null, "e": 30252, "s": 29666, "text": "Time Complexity : O(n) Auxiliary Space : O(n)The above implementation takes O(n) extra space, how to do in O(1) extra space? The idea is to take advantage of the fact that the array is already Sorted. We initialize the count of distinct elements to number of elements in the array. We start with two index variables from two corners of the array and check for pair in the input array with sum as 0. If pair with 0 sum is found or duplicates are encountered, we decrement the count of distinct elements.Finally we return the updated count.Below is the implementation of above approach. " }, { "code": null, "e": 30256, "s": 30252, "text": "C++" }, { "code": null, "e": 30261, "s": 30256, "text": "Java" }, { "code": null, "e": 30269, "s": 30261, "text": "Python3" }, { "code": null, "e": 30272, "s": 30269, "text": "C#" }, { "code": null, "e": 30276, "s": 30272, "text": "PHP" }, { "code": null, "e": 30287, "s": 30276, "text": "Javascript" }, { "code": "// C++ program to find absolute distinct// count of an array using O(1) space.#include <bits/stdc++.h>using namespace std; // The function returns return number// of distinct absolute values// among the elements of the arrayint distinctCount(int arr[], int n){ // initialize count as number of elements int count = n; int i = 0, j = n - 1, sum = 0; while (i < j) { // Remove duplicate elements from the // left of the current window (i, j) // and also decrease the count while (i != j && arr[i] == arr[i + 1]) count--, i++; // Remove duplicate elements from the // right of the current window (i, j) // and also decrease the count while (i != j && arr[j] == arr[j - 1]) count--, j--; // break if only one element is left if (i == j) break; // Now look for the zero sum pair // in current window (i, j) sum = arr[i] + arr[j]; if (sum == 0) { // decrease the count if (positive, // negative) pair is encountered count--; i++, j--; } else if(sum < 0) i++; else j--; } return count;} // Driver codeint main(){ int arr[] = {-2, -1, 0, 1, 1}; int n = sizeof(arr)/sizeof(arr[0]); cout << \"Count of absolute distinct values : \" << distinctCount(arr, n); return 0;}", "e": 31718, "s": 30287, "text": null }, { "code": "// Java program to find absolute distinct// count of an array using O(1) space. import java.io.*; class GFG { // The function returns return number// of distinct absolute values// among the elements of the arraystatic int distinctCount(int arr[], int n){ // initialize count as number of elements int count = n; int i = 0, j = n - 1, sum = 0; while (i < j) { // Remove duplicate elements from the // left of the current window (i, j) // and also decrease the count while (i != j && arr[i] == arr[i + 1]) { count--; i++; } // Remove duplicate elements from the // right of the current window (i, j) // and also decrease the count while (i != j && arr[j] == arr[j - 1]) { count--; j--; } // break if only one element is left if (i == j) break; // Now look for the zero sum pair // in current window (i, j) sum = arr[i] + arr[j]; if (sum == 0) { // decrease the count if (positive, // negative) pair is encountered count--; i++; j--; } else if(sum < 0) i++; else j--; } return count;} // Driver code public static void main (String[] args) { int arr[] = {-2, -1, 0, 1, 1}; int n = arr.length; System.out.println (\"Count of absolute distinct values : \"+ distinctCount(arr, n)); }}", "e": 33271, "s": 31718, "text": null }, { "code": "# Python3 program to find absolute distinct# count of an array using O(1) space. # The function returns return number# of distinct absolute values# among the elements of the arraydef distinctCount(arr, n): # initialize count as number of elements count = n; i = 0; j = n - 1; sum = 0; while (i < j): # Remove duplicate elements from the # left of the current window (i, j) # and also decrease the count while (i != j and arr[i] == arr[i + 1]): count = count - 1; i = i + 1; # Remove duplicate elements from the # right of the current window (i, j) # and also decrease the count while (i != j and arr[j] == arr[j - 1]): count = count - 1; j = j - 1; # break if only one element is left if (i == j): break; # Now look for the zero sum pair # in current window (i, j) sum = arr[i] + arr[j]; if (sum == 0): # decrease the count if (positive, # negative) pair is encountered count = count - 1; i = i + 1; j = j - 1; else if(sum < 0): i = i + 1; else: j = j - 1; return count; # Driver codearr = [-2, -1, 0, 1, 1];n = len(arr); print(\"Count of absolute distinct values : \", distinctCount(arr, n)); # This code is contributed# by Akanksha Rai", "e": 34730, "s": 33271, "text": null }, { "code": "//C# program to find absolute distinct// count of an array using O(1) space.using System; class GFG { // The function returns return number// of distinct absolute values// among the elements of the arraystatic int distinctCount(int []arr, int n){ // initialize count as number of elements int count = n; int i = 0, j = n - 1, sum = 0; while (i < j) { // Remove duplicate elements from the // left of the current window (i, j) // and also decrease the count while (i != j && arr[i] == arr[i + 1]) { count--; i++; } // Remove duplicate elements from the // right of the current window (i, j) // and also decrease the count while (i != j && arr[j] == arr[j - 1]) { count--; j--; } // break if only one element is left if (i == j) break; // Now look for the zero sum pair // in current window (i, j) sum = arr[i] + arr[j]; if (sum == 0) { // decrease the count if (positive, // negative) pair is encountered count--; i++; j--; } else if(sum < 0) i++; else j--; } return count;} // Driver code public static void Main () { int []arr = {-2, -1, 0, 1, 1}; int n = arr.Length; Console.WriteLine(\"Count of absolute distinct values : \"+ distinctCount(arr, n)); // This code is contributed by inder_verma }}", "e": 36299, "s": 34730, "text": null }, { "code": "<?php// PHP program to find absolute distinct// count of an array using O(1) space. // The function returns return number// of distinct absolute values// among the elements of the arrayfunction distinctCount($arr, $n){ // initialize count as number // of elements $count = $n; $i = 0; $j = $n - 1; $sum = 0; while ($i < $j) { // Remove duplicate elements from the // left of the current window (i, j) // and also decrease the count while ($i != $j && $arr[$i] == $arr[$i + 1]) {$count--; $i++;} // Remove duplicate elements from the // right of the current window (i, j) // and also decrease the count while ($i != $j && $arr[$j] == $arr[$j - 1]) {$count--; $j--;} // break if only one element is left if ($i == $j) break; // Now look for the zero sum pair // in current window (i, j) $sum = $arr[$i] + $arr[$j]; if ($sum == 0) { // decrease the count if (positive, // negative) pair is encountered $count--; $i++; $j--; } else if($sum < 0) $i++; else $j--; } return $count;} // Driver code$arr = array(-2, -1, 0, 1, 1);$n = sizeof($arr); echo \"Count of absolute distinct values : \" . distinctCount($arr, $n); // This code is contributed// by Akanksha Rai?>", "e": 37732, "s": 36299, "text": null }, { "code": "<script> // Javascript program to find absolute distinct // count of an array using O(1) space. // The function returns return number // of distinct absolute values // among the elements of the array function distinctCount(arr, n) { // initialize count as number of elements let count = n; let i = 0, j = n - 1, sum = 0; while (i < j) { // Remove duplicate elements from the // left of the current window (i, j) // and also decrease the count while (i != j && arr[i] == arr[i + 1]) count--, i++; // Remove duplicate elements from the // right of the current window (i, j) // and also decrease the count while (i != j && arr[j] == arr[j - 1]) count--, j--; // break if only one element is left if (i == j) break; // Now look for the zero sum pair // in current window (i, j) sum = arr[i] + arr[j]; if (sum == 0) { // decrease the count if (positive, // negative) pair is encountered count--; i++, j--; } else if(sum < 0) i++; else j--; } return count; } let arr = [-2, -1, 0, 1, 1]; let n = arr.length; document.write( \"Count of absolute distinct values : \" + distinctCount(arr, n)); </script>", "e": 39271, "s": 37732, "text": null }, { "code": null, "e": 39281, "s": 39271, "text": "Output : " }, { "code": null, "e": 39319, "s": 39281, "text": "Count of absolute distinct values : 3" }, { "code": null, "e": 39752, "s": 39319, "text": "Time Complexity: O(n) Auxiliary Space: O(1)This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 39758, "s": 39752, "text": "jit_t" }, { "code": null, "e": 39769, "s": 39758, "text": "inderDuMCA" }, { "code": null, "e": 39783, "s": 39769, "text": "princiraj1992" }, { "code": null, "e": 39796, "s": 39783, "text": "Adarsh_Verma" }, { "code": null, "e": 39809, "s": 39796, "text": "Akanksha_Rai" }, { "code": null, "e": 39823, "s": 39809, "text": "divyesh072019" }, { "code": null, "e": 39832, "s": 39823, "text": "mukesh07" }, { "code": null, "e": 39849, "s": 39832, "text": "surinderdawra388" }, { "code": null, "e": 39856, "s": 39849, "text": "Arrays" }, { "code": null, "e": 39864, "s": 39856, "text": "Sorting" }, { "code": null, "e": 39871, "s": 39864, "text": "Arrays" }, { "code": null, "e": 39879, "s": 39871, "text": "Sorting" }, { "code": null, "e": 39977, "s": 39879, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39986, "s": 39977, "text": "Comments" }, { "code": null, "e": 39999, "s": 39986, "text": "Old Comments" }, { "code": null, "e": 40047, "s": 39999, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 40091, "s": 40047, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 40114, "s": 40091, "text": "Introduction to Arrays" } ]
H2O - Flow
In the last lesson, you learned to create H2O based ML models using command line interface. H2O Flow fulfils the same purpose, but with a web-based interface. In the following lessons, I will show you how to start H2O Flow and to run a sample application. The H2O installation that you downloaded earlier contains the h2o.jar file. To start H2O Flow, first run this jar from the command prompt βˆ’ $ java -jar h2o.jar When the jar runs successfully, you will get the following message on the console βˆ’ Open H2O Flow in your web browser: http://192.168.1.10:54321 Now, open the browser of your choice and type the above URL. You would see the H2O web-based desktop as shown here βˆ’ This is basically a notebook similar to Colab or Jupyter. I will show you how to load and run a sample application in this notebook while explaining the various features in Flow. Click on the view example Flows link on the above screen to see the list of provided examples. I will describe the Airlines delay Flow example from the sample. 14 Lectures 1 hours Mahesh Kumar 31 Lectures 1.5 hours Shweta 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 77 Lectures 5.5 hours Ayushi Nangru 12 Lectures 1.5 hours Richa Maheshwari Print Add Notes Bookmark this page
[ { "code": null, "e": 1811, "s": 1652, "text": "In the last lesson, you learned to create H2O based ML models using command line interface. H2O Flow fulfils the same purpose, but with a web-based interface." }, { "code": null, "e": 1908, "s": 1811, "text": "In the following lessons, I will show you how to start H2O Flow and to run a sample application." }, { "code": null, "e": 2048, "s": 1908, "text": "The H2O installation that you downloaded earlier contains the h2o.jar file. To start H2O Flow, first run this jar from the command prompt βˆ’" }, { "code": null, "e": 2069, "s": 2048, "text": "$ java -jar h2o.jar\n" }, { "code": null, "e": 2153, "s": 2069, "text": "When the jar runs successfully, you will get the following message on the console βˆ’" }, { "code": null, "e": 2215, "s": 2153, "text": "Open H2O Flow in your web browser: http://192.168.1.10:54321\n" }, { "code": null, "e": 2332, "s": 2215, "text": "Now, open the browser of your choice and type the above URL. You would see the H2O web-based desktop as shown here βˆ’" }, { "code": null, "e": 2606, "s": 2332, "text": "This is basically a notebook similar to Colab or Jupyter. I will show you how to load and run a sample application in this notebook while explaining the various features in Flow. Click on the view example Flows link on the above screen to see the list of provided examples." }, { "code": null, "e": 2671, "s": 2606, "text": "I will describe the Airlines delay Flow example from the sample." }, { "code": null, "e": 2704, "s": 2671, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 2718, "s": 2704, "text": " Mahesh Kumar" }, { "code": null, "e": 2753, "s": 2718, "text": "\n 31 Lectures \n 1.5 hours \n" }, { "code": null, "e": 2761, "s": 2753, "text": " Shweta" }, { "code": null, "e": 2798, "s": 2761, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 2814, "s": 2798, "text": " Malhar Lathkar" }, { "code": null, "e": 2847, "s": 2814, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 2866, "s": 2847, "text": " Arnab Chakraborty" }, { "code": null, "e": 2901, "s": 2866, "text": "\n 77 Lectures \n 5.5 hours \n" }, { "code": null, "e": 2916, "s": 2901, "text": " Ayushi Nangru" }, { "code": null, "e": 2951, "s": 2916, "text": "\n 12 Lectures \n 1.5 hours \n" }, { "code": null, "e": 2969, "s": 2951, "text": " Richa Maheshwari" }, { "code": null, "e": 2976, "s": 2969, "text": " Print" }, { "code": null, "e": 2987, "s": 2976, "text": " Add Notes" } ]
Web Scraping Metacritic Reviews using BeautifulSoup | by Adeline Ong | Towards Data Science
I decided to scrape Metacritic Pokemon reviews because I wanted to topic model negative game reviews. I was intrigued by how the games were praised by critics but evaluated badly by most gamers. Why do gamers hate Pokemon? More about that in this post. In the meantime, here’s how I scraped the reviews from the site. **Full code at the bottom. Embedded codes (in the gray boxes) are for explanatory purposes*** Import packages. The main packages that you need are request, BeautifulSoup and pandas. Import packages. The main packages that you need are request, BeautifulSoup and pandas. #To get the url, and scrap the html page import requestsfrom bs4 import BeautifulSoup#To save the reviews in a dataframe import pandas as pd 2. Figure out the web page’s Html structure. Html tags are used to mark page elements, and similar elements are usually contained within the same tags. You want to be familiar with the Html tag patterns, what info is contained within which tags, and the best way to find these tags. The easiest way to find important tags is to use Chrome, select the text you’re interested in scraping, right-click and β€˜Inspect’. This will open a separate window containing the page’s Html. The text we highlighted is in the span tag. You can expand the span tag and see the text by clicking on the small triangle next to <span>. BeautifulSoup (BS) can find reviews within span tags, but there are other page elements within span tags that are not reviews. A better way would be to tell BS to find an outer tag that is review-specific and then find a span tag within. If you scroll through the page’s Html, you will notice that each review’s text is nested within div classes. These classes follow a fixed structure and repeat for every review on the page. Take note of the review_content div class. It contains reviews contents such as username, rating score and review text. Also, note the other classes within review_content as we’ll use these to tell BS how to find review texts. 3. Parse the page using BS. Make a URL request, and parse the response into BS. url = 'https://www.metacritic.com/game/switch/pokemon-sword/user-reviews?page=0'user_agent = {'User-agent': 'Mozilla/5.0'}response = requests.get(url, headers = user_agent)soup = BeautifulSoup(response.text, 'html.parser') 4. Create a dictionary to hold the info that you want to scrape. The keys are the feature names and the values are lists. review_dict = {'name':[], 'date':[], 'rating':[], 'review':[]} 5. Tell BS how to find the info that you want, and append them to the dictionary’s lists. We’ll go through how to get the text review. The code for the other elements is at the bottom of this post. #look for review_content tags since every user review has this tag for review in soup.find_all('div', class_='review_content'): #within review_content tag, look for the presence of longer reviewsif review.find('span', class_='blurb blurb_expanded'): review_dict['review'].append(review.find('span', class_=’blurb blurb_expanded').text) else: review_dict[β€˜review’].append(review.find('div',class_='review_body').find('span').text) We use find all to get all review_content tags within the page. This is the same as finding all reviews on the page because each review is enclosed by this div class. The if-else statement ensures that the text is pulled from the right tag, depending on whether the review is long or not. Let’s look at the β€˜else ’condition first. For each review_content tag, we look for a div class that is close to the span tag containing the text review. In this case, I’ve used review_body div class. Since there is only one span tag within this class, we can use find to look for the first span tag. On to the β€˜if’ condition. Longer reviews (that require users to click on β€˜Expand’ to see the full text) are within a blurb blurb_expanded span class. Shorter reviews do not have this class. Since blurb blurb_expanded only appears for longer reviews, we can find it directly. Since all reviews on Metacritic have the same elements, we can just append the desired info to lists, and they will be in-order. 6. Convert the dictionary into a dataframe. sword_reviews = pd.DataFrame(review_dict) Woohoo! And that’s it. If you want to scrape all the reviews, you just need to loop through all the pages, as I have done in the code below: In this post, we created a simple web scraper using BS. We could do this because the page did not have dynamic content. For dynamic pages, you might want to try using Selenium, which can be very powerful when combined with BS. Web scraping can be time-consuming, but it’s a gateway to online content. I personally find web scraping useful for NPL projects because it enables easy access to current conversations, and quick sensing of sentiments, which is useful for real-time evaluations of marketing/communication campaigns. I hope this post has been helpful to you. Happy scraping!
[ { "code": null, "e": 365, "s": 47, "text": "I decided to scrape Metacritic Pokemon reviews because I wanted to topic model negative game reviews. I was intrigued by how the games were praised by critics but evaluated badly by most gamers. Why do gamers hate Pokemon? More about that in this post. In the meantime, here’s how I scraped the reviews from the site." }, { "code": null, "e": 459, "s": 365, "text": "**Full code at the bottom. Embedded codes (in the gray boxes) are for explanatory purposes***" }, { "code": null, "e": 547, "s": 459, "text": "Import packages. The main packages that you need are request, BeautifulSoup and pandas." }, { "code": null, "e": 635, "s": 547, "text": "Import packages. The main packages that you need are request, BeautifulSoup and pandas." }, { "code": null, "e": 777, "s": 635, "text": "#To get the url, and scrap the html page import requestsfrom bs4 import BeautifulSoup#To save the reviews in a dataframe import pandas as pd" }, { "code": null, "e": 1060, "s": 777, "text": "2. Figure out the web page’s Html structure. Html tags are used to mark page elements, and similar elements are usually contained within the same tags. You want to be familiar with the Html tag patterns, what info is contained within which tags, and the best way to find these tags." }, { "code": null, "e": 1191, "s": 1060, "text": "The easiest way to find important tags is to use Chrome, select the text you’re interested in scraping, right-click and β€˜Inspect’." }, { "code": null, "e": 1391, "s": 1191, "text": "This will open a separate window containing the page’s Html. The text we highlighted is in the span tag. You can expand the span tag and see the text by clicking on the small triangle next to <span>." }, { "code": null, "e": 1629, "s": 1391, "text": "BeautifulSoup (BS) can find reviews within span tags, but there are other page elements within span tags that are not reviews. A better way would be to tell BS to find an outer tag that is review-specific and then find a span tag within." }, { "code": null, "e": 1818, "s": 1629, "text": "If you scroll through the page’s Html, you will notice that each review’s text is nested within div classes. These classes follow a fixed structure and repeat for every review on the page." }, { "code": null, "e": 2045, "s": 1818, "text": "Take note of the review_content div class. It contains reviews contents such as username, rating score and review text. Also, note the other classes within review_content as we’ll use these to tell BS how to find review texts." }, { "code": null, "e": 2125, "s": 2045, "text": "3. Parse the page using BS. Make a URL request, and parse the response into BS." }, { "code": null, "e": 2348, "s": 2125, "text": "url = 'https://www.metacritic.com/game/switch/pokemon-sword/user-reviews?page=0'user_agent = {'User-agent': 'Mozilla/5.0'}response = requests.get(url, headers = user_agent)soup = BeautifulSoup(response.text, 'html.parser')" }, { "code": null, "e": 2470, "s": 2348, "text": "4. Create a dictionary to hold the info that you want to scrape. The keys are the feature names and the values are lists." }, { "code": null, "e": 2533, "s": 2470, "text": "review_dict = {'name':[], 'date':[], 'rating':[], 'review':[]}" }, { "code": null, "e": 2731, "s": 2533, "text": "5. Tell BS how to find the info that you want, and append them to the dictionary’s lists. We’ll go through how to get the text review. The code for the other elements is at the bottom of this post." }, { "code": null, "e": 3161, "s": 2731, "text": "#look for review_content tags since every user review has this tag for review in soup.find_all('div', class_='review_content'): #within review_content tag, look for the presence of longer reviewsif review.find('span', class_='blurb blurb_expanded'): review_dict['review'].append(review.find('span', class_=’blurb blurb_expanded').text) else: review_dict[β€˜review’].append(review.find('div',class_='review_body').find('span').text)" }, { "code": null, "e": 3328, "s": 3161, "text": "We use find all to get all review_content tags within the page. This is the same as finding all reviews on the page because each review is enclosed by this div class." }, { "code": null, "e": 3450, "s": 3328, "text": "The if-else statement ensures that the text is pulled from the right tag, depending on whether the review is long or not." }, { "code": null, "e": 3750, "s": 3450, "text": "Let’s look at the β€˜else ’condition first. For each review_content tag, we look for a div class that is close to the span tag containing the text review. In this case, I’ve used review_body div class. Since there is only one span tag within this class, we can use find to look for the first span tag." }, { "code": null, "e": 4025, "s": 3750, "text": "On to the β€˜if’ condition. Longer reviews (that require users to click on β€˜Expand’ to see the full text) are within a blurb blurb_expanded span class. Shorter reviews do not have this class. Since blurb blurb_expanded only appears for longer reviews, we can find it directly." }, { "code": null, "e": 4154, "s": 4025, "text": "Since all reviews on Metacritic have the same elements, we can just append the desired info to lists, and they will be in-order." }, { "code": null, "e": 4198, "s": 4154, "text": "6. Convert the dictionary into a dataframe." }, { "code": null, "e": 4240, "s": 4198, "text": "sword_reviews = pd.DataFrame(review_dict)" }, { "code": null, "e": 4381, "s": 4240, "text": "Woohoo! And that’s it. If you want to scrape all the reviews, you just need to loop through all the pages, as I have done in the code below:" }, { "code": null, "e": 4608, "s": 4381, "text": "In this post, we created a simple web scraper using BS. We could do this because the page did not have dynamic content. For dynamic pages, you might want to try using Selenium, which can be very powerful when combined with BS." }, { "code": null, "e": 4907, "s": 4608, "text": "Web scraping can be time-consuming, but it’s a gateway to online content. I personally find web scraping useful for NPL projects because it enables easy access to current conversations, and quick sensing of sentiments, which is useful for real-time evaluations of marketing/communication campaigns." } ]
JavaScript Boolean valueOf() Method - GeeksforGeeks
24 Nov, 2021 Below is the example of Boolean valueOf() method. Example: javascript <script> // Here Boolean object obj // is created for the value 27 var obj = new Boolean(27); // Here boolean.valueOf() function is // used for the created object obj. document.write(obj.valueOf()); Output: true The boolean.valueOf() method is used to return a boolean value either β€œtrue” or β€œfalse” depending upon the value of the specified boolean object.Syntax: boolean.valueOf() Parameter: This method does not accept any parameter.Return value: It returns a boolean value either β€œtrue” or β€œfalse” depending upon the value of the specified boolean object.More codes for the above method are as follows: Program 1: javascript <script> // Here Boolean object obj is created // for the value true. var obj = new Boolean(true); // Here boolean.valueOf() function is // used for the created object obj. document.write(obj.valueOf());</script> Output: true Program 2: javascript <script> // Here Boolean object obj is // created for the value 1. var obj = new Boolean(1); // Here boolean.valueOf() function // is used for the created object obj. document.write(obj.valueOf());</script> Output: true Program 3: javascript <script> // Here Boolean object obj is // created for the value -1. var obj = new Boolean(-1); // Here boolean.valueOf() function // is used for the created object obj. document.write(obj.valueOf());</script> Output: true Program 4: javascript <script> // Here Boolean object obj is // created for the value 1.2 var obj = new Boolean(1.2); // Here boolean.valueOf() function // is used for the created object obj. document.write(obj.valueOf());</script> Output: true Program 5: javascript <script> // Here Boolean object obj is // created for the value as string "gfg" var obj = new Boolean("gfg"); // Here boolean.valueOf() function is // used for the created object obj. document.write(obj.valueOf());</script> Output: true Program 6: javascript <script> // Here Boolean object obj is created for the value false. var obj = new Boolean(false); // Here boolean.valueOf() function is // used for the created object obj. document.write(obj.valueOf());</script> Output: false Program 7: javascript <script> // Here Boolean object obj is created // for the value zero (0) var obj = new Boolean(0); // Here boolean.valueOf() function is // used for the created object obj. document.write(obj.valueOf());</script> Output: false Program 1: Here the value as geeksforgeeks gives an error because this value is not defined only true and false has been predefined. javascript <script> // Here Boolean object obj is created // for the value geeksforgeeks. var obj = new Boolean(geeksforgeeks); // Here boolean.valueOf() function is // used for the created object obj. console.log(obj.valueOf());</script> Output: Error: geeksforgeeks is not defined Program 2: Here complex number can not be taken as the parameter only integer values and string can be taken as the parameter that is why it returns error. javascript <script> // Here Boolean object obj is created // for the value such as complex number 1+2i var obj = new Boolean(1 + 2i); // Here boolean.valueOf() function is // used for the created object obj. console.log(obj.valueOf()); Output: Error: Invalid or unexpected token Supported Browsers: The browsers supported by JavaScript Boolean valueOf() Method are listed below: Google Chrome 1 and above Internet Explorer 4 and above Mozilla Firefox 1 and above Safari 1 and above Opera 4 and above ysachin2314 JavaScript-Boolean JavaScript-Methods JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Convert a string to an integer in JavaScript How to calculate the number of days between two dates in javascript? Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React File uploading in React.js Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 29980, "s": 29952, "text": "\n24 Nov, 2021" }, { "code": null, "e": 30032, "s": 29980, "text": "Below is the example of Boolean valueOf() method. " }, { "code": null, "e": 30043, "s": 30032, "text": "Example: " }, { "code": null, "e": 30054, "s": 30043, "text": "javascript" }, { "code": "<script> // Here Boolean object obj // is created for the value 27 var obj = new Boolean(27); // Here boolean.valueOf() function is // used for the created object obj. document.write(obj.valueOf());", "e": 30260, "s": 30054, "text": null }, { "code": null, "e": 30270, "s": 30260, "text": "Output: " }, { "code": null, "e": 30275, "s": 30270, "text": "true" }, { "code": null, "e": 30430, "s": 30275, "text": "The boolean.valueOf() method is used to return a boolean value either β€œtrue” or β€œfalse” depending upon the value of the specified boolean object.Syntax: " }, { "code": null, "e": 30448, "s": 30430, "text": "boolean.valueOf()" }, { "code": null, "e": 30674, "s": 30448, "text": "Parameter: This method does not accept any parameter.Return value: It returns a boolean value either β€œtrue” or β€œfalse” depending upon the value of the specified boolean object.More codes for the above method are as follows: " }, { "code": null, "e": 30687, "s": 30674, "text": "Program 1: " }, { "code": null, "e": 30698, "s": 30687, "text": "javascript" }, { "code": "<script> // Here Boolean object obj is created // for the value true. var obj = new Boolean(true); // Here boolean.valueOf() function is // used for the created object obj. document.write(obj.valueOf());</script>", "e": 30918, "s": 30698, "text": null }, { "code": null, "e": 30928, "s": 30918, "text": "Output: " }, { "code": null, "e": 30933, "s": 30928, "text": "true" }, { "code": null, "e": 30950, "s": 30937, "text": "Program 2: " }, { "code": null, "e": 30961, "s": 30950, "text": "javascript" }, { "code": "<script> // Here Boolean object obj is // created for the value 1. var obj = new Boolean(1); // Here boolean.valueOf() function // is used for the created object obj. document.write(obj.valueOf());</script>", "e": 31175, "s": 30961, "text": null }, { "code": null, "e": 31185, "s": 31175, "text": "Output: " }, { "code": null, "e": 31190, "s": 31185, "text": "true" }, { "code": null, "e": 31207, "s": 31194, "text": "Program 3: " }, { "code": null, "e": 31218, "s": 31207, "text": "javascript" }, { "code": "<script> // Here Boolean object obj is // created for the value -1. var obj = new Boolean(-1); // Here boolean.valueOf() function // is used for the created object obj. document.write(obj.valueOf());</script>", "e": 31434, "s": 31218, "text": null }, { "code": null, "e": 31444, "s": 31434, "text": "Output: " }, { "code": null, "e": 31449, "s": 31444, "text": "true" }, { "code": null, "e": 31462, "s": 31449, "text": "Program 4: " }, { "code": null, "e": 31473, "s": 31462, "text": "javascript" }, { "code": "<script> // Here Boolean object obj is // created for the value 1.2 var obj = new Boolean(1.2); // Here boolean.valueOf() function // is used for the created object obj. document.write(obj.valueOf());</script>", "e": 31690, "s": 31473, "text": null }, { "code": null, "e": 31700, "s": 31690, "text": "Output: " }, { "code": null, "e": 31705, "s": 31700, "text": "true" }, { "code": null, "e": 31718, "s": 31705, "text": "Program 5: " }, { "code": null, "e": 31729, "s": 31718, "text": "javascript" }, { "code": "<script> // Here Boolean object obj is // created for the value as string \"gfg\" var obj = new Boolean(\"gfg\"); // Here boolean.valueOf() function is // used for the created object obj. document.write(obj.valueOf());</script>", "e": 31960, "s": 31729, "text": null }, { "code": null, "e": 31970, "s": 31960, "text": "Output: " }, { "code": null, "e": 31975, "s": 31970, "text": "true" }, { "code": null, "e": 31990, "s": 31977, "text": "Program 6: " }, { "code": null, "e": 32001, "s": 31990, "text": "javascript" }, { "code": "<script> // Here Boolean object obj is created for the value false. var obj = new Boolean(false); // Here boolean.valueOf() function is // used for the created object obj. document.write(obj.valueOf());</script>", "e": 32219, "s": 32001, "text": null }, { "code": null, "e": 32229, "s": 32219, "text": "Output: " }, { "code": null, "e": 32235, "s": 32229, "text": "false" }, { "code": null, "e": 32252, "s": 32239, "text": "Program 7: " }, { "code": null, "e": 32263, "s": 32252, "text": "javascript" }, { "code": "<script> // Here Boolean object obj is created // for the value zero (0) var obj = new Boolean(0); // Here boolean.valueOf() function is // used for the created object obj. document.write(obj.valueOf());</script>", "e": 32483, "s": 32263, "text": null }, { "code": null, "e": 32493, "s": 32483, "text": "Output: " }, { "code": null, "e": 32499, "s": 32493, "text": "false" }, { "code": null, "e": 32635, "s": 32501, "text": "Program 1: Here the value as geeksforgeeks gives an error because this value is not defined only true and false has been predefined. " }, { "code": null, "e": 32646, "s": 32635, "text": "javascript" }, { "code": "<script> // Here Boolean object obj is created // for the value geeksforgeeks. var obj = new Boolean(geeksforgeeks); // Here boolean.valueOf() function is // used for the created object obj. console.log(obj.valueOf());</script>", "e": 32881, "s": 32646, "text": null }, { "code": null, "e": 32891, "s": 32881, "text": "Output: " }, { "code": null, "e": 32927, "s": 32891, "text": "Error: geeksforgeeks is not defined" }, { "code": null, "e": 33087, "s": 32929, "text": "Program 2: Here complex number can not be taken as the parameter only integer values and string can be taken as the parameter that is why it returns error. " }, { "code": null, "e": 33098, "s": 33087, "text": "javascript" }, { "code": "<script> // Here Boolean object obj is created // for the value such as complex number 1+2i var obj = new Boolean(1 + 2i); // Here boolean.valueOf() function is // used for the created object obj. console.log(obj.valueOf());", "e": 33330, "s": 33098, "text": null }, { "code": null, "e": 33340, "s": 33330, "text": "Output: " }, { "code": null, "e": 33375, "s": 33340, "text": "Error: Invalid or unexpected token" }, { "code": null, "e": 33476, "s": 33375, "text": "Supported Browsers: The browsers supported by JavaScript Boolean valueOf() Method are listed below: " }, { "code": null, "e": 33502, "s": 33476, "text": "Google Chrome 1 and above" }, { "code": null, "e": 33532, "s": 33502, "text": "Internet Explorer 4 and above" }, { "code": null, "e": 33560, "s": 33532, "text": "Mozilla Firefox 1 and above" }, { "code": null, "e": 33579, "s": 33560, "text": "Safari 1 and above" }, { "code": null, "e": 33597, "s": 33579, "text": "Opera 4 and above" }, { "code": null, "e": 33611, "s": 33599, "text": "ysachin2314" }, { "code": null, "e": 33630, "s": 33611, "text": "JavaScript-Boolean" }, { "code": null, "e": 33649, "s": 33630, "text": "JavaScript-Methods" }, { "code": null, "e": 33660, "s": 33649, "text": "JavaScript" }, { "code": null, "e": 33677, "s": 33660, "text": "Web Technologies" }, { "code": null, "e": 33775, "s": 33677, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33784, "s": 33775, "text": "Comments" }, { "code": null, "e": 33797, "s": 33784, "text": "Old Comments" }, { "code": null, "e": 33842, "s": 33797, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 33911, "s": 33842, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 33972, "s": 33911, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 34044, "s": 33972, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 34071, "s": 34044, "text": "File uploading in React.js" }, { "code": null, "e": 34113, "s": 34071, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 34146, "s": 34113, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 34189, "s": 34146, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 34251, "s": 34189, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Moore's Voting Algorithm | Majority element in an array - onlinetutorialspoint
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws In this tutorial, we’ll learn about Moore’s voting algorithm in Python. To understand this, let’s start with the problem of finding the majority element in a given array. Say, you’re given an array A of size n. Now, the element in the array, that appears more than n/2 times is said to be the majority element. Can you think of ways to find this majority element for a given array? What can you infer from the given problem statement? One of the most important observation to note is that, for a given array, there can be at most one majority element. This is because, for an array of size n, it is possible only for one element to occur more than n/2 times in the array. There can even be a possibility of no element to occur more than n/2 times, and in that case, the majority element doesn’t exist for the given array. A simple approach will be, to iterate over each element of the array and check whether it is the majority element or not. def majorityElement(A, N): for i in range(len(A)): count = 0 for j in range(len(A)): if(A[j] == A[i]): count += 1 if(count > N/2): return A[i] return -1 if __name__ == "__main__": arr = [3,1,3,1,3,5,3,3] res = majorityElement(arr,8) print(res) 3 O(n) to check whether an element is the majority element or not. This operation is done for each array element, i.e., for n times. So, the overall time complexity is O(n2) . O(1) , as no extra space is being used. Constant space complexity. Can you think of a more efficient solution to solve this problem? Arr = [1,1,2,2,3] Arr = [1,12] Arr = [1,1,2,2,3] Arr = [1,12] Note that in the above cases, Arr doesn’t have a majority element. Here comes the answer to solve the problem in linear time, with Moore’s voting algorithm. Loop through each element of the array, and maintain two integers candidate i.e., the potential candidate to be the majority element and count. At a given index i, If arr[i] is equal to the candidate, then, increment count by 1. If arr[i] is not equal to the candidate, then, decrement count by 1. If the count becomes zero, then, the value at that index will be the new value of candidate and count will be set to 1. If arr[i] is equal to the candidate, then, increment count by 1. If arr[i] is not equal to the candidate, then, decrement count by 1. If the count becomes zero, then, the value at that index will be the new value of candidate and count will be set to 1. At the end, the value stored in candidate will be the majority element of the array, if exists. As a final check, iterate through the array and check if the frequency of the candidate in the array is greater than n/2 or not. If yes, then that is the majority element. Otherwise, we can say that the array doesn’t have a majority element. def majorityElement(A, N): candidate = A[0] count=1 for i in range(len(A)): if(A[i]==candidate): count += 1; else: count -= 1; if(count == 0): candidate = A[i] count = 1 continue res = -1 #checking if the candidate is the majority or not count = 0 for num in A: if(num == candidate): count += 1 if(count > N/2): res = candidate return res if __name__ == "__main__": arr = [3,1,3,1,3,5,3,3] res = majorityElement(arr,8) print(res) 3 Note that, for a given array, if candidate is the actual majority element i.e., the element that occurs more than n/2 times, then, the number of increments of count will be more than the number of decrements. Hence, count will remain to be greater than zero after looping through the array. Also, it is made sure that count never holds zero at the end of any iteration. So, the element stored in candidate after looping through the array is the potential majority element of the array. O(n) – Linear time complexity, as we are just looping through the array elements, it takes linear time. O(1) , no extra space is being used. Constant space complexity. More on Moore’s Algorithm Happy Learning πŸ™‚ How to implement Counting Sort Algorithm Python Kadane’s Algorithm | Maximum subarray sum Java Program to find Smallest and Largest element in Array Python – Three way partitioning of an Array Example How to Rotate an Array to Left direction based on user input ? What is an Algorithm ? C Program to add elements of an array C Program – Reverse the Elements of an Array Binary Search using Java How to find a missing number in an array ? PHP Array Example Tutorials C Program – Find Largest and Smallest number in an Array Difference between Linkedlist and Array PHP Array Sort Techniques Tutorials Java Program To Find Largest and Smallest Number in Array How to implement Counting Sort Algorithm Python Kadane’s Algorithm | Maximum subarray sum Java Program to find Smallest and Largest element in Array Python – Three way partitioning of an Array Example How to Rotate an Array to Left direction based on user input ? What is an Algorithm ? C Program to add elements of an array C Program – Reverse the Elements of an Array Binary Search using Java How to find a missing number in an array ? PHP Array Example Tutorials C Program – Find Largest and Smallest number in an Array Difference between Linkedlist and Array PHP Array Sort Techniques Tutorials Java Program To Find Largest and Smallest Number in Array
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 569, "s": 398, "text": "In this tutorial, we’ll learn about Moore’s voting algorithm in Python. To understand this, let’s start with the problem of finding the majority element in a given array." }, { "code": null, "e": 780, "s": 569, "text": "Say, you’re given an array A of size n. Now, the element in the array, that appears more than n/2 times is said to be the majority element. Can you think of ways to find this majority element for a given array?" }, { "code": null, "e": 833, "s": 780, "text": "What can you infer from the given problem statement?" }, { "code": null, "e": 1220, "s": 833, "text": "One of the most important observation to note is that, for a given array, there can be at most one majority element. This is because, for an array of size n, it is possible only for one element to occur more than n/2 times in the array. There can even be a possibility of no element to occur more than n/2 times, and in that case, the majority element doesn’t exist for the given array." }, { "code": null, "e": 1342, "s": 1220, "text": "A simple approach will be, to iterate over each element of the array and check whether it is the majority element or not." }, { "code": null, "e": 1686, "s": 1342, "text": "def majorityElement(A, N):\n \n for i in range(len(A)):\n \n count = 0\n for j in range(len(A)):\n if(A[j] == A[i]):\n count += 1\n\n if(count > N/2):\n return A[i]\n \n return -1\n\n\nif __name__ == \"__main__\":\n arr = [3,1,3,1,3,5,3,3]\n res = majorityElement(arr,8)\n print(res)" }, { "code": null, "e": 1688, "s": 1686, "text": "3" }, { "code": null, "e": 1862, "s": 1688, "text": "O(n) to check whether an element is the majority element or not. This operation is done for each array element, i.e., for n times. So, the overall time complexity is O(n2) ." }, { "code": null, "e": 1929, "s": 1862, "text": "O(1) , as no extra space is being used. Constant space complexity." }, { "code": null, "e": 1995, "s": 1929, "text": "Can you think of a more efficient solution to solve this problem?" }, { "code": null, "e": 2029, "s": 1995, "text": "\n Arr = [1,1,2,2,3]\nArr = [1,12]\n" }, { "code": null, "e": 2048, "s": 2029, "text": " Arr = [1,1,2,2,3]" }, { "code": null, "e": 2061, "s": 2048, "text": "Arr = [1,12]" }, { "code": null, "e": 2128, "s": 2061, "text": "Note that in the above cases, Arr doesn’t have a majority element." }, { "code": null, "e": 2218, "s": 2128, "text": "Here comes the answer to solve the problem in linear time, with Moore’s voting algorithm." }, { "code": null, "e": 2362, "s": 2218, "text": "Loop through each element of the array, and maintain two integers candidate i.e., the potential candidate to be the majority element and count." }, { "code": null, "e": 2639, "s": 2362, "text": "At a given index i,\n\nIf arr[i] is equal to the candidate, then, increment count by 1.\nIf arr[i] is not equal to the candidate, then, decrement count by 1.\nIf the count becomes zero, then, the value at that index will be the new value of candidate and count will be set to 1.\n\n" }, { "code": null, "e": 2704, "s": 2639, "text": "If arr[i] is equal to the candidate, then, increment count by 1." }, { "code": null, "e": 2773, "s": 2704, "text": "If arr[i] is not equal to the candidate, then, decrement count by 1." }, { "code": null, "e": 2893, "s": 2773, "text": "If the count becomes zero, then, the value at that index will be the new value of candidate and count will be set to 1." }, { "code": null, "e": 2989, "s": 2893, "text": "At the end, the value stored in candidate will be the majority element of the array, if exists." }, { "code": null, "e": 3231, "s": 2989, "text": "As a final check, iterate through the array and check if the frequency of the candidate in the array is greater than n/2 or not. If yes, then that is the majority element. Otherwise, we can say that the array doesn’t have a majority element." }, { "code": null, "e": 3859, "s": 3231, "text": "def majorityElement(A, N):\n candidate = A[0]\n count=1\n for i in range(len(A)):\n \n if(A[i]==candidate):\n count += 1;\n else:\n count -= 1;\n \n if(count == 0):\n candidate = A[i]\n count = 1\n continue\n \n res = -1\n \n #checking if the candidate is the majority or not\n count = 0\n for num in A:\n if(num == candidate):\n count += 1\n \n if(count > N/2):\n res = candidate\n \n return res\n\n\nif __name__ == \"__main__\":\n arr = [3,1,3,1,3,5,3,3]\n res = majorityElement(arr,8)\n print(res)" }, { "code": null, "e": 3861, "s": 3859, "text": "3" }, { "code": null, "e": 4347, "s": 3861, "text": "Note that, for a given array, if candidate is the actual majority element i.e., the element that occurs more than n/2 times, then, the number of increments of count will be more than the number of decrements. Hence, count will remain to be greater than zero after looping through the array. Also, it is made sure that count never holds zero at the end of any iteration. So, the element stored in candidate after looping through the array is the potential majority element of the array." }, { "code": null, "e": 4451, "s": 4347, "text": "O(n) – Linear time complexity, as we are just looping through the array elements, it takes linear time." }, { "code": null, "e": 4515, "s": 4451, "text": "O(1) , no extra space is being used. Constant space complexity." }, { "code": null, "e": 4541, "s": 4515, "text": "More on Moore’s Algorithm" }, { "code": null, "e": 4558, "s": 4541, "text": "Happy Learning πŸ™‚" }, { "code": null, "e": 5217, "s": 4558, "text": "\nHow to implement Counting Sort Algorithm Python\nKadane’s Algorithm | Maximum subarray sum\nJava Program to find Smallest and Largest element in Array\nPython – Three way partitioning of an Array Example\nHow to Rotate an Array to Left direction based on user input ?\nWhat is an Algorithm ?\nC Program to add elements of an array\nC Program – Reverse the Elements of an Array\nBinary Search using Java\nHow to find a missing number in an array ?\nPHP Array Example Tutorials\nC Program – Find Largest and Smallest number in an Array\nDifference between Linkedlist and Array\nPHP Array Sort Techniques Tutorials\nJava Program To Find Largest and Smallest Number in Array\n" }, { "code": null, "e": 5265, "s": 5217, "text": "How to implement Counting Sort Algorithm Python" }, { "code": null, "e": 5307, "s": 5265, "text": "Kadane’s Algorithm | Maximum subarray sum" }, { "code": null, "e": 5366, "s": 5307, "text": "Java Program to find Smallest and Largest element in Array" }, { "code": null, "e": 5418, "s": 5366, "text": "Python – Three way partitioning of an Array Example" }, { "code": null, "e": 5481, "s": 5418, "text": "How to Rotate an Array to Left direction based on user input ?" }, { "code": null, "e": 5504, "s": 5481, "text": "What is an Algorithm ?" }, { "code": null, "e": 5542, "s": 5504, "text": "C Program to add elements of an array" }, { "code": null, "e": 5587, "s": 5542, "text": "C Program – Reverse the Elements of an Array" }, { "code": null, "e": 5612, "s": 5587, "text": "Binary Search using Java" }, { "code": null, "e": 5655, "s": 5612, "text": "How to find a missing number in an array ?" }, { "code": null, "e": 5683, "s": 5655, "text": "PHP Array Example Tutorials" }, { "code": null, "e": 5740, "s": 5683, "text": "C Program – Find Largest and Smallest number in an Array" }, { "code": null, "e": 5780, "s": 5740, "text": "Difference between Linkedlist and Array" }, { "code": null, "e": 5816, "s": 5780, "text": "PHP Array Sort Techniques Tutorials" } ]
Height of a complete binary tree (or Heap) with N nodes - GeeksforGeeks
06 Jan, 2022 Consider a Binary Heap of size N. We need to find the height of it.Examples : Input : N = 6 Output : 2 () / \ () () / \ / () () () Input : N = 9 Output : () / \ () () / \ / \ () () () () / \ () () Let the size of heap be N and height be h If we take a few examples, we can notice that the value of h in a complete binary tree is floor(log2N). Examples : N h --------- 1 0 2 1 3 1 4 2 5 2 ..... ..... C++ Java Python 3 C# PHP Javascript // CPP program to find height of complete// binary tree from total nodes.#include <bits/stdc++.h>using namespace std; int height(int N){ return floor(log2(N));} // driver nodeint main(){ int N = 2; cout << height(N); return 0;} // Java program to find height// of complete binary tree// from total nodes.import java.lang.*; class GFG { // Function to calculate height static int height(int N) { return (int)Math.ceil(Math.log(N + 1) / Math.log(2)) - 1; } // Driver Code public static void main(String[] args) { int N = 6; System.out.println(height(N)); }} // This code is contributed by// Smitha Dinesh Semwal # Python 3 program to find# height of complete binary# tree from total nodes.import mathdef height(N): return math.ceil(math.log2(N + 1)) - 1 # driver nodeN = 6print(height(N)) # This code is contributed by# Smitha Dinesh Semwal // C# program to find height// of complete binary tree// from total nodes.using System; class GFG { static int height(int N) { return (int)Math.Ceiling(Math.Log(N + 1) / Math.Log(2)) - 1; } // Driver node public static void Main() { int N = 6; Console.Write(height(N)); }} // This code is contributed by// Smitha Dinesh Semwal <?php// PHP program to find height// of complete binary tree// from total nodes. function height($N){ return ceil(log($N + 1, 2)) - 1;} // Driver Code$N = 6;echo height($N); // This code is contributed by aj_36?> <script> // Javascript program to find height // of complete binary tree // from total nodes. function height(N) { return Math.ceil(Math.log(N + 1) / Math.log(2)) - 1; } let N = 6; document.write(height(N)); </script> 2 Smitha Dinesh Semwal jit_t suresh07 demishassabis Heap Tree Tree Heap Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Sliding Window Maximum (Maximum of all subarrays of size k) Building Heap from Array Time Complexity of building a heap Max Heap in Java Insertion and Deletion in Heaps Binary Tree | Set 1 (Introduction) AVL Tree | Set 1 (Insertion) Binary Tree | Set 3 (Types of Binary Tree) Binary Tree | Set 2 (Properties)
[ { "code": null, "e": 25022, "s": 24994, "text": "\n06 Jan, 2022" }, { "code": null, "e": 25102, "s": 25022, "text": "Consider a Binary Heap of size N. We need to find the height of it.Examples : " }, { "code": null, "e": 25305, "s": 25102, "text": "Input : N = 6\nOutput : 2\n ()\n / \\\n () ()\n / \\ /\n () () ()\n\nInput : N = 9\nOutput :\n ()\n / \\\n () ()\n / \\ / \\\n () () () ()\n / \\\n() ()" }, { "code": null, "e": 25466, "s": 25307, "text": "Let the size of heap be N and height be h If we take a few examples, we can notice that the value of h in a complete binary tree is floor(log2N). Examples : " }, { "code": null, "e": 25538, "s": 25466, "text": " N h\n---------\n 1 0\n 2 1\n 3 1\n 4 2\n 5 2\n .....\n ....." }, { "code": null, "e": 25544, "s": 25540, "text": "C++" }, { "code": null, "e": 25549, "s": 25544, "text": "Java" }, { "code": null, "e": 25558, "s": 25549, "text": "Python 3" }, { "code": null, "e": 25561, "s": 25558, "text": "C#" }, { "code": null, "e": 25565, "s": 25561, "text": "PHP" }, { "code": null, "e": 25576, "s": 25565, "text": "Javascript" }, { "code": "// CPP program to find height of complete// binary tree from total nodes.#include <bits/stdc++.h>using namespace std; int height(int N){ return floor(log2(N));} // driver nodeint main(){ int N = 2; cout << height(N); return 0;}", "e": 25816, "s": 25576, "text": null }, { "code": "// Java program to find height// of complete binary tree// from total nodes.import java.lang.*; class GFG { // Function to calculate height static int height(int N) { return (int)Math.ceil(Math.log(N + 1) / Math.log(2)) - 1; } // Driver Code public static void main(String[] args) { int N = 6; System.out.println(height(N)); }} // This code is contributed by// Smitha Dinesh Semwal", "e": 26268, "s": 25816, "text": null }, { "code": "# Python 3 program to find# height of complete binary# tree from total nodes.import mathdef height(N): return math.ceil(math.log2(N + 1)) - 1 # driver nodeN = 6print(height(N)) # This code is contributed by# Smitha Dinesh Semwal", "e": 26500, "s": 26268, "text": null }, { "code": "// C# program to find height// of complete binary tree// from total nodes.using System; class GFG { static int height(int N) { return (int)Math.Ceiling(Math.Log(N + 1) / Math.Log(2)) - 1; } // Driver node public static void Main() { int N = 6; Console.Write(height(N)); }} // This code is contributed by// Smitha Dinesh Semwal", "e": 26888, "s": 26500, "text": null }, { "code": "<?php// PHP program to find height// of complete binary tree// from total nodes. function height($N){ return ceil(log($N + 1, 2)) - 1;} // Driver Code$N = 6;echo height($N); // This code is contributed by aj_36?>", "e": 27104, "s": 26888, "text": null }, { "code": "<script> // Javascript program to find height // of complete binary tree // from total nodes. function height(N) { return Math.ceil(Math.log(N + 1) / Math.log(2)) - 1; } let N = 6; document.write(height(N)); </script>", "e": 27376, "s": 27104, "text": null }, { "code": null, "e": 27378, "s": 27376, "text": "2" }, { "code": null, "e": 27401, "s": 27380, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 27407, "s": 27401, "text": "jit_t" }, { "code": null, "e": 27416, "s": 27407, "text": "suresh07" }, { "code": null, "e": 27430, "s": 27416, "text": "demishassabis" }, { "code": null, "e": 27435, "s": 27430, "text": "Heap" }, { "code": null, "e": 27440, "s": 27435, "text": "Tree" }, { "code": null, "e": 27445, "s": 27440, "text": "Tree" }, { "code": null, "e": 27450, "s": 27445, "text": "Heap" }, { "code": null, "e": 27548, "s": 27450, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27557, "s": 27548, "text": "Comments" }, { "code": null, "e": 27570, "s": 27557, "text": "Old Comments" }, { "code": null, "e": 27630, "s": 27570, "text": "Sliding Window Maximum (Maximum of all subarrays of size k)" }, { "code": null, "e": 27655, "s": 27630, "text": "Building Heap from Array" }, { "code": null, "e": 27690, "s": 27655, "text": "Time Complexity of building a heap" }, { "code": null, "e": 27707, "s": 27690, "text": "Max Heap in Java" }, { "code": null, "e": 27739, "s": 27707, "text": "Insertion and Deletion in Heaps" }, { "code": null, "e": 27774, "s": 27739, "text": "Binary Tree | Set 1 (Introduction)" }, { "code": null, "e": 27803, "s": 27774, "text": "AVL Tree | Set 1 (Insertion)" }, { "code": null, "e": 27846, "s": 27803, "text": "Binary Tree | Set 3 (Types of Binary Tree)" } ]
A friendly Guide for writing Recursive Functions with Python | by Eugenia Anello | Towards Data Science
At first, recursion can seem impossible to learn if it is explained very badly. I still remember how I found it challenging the first time I have met it. To understand it deeply, I needed to do many exercises. It was hard since my mind instinctively solved the problems using iterations, like for loop and while. But with some effort, I was able to understand the basics of recursive function while doing many exercises. In this post, I want to introduce you to what recursion is and show examples of recursive functions with illustrations, that can surely help in understanding the topic in a more efficient way. As you can intuit from the word β€œrecursive”, a function is recursive when it recalls itself. So, the same function is called one or more times. Before writing any recursive function, you need to take into account two cases: Base Case is the most simple case that needs to be considered when solving a problem. It also leads to the end of the recursion.Recursive Case includes the general solution to solve the problem, using the recursive function. Base Case is the most simple case that needs to be considered when solving a problem. It also leads to the end of the recursion. Recursive Case includes the general solution to solve the problem, using the recursive function. For example, let’s try to calculate the factorial of a positive number: In this case, we can identify the two different cases: Base Case: if the number is equal to 0 or 1, the function returns 1 Recursive Case: We consider the remaining cases, where the number is greater than 1. For example, when we calculate 3!, there are some steps to solve this simple problem: call fact(3)fact(3) returns 3*fact(2) , where the new function to call is fact(2)fact(2) returns 2*fact(1) , where the new function to call is fact(1)fact(1) returns 1the problem is solved from step 4 back to the first step call fact(3) fact(3) returns 3*fact(2) , where the new function to call is fact(2) fact(2) returns 2*fact(1) , where the new function to call is fact(1) fact(1) returns 1 the problem is solved from step 4 back to the first step Let’s try the other three examples to understand if you really understood how the recursive function works. Write a recursive function that returns True if and only if the number is even Write a recursive function that returns True if and only if the number is even We need to identify again the two cases: Base Case: if the number is equal to 0, the number is even Recursive Case: We consider all the cases, except for n=0. For example, when n=4. 2. Write a recursive function that sums the elements of a list, which needs to have at least one element The two distinct cases are: Base Case: if there is only one element in the list, the function returns the first element of the list Recursive Case: in the remaining cases, we use the recursive function. Each time, the first of the list is removed. The recursive call can be explained by showing the following steps: sum_list([1,2,3,4]) #1st call with [1,2,3,4] 1 + sum_list([2,3,4]) #2nd call with [2,3,4]1 + 2 + sum_list([3,4]) #3rd call with [3,4]1 + 2 + 3 + sum_list([4]) #4th call with [4]1 + 2 + 3 + 4 #return from 4th call with sum_list([4])=41 + 2 + 7 #return from 3rd call 1 + 9 #return from 2nd call 10 #return from 1st call 3. Given a list (with at least one element), write a recursive function that returns only the even elements This time, we can find that: Base Case: if there is only one element, we return the list if the element is even, otherwise we return []. Recursive Case: in the remaining case, the recursive function is applied. As before, we remove an element from the list each time in the recursive function. Again, we can show that the recursive call is split into different steps: even_elements([0,1,2,3]) #1st call with [0,1,2,3][0]+even_elements([1,2,3]) #2nd call with [1,2,3] [0]+[]+even_elements([2,3]) #3rd call with [2,3][0]+[]+[2]+even_elements([3]) #4th call with [3][0]+[]+[2]+[] #return from 4th call with even_elements([3])=[][0]+[]+[2] #return from 3rd call[0]+[2] #return from 2nd call[0,2] #return from 1st call This overview of the recursive functions is finally ended. Now, you should have a better idea of what recursion is and how to write a recursive function. It can provide some advantages. First, recursion splits a complex task into simplex sub-tasks. Moreover, it’s suitable to deal with Python data structures, like stacks, queues and linked lists. But you should also know that this type of solution is not convenient for every problem. Each recursive call waits for a subsequent recursive call and, then, it can take more times sometimes of the iteration. You should compare the time with iteration and the time with the recursive function to be sure. Anyway, there are well-known applications of recursive functions in the data science field, such as recurrent neural networks, decision trees, random trees and isolation trees, where the recursion is essential to make them work. I hope you found useful this tutorial. Thanks for reading. Have a nice day! Did you appreciate the article? Become a member and get unlimited access to new data science posts every day!
[ { "code": null, "e": 382, "s": 172, "text": "At first, recursion can seem impossible to learn if it is explained very badly. I still remember how I found it challenging the first time I have met it. To understand it deeply, I needed to do many exercises." }, { "code": null, "e": 593, "s": 382, "text": "It was hard since my mind instinctively solved the problems using iterations, like for loop and while. But with some effort, I was able to understand the basics of recursive function while doing many exercises." }, { "code": null, "e": 786, "s": 593, "text": "In this post, I want to introduce you to what recursion is and show examples of recursive functions with illustrations, that can surely help in understanding the topic in a more efficient way." }, { "code": null, "e": 1010, "s": 786, "text": "As you can intuit from the word β€œrecursive”, a function is recursive when it recalls itself. So, the same function is called one or more times. Before writing any recursive function, you need to take into account two cases:" }, { "code": null, "e": 1235, "s": 1010, "text": "Base Case is the most simple case that needs to be considered when solving a problem. It also leads to the end of the recursion.Recursive Case includes the general solution to solve the problem, using the recursive function." }, { "code": null, "e": 1364, "s": 1235, "text": "Base Case is the most simple case that needs to be considered when solving a problem. It also leads to the end of the recursion." }, { "code": null, "e": 1461, "s": 1364, "text": "Recursive Case includes the general solution to solve the problem, using the recursive function." }, { "code": null, "e": 1533, "s": 1461, "text": "For example, let’s try to calculate the factorial of a positive number:" }, { "code": null, "e": 1588, "s": 1533, "text": "In this case, we can identify the two different cases:" }, { "code": null, "e": 1656, "s": 1588, "text": "Base Case: if the number is equal to 0 or 1, the function returns 1" }, { "code": null, "e": 1741, "s": 1656, "text": "Recursive Case: We consider the remaining cases, where the number is greater than 1." }, { "code": null, "e": 1827, "s": 1741, "text": "For example, when we calculate 3!, there are some steps to solve this simple problem:" }, { "code": null, "e": 2051, "s": 1827, "text": "call fact(3)fact(3) returns 3*fact(2) , where the new function to call is fact(2)fact(2) returns 2*fact(1) , where the new function to call is fact(1)fact(1) returns 1the problem is solved from step 4 back to the first step" }, { "code": null, "e": 2064, "s": 2051, "text": "call fact(3)" }, { "code": null, "e": 2134, "s": 2064, "text": "fact(3) returns 3*fact(2) , where the new function to call is fact(2)" }, { "code": null, "e": 2204, "s": 2134, "text": "fact(2) returns 2*fact(1) , where the new function to call is fact(1)" }, { "code": null, "e": 2222, "s": 2204, "text": "fact(1) returns 1" }, { "code": null, "e": 2279, "s": 2222, "text": "the problem is solved from step 4 back to the first step" }, { "code": null, "e": 2387, "s": 2279, "text": "Let’s try the other three examples to understand if you really understood how the recursive function works." }, { "code": null, "e": 2466, "s": 2387, "text": "Write a recursive function that returns True if and only if the number is even" }, { "code": null, "e": 2545, "s": 2466, "text": "Write a recursive function that returns True if and only if the number is even" }, { "code": null, "e": 2586, "s": 2545, "text": "We need to identify again the two cases:" }, { "code": null, "e": 2645, "s": 2586, "text": "Base Case: if the number is equal to 0, the number is even" }, { "code": null, "e": 2727, "s": 2645, "text": "Recursive Case: We consider all the cases, except for n=0. For example, when n=4." }, { "code": null, "e": 2832, "s": 2727, "text": "2. Write a recursive function that sums the elements of a list, which needs to have at least one element" }, { "code": null, "e": 2860, "s": 2832, "text": "The two distinct cases are:" }, { "code": null, "e": 2964, "s": 2860, "text": "Base Case: if there is only one element in the list, the function returns the first element of the list" }, { "code": null, "e": 3080, "s": 2964, "text": "Recursive Case: in the remaining cases, we use the recursive function. Each time, the first of the list is removed." }, { "code": null, "e": 3148, "s": 3080, "text": "The recursive call can be explained by showing the following steps:" }, { "code": null, "e": 3584, "s": 3148, "text": "sum_list([1,2,3,4]) #1st call with [1,2,3,4] 1 + sum_list([2,3,4]) #2nd call with [2,3,4]1 + 2 + sum_list([3,4]) #3rd call with [3,4]1 + 2 + 3 + sum_list([4]) #4th call with [4]1 + 2 + 3 + 4 #return from 4th call with sum_list([4])=41 + 2 + 7 #return from 3rd call 1 + 9 #return from 2nd call 10 #return from 1st call" }, { "code": null, "e": 3692, "s": 3584, "text": "3. Given a list (with at least one element), write a recursive function that returns only the even elements" }, { "code": null, "e": 3721, "s": 3692, "text": "This time, we can find that:" }, { "code": null, "e": 3829, "s": 3721, "text": "Base Case: if there is only one element, we return the list if the element is even, otherwise we return []." }, { "code": null, "e": 3986, "s": 3829, "text": "Recursive Case: in the remaining case, the recursive function is applied. As before, we remove an element from the list each time in the recursive function." }, { "code": null, "e": 4060, "s": 3986, "text": "Again, we can show that the recursive call is split into different steps:" }, { "code": null, "e": 4539, "s": 4060, "text": "even_elements([0,1,2,3]) #1st call with [0,1,2,3][0]+even_elements([1,2,3]) #2nd call with [1,2,3] [0]+[]+even_elements([2,3]) #3rd call with [2,3][0]+[]+[2]+even_elements([3]) #4th call with [3][0]+[]+[2]+[] #return from 4th call with even_elements([3])=[][0]+[]+[2] #return from 3rd call[0]+[2] #return from 2nd call[0,2] #return from 1st call " }, { "code": null, "e": 5497, "s": 4539, "text": "This overview of the recursive functions is finally ended. Now, you should have a better idea of what recursion is and how to write a recursive function. It can provide some advantages. First, recursion splits a complex task into simplex sub-tasks. Moreover, it’s suitable to deal with Python data structures, like stacks, queues and linked lists. But you should also know that this type of solution is not convenient for every problem. Each recursive call waits for a subsequent recursive call and, then, it can take more times sometimes of the iteration. You should compare the time with iteration and the time with the recursive function to be sure. Anyway, there are well-known applications of recursive functions in the data science field, such as recurrent neural networks, decision trees, random trees and isolation trees, where the recursion is essential to make them work. I hope you found useful this tutorial. Thanks for reading. Have a nice day!" } ]
Ruby | Enumerable partition() function - GeeksforGeeks
05 Dec, 2019 The partition() of enumerable is an inbuilt method in Ruby returns two arrays, one containing the elements of the enumerable which return true, while the other contains the elements which returns false. It returns an enumerator if no block is passed. Syntax enu.partition { |obj| block } Parameters: The function takes a block according to which partition is to be done. Return Value: It returns two arrays. Example #1: # Ruby program for partition method in Enumerable # Initialize an enumerableenu1 = [10, 19, 18] # Printsenu1.partition { |num| num>12} Output: [[19, 18], [10]] Example #2: # Ruby program for partition method in Enumerable # Initialize an enumerableenu1 = (1..100) # Printsenu1.partition Output: Enumerator: 1..100:partition Ruby Enumerable-class Ruby-Methods Ruby Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Include v/s Extend in Ruby Ruby | Enumerator each_with_index function Global Variable in Ruby Ruby | Array select() function Ruby | Hash delete() function Ruby | String gsub! Method Ruby | String capitalize() Method How to Make a Custom Array of Hashes in Ruby? Ruby | Case Statement Ruby | Decision Making (if, if-else, if-else-if, ternary) | Set - 1
[ { "code": null, "e": 23297, "s": 23269, "text": "\n05 Dec, 2019" }, { "code": null, "e": 23548, "s": 23297, "text": "The partition() of enumerable is an inbuilt method in Ruby returns two arrays, one containing the elements of the enumerable which return true, while the other contains the elements which returns false. It returns an enumerator if no block is passed." }, { "code": null, "e": 23585, "s": 23548, "text": "Syntax enu.partition { |obj| block }" }, { "code": null, "e": 23668, "s": 23585, "text": "Parameters: The function takes a block according to which partition is to be done." }, { "code": null, "e": 23705, "s": 23668, "text": "Return Value: It returns two arrays." }, { "code": null, "e": 23717, "s": 23705, "text": "Example #1:" }, { "code": "# Ruby program for partition method in Enumerable # Initialize an enumerableenu1 = [10, 19, 18] # Printsenu1.partition { |num| num>12} ", "e": 23860, "s": 23717, "text": null }, { "code": null, "e": 23868, "s": 23860, "text": "Output:" }, { "code": null, "e": 23886, "s": 23868, "text": "[[19, 18], [10]]\n" }, { "code": null, "e": 23898, "s": 23886, "text": "Example #2:" }, { "code": "# Ruby program for partition method in Enumerable # Initialize an enumerableenu1 = (1..100) # Printsenu1.partition ", "e": 24022, "s": 23898, "text": null }, { "code": null, "e": 24030, "s": 24022, "text": "Output:" }, { "code": null, "e": 24060, "s": 24030, "text": "Enumerator: 1..100:partition\n" }, { "code": null, "e": 24082, "s": 24060, "text": "Ruby Enumerable-class" }, { "code": null, "e": 24095, "s": 24082, "text": "Ruby-Methods" }, { "code": null, "e": 24100, "s": 24095, "text": "Ruby" }, { "code": null, "e": 24198, "s": 24100, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24207, "s": 24198, "text": "Comments" }, { "code": null, "e": 24220, "s": 24207, "text": "Old Comments" }, { "code": null, "e": 24247, "s": 24220, "text": "Include v/s Extend in Ruby" }, { "code": null, "e": 24290, "s": 24247, "text": "Ruby | Enumerator each_with_index function" }, { "code": null, "e": 24314, "s": 24290, "text": "Global Variable in Ruby" }, { "code": null, "e": 24345, "s": 24314, "text": "Ruby | Array select() function" }, { "code": null, "e": 24375, "s": 24345, "text": "Ruby | Hash delete() function" }, { "code": null, "e": 24402, "s": 24375, "text": "Ruby | String gsub! Method" }, { "code": null, "e": 24436, "s": 24402, "text": "Ruby | String capitalize() Method" }, { "code": null, "e": 24482, "s": 24436, "text": "How to Make a Custom Array of Hashes in Ruby?" }, { "code": null, "e": 24504, "s": 24482, "text": "Ruby | Case Statement" } ]
How to push a Lua table as an argument?
We may want to push the Lua table as an argument to a code written in C++ which uses Lua as an embedded language and for that case we need to make use of the different API functions that the Lua library provides us with. The Lua code will look something like the code shown below βˆ’ a = { numb = 10, create = function(a) print(a); end, increment = function(self) --self.numb = 11; print(self.numb); end, decrement = function(self,i) self.numb = self.numb-i; print(self.numb); end }; b = a; And the C++ code that will invoke the Lua functions will look like this βˆ’ luaL_openlibs(L); luaL_dofile (L,"main.lua"); lua_getglobal(L, "a"); lua_getfield(L, -1, "increment"); lua_pushvalue(L,-2); // get the table a as the argument lua_pcall(L ,1,0,0); printf(" \nI am done with Lua in C++.\n"); lua_close(L); In the above code, the call to lua_pushvalue(L,-2) is the one that does the magic, as it enables us to pass the table a as the argument. 11 I am done with Lua in C++
[ { "code": null, "e": 1283, "s": 1062, "text": "We may want to push the Lua table as an argument to a code written in C++ which uses Lua as an embedded language and for that case we need to make use of the different API functions that the Lua library provides us with." }, { "code": null, "e": 1344, "s": 1283, "text": "The Lua code will look something like the code shown below βˆ’" }, { "code": null, "e": 1578, "s": 1344, "text": "a = {\n numb = 10,\n create = function(a)\n print(a);\n end,\nincrement = function(self)\n --self.numb = 11;\n print(self.numb);\nend,\ndecrement = function(self,i)\n self.numb = self.numb-i;\n print(self.numb);\nend\n};\nb = a;" }, { "code": null, "e": 1652, "s": 1578, "text": "And the C++ code that will invoke the Lua functions will look like this βˆ’" }, { "code": null, "e": 1889, "s": 1652, "text": "luaL_openlibs(L);\nluaL_dofile (L,\"main.lua\");\nlua_getglobal(L, \"a\");\nlua_getfield(L, -1, \"increment\");\nlua_pushvalue(L,-2); // get the table a as the argument\nlua_pcall(L ,1,0,0);\nprintf(\" \\nI am done with Lua in C++.\\n\");\nlua_close(L);" }, { "code": null, "e": 2026, "s": 1889, "text": "In the above code, the call to lua_pushvalue(L,-2) is the one that does the magic, as it enables us to pass the table a as the argument." }, { "code": null, "e": 2055, "s": 2026, "text": "11\nI am done with Lua in C++" } ]
Types of variable, it's graphical representation | Towards Data Science
β€œYou can have data without information, but you cannot have information without data.” β€” Daniel Keys Moran Data is the raw material for the information age. We can not think of modern technology without data. If we have data we are able to get tons of information about any incidence or space. Today’s world has quite a hunger for data. It can be compared with oil for modern technologies. But it does not make any sense if you don’t know the data. Firstly, we must be familiar with the data we are exploring. If we don’t know the data well, our system or analysis model building on top of the data will be ended up with a useless analysis or system. For this reason, we need to be familiar with data types and their representation techniques. The parameter holds the data is known as a variable in statistics. One dataset may describe the stock market, others may describe the population, employee data, and so on. It varies with the system. The properties with varying values are variables. This article will help you in this regard. All the variable types and possible graphical representations of the variables will be shown here. This would be the best article for you if you are interested in it. Let’s get started. Types of variableLevels of MeasurementData Representation (Bar Chart, Pie Chart, Pareto Diagram)with python Types of variable Levels of Measurement Data Representation (Bar Chart, Pie Chart, Pareto Diagram)with python The data source is vast. We may find different types of data from different data sources. But it is important to know about the characteristics of the data. And variables define the characteristics of data. There are some parameters by which we can easily divide or categorize the variables. Basically there are two types of variables. Mainly two variable types are i) categorical and ii) numerical i. Categorical: Categorical variables represent types of data which may be divided into groups. It is also known as qualitative variable. Examples: Car Brand is a categorical variable that holds categorical data like Audi, Toyota, BMW, etc. Answer is a categorical variable that holds categorical data yes/no. ii.Numerical: All the variables representing in number is known as the numerical variable. It is also known as quantitative variable. It can be a)discrete, or b)continuous. a) Discrete: In a simple way, all the variables which contain countable data is known as the discrete variable. Example: Variable -No of Children, SAT Score, Population etc., all of these variables contain discrete data. b)Continuous: The variable which is uncountable is known as the continuous variable. It takes forever to count and the counting process will never end. Example: Age is a continuous variable. But why? Suppose, your age is 25 years, 2 months, 10 days, 7 hours, 40 seconds, 44 milliseconds, 10 nanoseconds, 99 picoseconds...and so on. It will never end. Another example could be β€œAverage ” variable. Take an average number of 1.232343542543245.......... never ends. A quick comparison of the variables. According to Wikipedia, β€œLevel of measurement or scale of measure is a classification that describes the nature of the information within the values assigned to variables.” Psychologist Stanley Smith Stevens developed the best-known classification with four levels, or scales, of measurement: i. nominal, ii.ordinal, iii. interval, iv. ratio The nominal and ordinal scales are used to measure the qualitative/categorical variable. On the other hand, the interval and ratio scales are used to measure the quantitative/ numerical variables. i. Nominal: It is a Latin word that means name only. The nominal level represents the categories that can not be put in any order. This level represents only the individual category or name. It only represents quality. With a nominal scale, we may identify the difference between two individuals within the variable. It doesn’t provide any idea about the size of the difference. Example: Suppose, a variable represents Car Brandβ†’ Audi, Toyota, BMW, etc. We can not order these names in any manner. So, such types of variables are in the level of nominal measurement. ii. Ordinal: It is an ordered level or rank. It indicates the categorical variables that can be put in order. With this scale, we can determine the direction of the difference of a variable, but we can not determine the size of the difference. Example: We have a variable named Height represents the height of the people with short, medium, and tall. We can easily order these values tall β†’ medium β†’ short. This order provides a good intuition about the direction of difference but it doesn’t provide any clue to identify how much the height differs from each other. iii. Interval: A variable that represents an equal interval among the levels and can be represented as a real number is known as an interval scale. It not only classifies and orders the measurements, but it also specifies that the distances between each interval on the scale are equivalent along the scale from low interval to high interval. Example: Temperature is a variable where the interval between 10-degree centigrade, and 20-degree, 70-degree centigrade, and 80-degree are the same. Marks of the examination, height, time, etc. can be a good example of an interval scale. iv. Ratio: It has all the properties like the interval scale. Additionally, it must satisfy a meaningful zero in the scale. Let’s make it clear. Suppose, we are considering the body temperature in Β°C and Β°F scale. We found that two persons’ body temperature is 10Β°C and 20Β°C or 10Β°F and 20Β°F respectively. We can not say that the 2nd person’s body temperature is 2 times higher than the 1st one. Because 0Β°C and 0Β°F are not the true zero that means it doesn’t mean the absence of temperature. If you want to represent temperature as a ratio scale then we must consider the Kelvin scale as 0 degree Kelvin indicates the absence of temperature. Here, we will discuss the Bar chart, Pie Chart, and Pareto Diagram to represent the variables. Suppose, we have a dataset of a car selling market and we are going to analyze the Car Brand variable. At first, we calculate the frequency of different Car Brand. It seems something like below. Let’s convert it to a dataframe. As we are going to analyze with this demo data for graphical representation. The frequency represents the count of sold cars of each brand. You can do the same with any dataset. Let's convert the image with a pandas dataframe. import pandas as pdimport matplotlib.pyplot as pltdf=pd.DataFrame({"Brand":['Audi',"BMW","Mercedes"],"Frequency":[124,98,113]}) Compute relative frequency Relative frequency indicates the distribution of individual frequency in percentage. Relative frequency(%)=(Individual Frequency/total frequency)*100 df['Relative Frequency(%)']=round((df.Frequency/sum(df.Frequency))*100,2) We have added a relative frequency column in our main dataset. Let’s draw a bar chart with the frequency. Bar Chart: import matplotlib.pyplot as pltfig,ax=plt.subplots()var=plt.bar(df.Brand, df.Frequency, align='center', alpha=0.5)#this loop is used to represent frequency on each barfor idx,rect in enumerate(var): height = rect.get_height() ax.text(rect.get_x() + rect.get_width()/2., 1.01*height, df.Frequency[idx], ha='center', va='bottom', rotation=0)#adding labels and titleplt.ylabel('Frequency')plt.xlabel('Brand Name')plt.title('Car Sales Statistics')plt.show() This represents a bar chart of the frequency. We can also represent the distribution of the frequency among different categorical data with Pie Chart. fig = plt.figure()ax = fig.add_axes([0,0,1,1])ax.axis('equal')ax.pie(df.Frequency, labels = df.Brand,autopct='%1.2f%%')plt.show() Pie chart with relative frequency. The Pareto diagram is a special type of bar chart where the categories are shown in descending order of frequency, and a separate curve shows the cumulative frequency. Let’s draw the diagram with python. from matplotlib.ticker import PercentFormatterdf = df.sort_values(by='Frequency',ascending=False)df["Cumulative Frequency"] = round(df["Frequency"].cumsum()/df["Frequency"].sum()*100,2)fig, ax = plt.subplots(figsize=(10,5))ax.bar(df.Brand, df["Frequency"], color="blue")ax2 = ax.twinx()ax2.plot(df.Brand, df["Cumulative Frequency"], color="red", marker="D", ms=7)ax2.yaxis.set_major_formatter(PercentFormatter())ax.tick_params(axis="y", colors="black")ax2.tick_params(axis="y", colors="black")ax2.set_ylim(0,105)ax.set_ylim(0,130)plt.show() Pareto Diagram for the frequency table. So far so good. We are at the very end of the article. We can also represent the numerical data with a bar chart, pie chart, and Pareto diagram. If we want to find the frequency of the numerical data, we may found a frequency of 1 for each data. But it is not feasible to represent the data. So, what can I do? We can divide the numerical data into different intervals and then count the frequency of the data within the interval. Let’s try to have better intuition with a python dataframe. df=pd.DataFrame({"data":[10,40,20,5,30,100,110,70,80,63,55,32,45,85,87,77,65,44,33,4,56,90,95,96]}) If we want to count the frequency, most of the frequency of the data will be 1. df['data'].value_counts() This gives the frequency.. Now, if we want to represent the above frequency with bar chart, pie chart it doesn’t provide any information. So, we need to count the frequency within intervals. Suppose, we divide the data into 5 equal intervals. d=df['data'].value_counts(bins = 5).sort_index() It shows the distribution of the frequency below. Well, we are able to apply the bar chart, pie chart, and Pareto diagram to represent the numerical variable’s frequency. Try to follow the above techniques to draw the chart and diagram for the numerical variable. It’s your task. The denominator variable is very much important for a data science task. At the very beginning of our analysis, we must have a look at it. Most often we forget to take it into account. Hopefully, this few minutes read provides you a good intuition about the variables, it’s types and so on. You will get the full jupyter notebook file in Github. Please, let me know if you have any problems in the comment section. [N.B: I will try my best to publish all the basic knowledge of statistics for data science. If you are interested, you may read the first part of statistical knowledge for data science~ Sampling. Statistics~ Part-1 ]
[ { "code": null, "e": 279, "s": 172, "text": "β€œYou can have data without information, but you cannot have information without data.” β€” Daniel Keys Moran" }, { "code": null, "e": 562, "s": 279, "text": "Data is the raw material for the information age. We can not think of modern technology without data. If we have data we are able to get tons of information about any incidence or space. Today’s world has quite a hunger for data. It can be compared with oil for modern technologies." }, { "code": null, "e": 916, "s": 562, "text": "But it does not make any sense if you don’t know the data. Firstly, we must be familiar with the data we are exploring. If we don’t know the data well, our system or analysis model building on top of the data will be ended up with a useless analysis or system. For this reason, we need to be familiar with data types and their representation techniques." }, { "code": null, "e": 1165, "s": 916, "text": "The parameter holds the data is known as a variable in statistics. One dataset may describe the stock market, others may describe the population, employee data, and so on. It varies with the system. The properties with varying values are variables." }, { "code": null, "e": 1394, "s": 1165, "text": "This article will help you in this regard. All the variable types and possible graphical representations of the variables will be shown here. This would be the best article for you if you are interested in it. Let’s get started." }, { "code": null, "e": 1502, "s": 1394, "text": "Types of variableLevels of MeasurementData Representation (Bar Chart, Pie Chart, Pareto Diagram)with python" }, { "code": null, "e": 1520, "s": 1502, "text": "Types of variable" }, { "code": null, "e": 1542, "s": 1520, "text": "Levels of Measurement" }, { "code": null, "e": 1612, "s": 1542, "text": "Data Representation (Bar Chart, Pie Chart, Pareto Diagram)with python" }, { "code": null, "e": 1948, "s": 1612, "text": "The data source is vast. We may find different types of data from different data sources. But it is important to know about the characteristics of the data. And variables define the characteristics of data. There are some parameters by which we can easily divide or categorize the variables. Basically there are two types of variables." }, { "code": null, "e": 2011, "s": 1948, "text": "Mainly two variable types are i) categorical and ii) numerical" }, { "code": null, "e": 2149, "s": 2011, "text": "i. Categorical: Categorical variables represent types of data which may be divided into groups. It is also known as qualitative variable." }, { "code": null, "e": 2321, "s": 2149, "text": "Examples: Car Brand is a categorical variable that holds categorical data like Audi, Toyota, BMW, etc. Answer is a categorical variable that holds categorical data yes/no." }, { "code": null, "e": 2494, "s": 2321, "text": "ii.Numerical: All the variables representing in number is known as the numerical variable. It is also known as quantitative variable. It can be a)discrete, or b)continuous." }, { "code": null, "e": 2606, "s": 2494, "text": "a) Discrete: In a simple way, all the variables which contain countable data is known as the discrete variable." }, { "code": null, "e": 2715, "s": 2606, "text": "Example: Variable -No of Children, SAT Score, Population etc., all of these variables contain discrete data." }, { "code": null, "e": 2867, "s": 2715, "text": "b)Continuous: The variable which is uncountable is known as the continuous variable. It takes forever to count and the counting process will never end." }, { "code": null, "e": 3178, "s": 2867, "text": "Example: Age is a continuous variable. But why? Suppose, your age is 25 years, 2 months, 10 days, 7 hours, 40 seconds, 44 milliseconds, 10 nanoseconds, 99 picoseconds...and so on. It will never end. Another example could be β€œAverage ” variable. Take an average number of 1.232343542543245.......... never ends." }, { "code": null, "e": 3215, "s": 3178, "text": "A quick comparison of the variables." }, { "code": null, "e": 3388, "s": 3215, "text": "According to Wikipedia, β€œLevel of measurement or scale of measure is a classification that describes the nature of the information within the values assigned to variables.”" }, { "code": null, "e": 3557, "s": 3388, "text": "Psychologist Stanley Smith Stevens developed the best-known classification with four levels, or scales, of measurement: i. nominal, ii.ordinal, iii. interval, iv. ratio" }, { "code": null, "e": 3754, "s": 3557, "text": "The nominal and ordinal scales are used to measure the qualitative/categorical variable. On the other hand, the interval and ratio scales are used to measure the quantitative/ numerical variables." }, { "code": null, "e": 3945, "s": 3754, "text": "i. Nominal: It is a Latin word that means name only. The nominal level represents the categories that can not be put in any order. This level represents only the individual category or name." }, { "code": null, "e": 3973, "s": 3945, "text": "It only represents quality." }, { "code": null, "e": 4071, "s": 3973, "text": "With a nominal scale, we may identify the difference between two individuals within the variable." }, { "code": null, "e": 4133, "s": 4071, "text": "It doesn’t provide any idea about the size of the difference." }, { "code": null, "e": 4321, "s": 4133, "text": "Example: Suppose, a variable represents Car Brandβ†’ Audi, Toyota, BMW, etc. We can not order these names in any manner. So, such types of variables are in the level of nominal measurement." }, { "code": null, "e": 4565, "s": 4321, "text": "ii. Ordinal: It is an ordered level or rank. It indicates the categorical variables that can be put in order. With this scale, we can determine the direction of the difference of a variable, but we can not determine the size of the difference." }, { "code": null, "e": 4888, "s": 4565, "text": "Example: We have a variable named Height represents the height of the people with short, medium, and tall. We can easily order these values tall β†’ medium β†’ short. This order provides a good intuition about the direction of difference but it doesn’t provide any clue to identify how much the height differs from each other." }, { "code": null, "e": 5231, "s": 4888, "text": "iii. Interval: A variable that represents an equal interval among the levels and can be represented as a real number is known as an interval scale. It not only classifies and orders the measurements, but it also specifies that the distances between each interval on the scale are equivalent along the scale from low interval to high interval." }, { "code": null, "e": 5469, "s": 5231, "text": "Example: Temperature is a variable where the interval between 10-degree centigrade, and 20-degree, 70-degree centigrade, and 80-degree are the same. Marks of the examination, height, time, etc. can be a good example of an interval scale." }, { "code": null, "e": 5614, "s": 5469, "text": "iv. Ratio: It has all the properties like the interval scale. Additionally, it must satisfy a meaningful zero in the scale. Let’s make it clear." }, { "code": null, "e": 6112, "s": 5614, "text": "Suppose, we are considering the body temperature in Β°C and Β°F scale. We found that two persons’ body temperature is 10Β°C and 20Β°C or 10Β°F and 20Β°F respectively. We can not say that the 2nd person’s body temperature is 2 times higher than the 1st one. Because 0Β°C and 0Β°F are not the true zero that means it doesn’t mean the absence of temperature. If you want to represent temperature as a ratio scale then we must consider the Kelvin scale as 0 degree Kelvin indicates the absence of temperature." }, { "code": null, "e": 6207, "s": 6112, "text": "Here, we will discuss the Bar chart, Pie Chart, and Pareto Diagram to represent the variables." }, { "code": null, "e": 6402, "s": 6207, "text": "Suppose, we have a dataset of a car selling market and we are going to analyze the Car Brand variable. At first, we calculate the frequency of different Car Brand. It seems something like below." }, { "code": null, "e": 6662, "s": 6402, "text": "Let’s convert it to a dataframe. As we are going to analyze with this demo data for graphical representation. The frequency represents the count of sold cars of each brand. You can do the same with any dataset. Let's convert the image with a pandas dataframe." }, { "code": null, "e": 6790, "s": 6662, "text": "import pandas as pdimport matplotlib.pyplot as pltdf=pd.DataFrame({\"Brand\":['Audi',\"BMW\",\"Mercedes\"],\"Frequency\":[124,98,113]})" }, { "code": null, "e": 6817, "s": 6790, "text": "Compute relative frequency" }, { "code": null, "e": 6902, "s": 6817, "text": "Relative frequency indicates the distribution of individual frequency in percentage." }, { "code": null, "e": 6967, "s": 6902, "text": "Relative frequency(%)=(Individual Frequency/total frequency)*100" }, { "code": null, "e": 7041, "s": 6967, "text": "df['Relative Frequency(%)']=round((df.Frequency/sum(df.Frequency))*100,2)" }, { "code": null, "e": 7104, "s": 7041, "text": "We have added a relative frequency column in our main dataset." }, { "code": null, "e": 7147, "s": 7104, "text": "Let’s draw a bar chart with the frequency." }, { "code": null, "e": 7158, "s": 7147, "text": "Bar Chart:" }, { "code": null, "e": 7656, "s": 7158, "text": "import matplotlib.pyplot as pltfig,ax=plt.subplots()var=plt.bar(df.Brand, df.Frequency, align='center', alpha=0.5)#this loop is used to represent frequency on each barfor idx,rect in enumerate(var): height = rect.get_height() ax.text(rect.get_x() + rect.get_width()/2., 1.01*height, df.Frequency[idx], ha='center', va='bottom', rotation=0)#adding labels and titleplt.ylabel('Frequency')plt.xlabel('Brand Name')plt.title('Car Sales Statistics')plt.show()" }, { "code": null, "e": 7702, "s": 7656, "text": "This represents a bar chart of the frequency." }, { "code": null, "e": 7807, "s": 7702, "text": "We can also represent the distribution of the frequency among different categorical data with Pie Chart." }, { "code": null, "e": 7937, "s": 7807, "text": "fig = plt.figure()ax = fig.add_axes([0,0,1,1])ax.axis('equal')ax.pie(df.Frequency, labels = df.Brand,autopct='%1.2f%%')plt.show()" }, { "code": null, "e": 7972, "s": 7937, "text": "Pie chart with relative frequency." }, { "code": null, "e": 8140, "s": 7972, "text": "The Pareto diagram is a special type of bar chart where the categories are shown in descending order of frequency, and a separate curve shows the cumulative frequency." }, { "code": null, "e": 8176, "s": 8140, "text": "Let’s draw the diagram with python." }, { "code": null, "e": 8717, "s": 8176, "text": "from matplotlib.ticker import PercentFormatterdf = df.sort_values(by='Frequency',ascending=False)df[\"Cumulative Frequency\"] = round(df[\"Frequency\"].cumsum()/df[\"Frequency\"].sum()*100,2)fig, ax = plt.subplots(figsize=(10,5))ax.bar(df.Brand, df[\"Frequency\"], color=\"blue\")ax2 = ax.twinx()ax2.plot(df.Brand, df[\"Cumulative Frequency\"], color=\"red\", marker=\"D\", ms=7)ax2.yaxis.set_major_formatter(PercentFormatter())ax.tick_params(axis=\"y\", colors=\"black\")ax2.tick_params(axis=\"y\", colors=\"black\")ax2.set_ylim(0,105)ax.set_ylim(0,130)plt.show()" }, { "code": null, "e": 8757, "s": 8717, "text": "Pareto Diagram for the frequency table." }, { "code": null, "e": 8812, "s": 8757, "text": "So far so good. We are at the very end of the article." }, { "code": null, "e": 9068, "s": 8812, "text": "We can also represent the numerical data with a bar chart, pie chart, and Pareto diagram. If we want to find the frequency of the numerical data, we may found a frequency of 1 for each data. But it is not feasible to represent the data. So, what can I do?" }, { "code": null, "e": 9248, "s": 9068, "text": "We can divide the numerical data into different intervals and then count the frequency of the data within the interval. Let’s try to have better intuition with a python dataframe." }, { "code": null, "e": 9348, "s": 9248, "text": "df=pd.DataFrame({\"data\":[10,40,20,5,30,100,110,70,80,63,55,32,45,85,87,77,65,44,33,4,56,90,95,96]})" }, { "code": null, "e": 9428, "s": 9348, "text": "If we want to count the frequency, most of the frequency of the data will be 1." }, { "code": null, "e": 9454, "s": 9428, "text": "df['data'].value_counts()" }, { "code": null, "e": 9481, "s": 9454, "text": "This gives the frequency.." }, { "code": null, "e": 9697, "s": 9481, "text": "Now, if we want to represent the above frequency with bar chart, pie chart it doesn’t provide any information. So, we need to count the frequency within intervals. Suppose, we divide the data into 5 equal intervals." }, { "code": null, "e": 9746, "s": 9697, "text": "d=df['data'].value_counts(bins = 5).sort_index()" }, { "code": null, "e": 9796, "s": 9746, "text": "It shows the distribution of the frequency below." }, { "code": null, "e": 10026, "s": 9796, "text": "Well, we are able to apply the bar chart, pie chart, and Pareto diagram to represent the numerical variable’s frequency. Try to follow the above techniques to draw the chart and diagram for the numerical variable. It’s your task." }, { "code": null, "e": 10372, "s": 10026, "text": "The denominator variable is very much important for a data science task. At the very beginning of our analysis, we must have a look at it. Most often we forget to take it into account. Hopefully, this few minutes read provides you a good intuition about the variables, it’s types and so on. You will get the full jupyter notebook file in Github." }, { "code": null, "e": 10441, "s": 10372, "text": "Please, let me know if you have any problems in the comment section." } ]
Integer Programming in Python | by Freddy Boulton | Towards Data Science
Integer Programming (IP) problems are optimization problems where all of the variables are constrained to be integers. IP problems are useful mathematical models for how to best allocate one’s resources. Let’s say you’re organizing a marketing campaign for a political candidate and you’re deciding which constituents to send marketing materials to. You can send each constituent a catchy flyer, a detailed pamphlet explaining your agenda, or a bumper sticker (or a combination of the three). If you had a way to measure how likely someone is to vote for your candidate based on the marketing materials they received, how would you decide which materials to send while also being mindful to not exceed your supply? Traditional optimization algorithms assume the variables can take on floating point values, but in our case, it isn’t reasonable to send someone half a bumper sticker or three quarters of a pamphlet. We’ll use a special python package called cvxpy to solve our problem such that the solutions make sense. I’ll show you how to use cvxpy to solve the political candidate problem, but I’ll start first a simpler problem called the knapsack problem to show you how the cvxpy syntax works. Let’s pretend you’re going on a hike and you’re planning which objects you can take with you. Each object has a weight in pounds w_i and will give you u_i units of utility. You’d like to take all of them but your knapsack can only carry P pounds. Suppose you can either take an object or not. Your goal is to maximize your utility without exceeding the weight limit of your bag. A cvxpy problem has three parts: Creating the variable: We will represent our choice mathematically with a vector of 1’s and 0’s. A 1 will mean we’ve selected that object and a 0 will mean we’ve left it home. We construct a variable that can only take 1’s and 0’s with the cvxpy.Bool object.Specifying the constraints: We only need to make sure that the sum of our objects doesn’t exceed the weight limit P. We can compute the total weight of our objects with the dot product of the selection vector and the weights vector. Note that cvxpy overloads the * operator to perform matrix multiplication.Formulating the objective function: We want to find the selection that maximizes our utility. The utility of any given selection is the dot product of the selection vector and the utility vector. Creating the variable: We will represent our choice mathematically with a vector of 1’s and 0’s. A 1 will mean we’ve selected that object and a 0 will mean we’ve left it home. We construct a variable that can only take 1’s and 0’s with the cvxpy.Bool object. Specifying the constraints: We only need to make sure that the sum of our objects doesn’t exceed the weight limit P. We can compute the total weight of our objects with the dot product of the selection vector and the weights vector. Note that cvxpy overloads the * operator to perform matrix multiplication. Formulating the objective function: We want to find the selection that maximizes our utility. The utility of any given selection is the dot product of the selection vector and the utility vector. Once we have a cost function and constraints, we pass them to a cvxpy Problem object. In this case, we’ve told cvxpy that we’re trying to maximize utility with cvxpy.Maximize. To solve the problem, we just have to run the solve method of our problem object. Afterwards, we can inspect the optimal value of our selection vector by looking at its value attribute. print(selection.value)matrix([[1.], [1.], [1.], [1.], [0.], [1.], [0.], [0.], [0.], [0.]]) We’ve selected the first four items and the sixth one. This makes sense because these have high ratio of utility to weight without weighing too much. Now that we’ve covered basic cvxpy syntax, we can solve the marketing optimization problem for our political candidate. Let’s say we had a model that takes in a constituent’s attributes and predicts the probability they will vote for our candidate for each combination of marketing materials we send them. I’m using fake data here but let’s pretend the model outputs the following probabilities: print(test_probs[0:5])array([[0.0001, 0.0001, 0.3 , 0.0001, 0.2 , 0.0001, 0.2 , 0.3 ], [0.1 , 0.1 , 0.1 , 0.2 , 0.2 , 0.2 , 0.1 , 0.0001], [0.1 , 0.0001, 0.2 , 0.0001, 0.1 , 0.2 , 0.0001, 0.4 ], [0.3 , 0.0001, 0.0001, 0.2 , 0.1 , 0.2 , 0.2 , 0.0001], [0.2 , 0.3 , 0.1 , 0.0001, 0.2 , 0.1 , 0.1 , 0.0001]]) There are eight total probabilities per constituent because there are eight total combinations of materials we could send an individual. Here’s what the entries of each 1 x 8 vector represent: [1 flyer, 1 pamphlet, 1 bumper sticker, flyer and pamphlet, flyer and bumper sticker, pamphlet and bumper sticker, all three, none]. For example, the first constituent has a 0.0001 probability of voting for our candidate if he received a flyer or pamphlet, but a 0.3 probability of voting for our candidate if we sent him a bumper sticker. Before we get into the cvxpy code, we’ll turn these probabilities into costs by taking the negative log. This makes the math work out nicer and it has a nice interpretation: if the probability is close to 1, the negative log will be close to 0. This means that there is little cost in sending that particular combination of materials to that constituent since we are certain it will lead them to vote for our candidate. Vice versa if the probability is close to 0. #clipping so that we don't take log of 0 or 1test_probs = np.clip(test_probs, 0.0001, 0.9999)#turning into costsmodel_costs = -np.log10(test_probs) Finally, let’s say that we cannot send more than 150 flyers, 80 pamphlets, and 25 bumper stickers. supply = np.atleast_2d([150, 80, 25]) Now that we’ve done all the set-up, we can get to the fun part: Creating the variable: We’ll use a cvxpy.Bool object again because we can only make binary choices here. We’ll specify that it must be the same shape as our probability matrix: Creating the variable: We’ll use a cvxpy.Bool object again because we can only make binary choices here. We’ll specify that it must be the same shape as our probability matrix: selection = cvxpy.Bool(*test_probs.shape) 2. Specifying the constraints: Our selection variable will only tell us which of the 8 choices we’ve made for each constituent, but it won’t tell how many total materials we’ve decided to send to them. We need a way to turn our 1 x 8 selection vector into a 1 x 3 vector. We can do so by multiplying by the selection vector by the following matrix: TRANSFORMER = np.array([[1,0,0], [0,1,0], [0,0,1], [1,1,0], [1,0,1], [0,1,1], [1,1,1], [0,0,0]]) If this part is a little confusing, work out the following example: print(np.dot(np.array([0,0,0,1,0,0,0,0]), TRANSFORMER))array([1, 1, 0]) The fourth entry of our decision vector represents sending a flyer and pamphlet to the constituent and multiplying by TRANSFORMER tells us just that! So we’ll tell cvxpy that multiplying our selection matrix by transformer can’t exceed our supply: supply_constraint = cvxpy.sum_entries(selection * TRANSFORMER, axis=0) <= supply I’m summing over the rows with cvxpy.sum_entries to aggregate the total number of materials we’ve sent across all constituents. We also need to ensure we’re making exactly once choice per constituent, otherwise the solver can attain zero cost by not sending anyone anything. # We must make our choice per constituent# remember that the last column is for "no materials"feasibility_constraint = cvxpy.sum_entries(selection, axis=1) == 1constraints = [supply_constraint, feasibility_constraint] 3. Formulating the objective function: The total cost of our assignment will be the sum of the costs we’ve incurred for each constituent. We’ll use the cvxpy.mul_elemwise function to multiply our selection matrix with our cost matrix, this will select the cost for each constituent, and the cvxpy.sum_elemwise function will compute the total cost by adding up the individual costs. cost = cvxpy.sum_entries(cvxpy.mul_elemwise(model_costs, selection)) The final step is to create the cvxpy.Problem and solve it. # Solving the problemproblem = cvxpy.Problem(cvxpy.Minimize(cost), constraints=constraints)problem.solve(solver=cvxpy.GLPK_MI) That’s it! Below is a snapshot of what our final assignments look like. We decided not to send any materials to the first constituent. This makes sense because the probability of them voting for our candidate is 0.3 whether we send them a bumper sticker or nothing at all. It also turns out that the optimal assignment exhausts our supply of pamphlets and bumper stickers but only uses 83 of the total 150 flyers. We should tell our candidate that her flyers aren’t as persuasive as she thinks. print(hard_assignments.value[0:5])matrix([[0., 0., 0., 0., 0., 0., 0., 1.], [0., 0., 0., 1., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 0., 0., 1.], [1., 0., 0., 0., 0., 0., 0., 0.], [1., 0., 0., 0., 0., 0., 0., 0.]])print(np.dot(hard_assignments.value, TRANSFORMER).sum(axis=0))matrix([[83., 80., 25.]]) Here is all the code packaged together: I hope you’ve enjoyed learning about integer programming problems and how to solve them in Python. Believe it or not, we’ve covered about 80% of the cvxpy knowledge you need to go out and solve your own optimization problems. I encourage you to read the official documentation to learn about the remaining 20%. CVXPY can solve more than just IP problems, check out their tutorials page to see what other problems cvxpy can solve. To install cvxpy, follow the directions on their website. I would also install cvxopt to make sure all the solvers that come packaged with cvxpy will work on your machine We’ve specified that cvxpy should use the GLPK_MI solver in the solve method. This is a special solver designed for IP problems. Before you solve your own problem, consult this table to see which prepackaged cvpxy solver is best suited to your problem.
[ { "code": null, "e": 886, "s": 171, "text": "Integer Programming (IP) problems are optimization problems where all of the variables are constrained to be integers. IP problems are useful mathematical models for how to best allocate one’s resources. Let’s say you’re organizing a marketing campaign for a political candidate and you’re deciding which constituents to send marketing materials to. You can send each constituent a catchy flyer, a detailed pamphlet explaining your agenda, or a bumper sticker (or a combination of the three). If you had a way to measure how likely someone is to vote for your candidate based on the marketing materials they received, how would you decide which materials to send while also being mindful to not exceed your supply?" }, { "code": null, "e": 1191, "s": 886, "text": "Traditional optimization algorithms assume the variables can take on floating point values, but in our case, it isn’t reasonable to send someone half a bumper sticker or three quarters of a pamphlet. We’ll use a special python package called cvxpy to solve our problem such that the solutions make sense." }, { "code": null, "e": 1371, "s": 1191, "text": "I’ll show you how to use cvxpy to solve the political candidate problem, but I’ll start first a simpler problem called the knapsack problem to show you how the cvxpy syntax works." }, { "code": null, "e": 1750, "s": 1371, "text": "Let’s pretend you’re going on a hike and you’re planning which objects you can take with you. Each object has a weight in pounds w_i and will give you u_i units of utility. You’d like to take all of them but your knapsack can only carry P pounds. Suppose you can either take an object or not. Your goal is to maximize your utility without exceeding the weight limit of your bag." }, { "code": null, "e": 1783, "s": 1750, "text": "A cvxpy problem has three parts:" }, { "code": null, "e": 2544, "s": 1783, "text": "Creating the variable: We will represent our choice mathematically with a vector of 1’s and 0’s. A 1 will mean we’ve selected that object and a 0 will mean we’ve left it home. We construct a variable that can only take 1’s and 0’s with the cvxpy.Bool object.Specifying the constraints: We only need to make sure that the sum of our objects doesn’t exceed the weight limit P. We can compute the total weight of our objects with the dot product of the selection vector and the weights vector. Note that cvxpy overloads the * operator to perform matrix multiplication.Formulating the objective function: We want to find the selection that maximizes our utility. The utility of any given selection is the dot product of the selection vector and the utility vector." }, { "code": null, "e": 2803, "s": 2544, "text": "Creating the variable: We will represent our choice mathematically with a vector of 1’s and 0’s. A 1 will mean we’ve selected that object and a 0 will mean we’ve left it home. We construct a variable that can only take 1’s and 0’s with the cvxpy.Bool object." }, { "code": null, "e": 3111, "s": 2803, "text": "Specifying the constraints: We only need to make sure that the sum of our objects doesn’t exceed the weight limit P. We can compute the total weight of our objects with the dot product of the selection vector and the weights vector. Note that cvxpy overloads the * operator to perform matrix multiplication." }, { "code": null, "e": 3307, "s": 3111, "text": "Formulating the objective function: We want to find the selection that maximizes our utility. The utility of any given selection is the dot product of the selection vector and the utility vector." }, { "code": null, "e": 3669, "s": 3307, "text": "Once we have a cost function and constraints, we pass them to a cvxpy Problem object. In this case, we’ve told cvxpy that we’re trying to maximize utility with cvxpy.Maximize. To solve the problem, we just have to run the solve method of our problem object. Afterwards, we can inspect the optimal value of our selection vector by looking at its value attribute." }, { "code": null, "e": 3823, "s": 3669, "text": "print(selection.value)matrix([[1.], [1.], [1.], [1.], [0.], [1.], [0.], [0.], [0.], [0.]])" }, { "code": null, "e": 3973, "s": 3823, "text": "We’ve selected the first four items and the sixth one. This makes sense because these have high ratio of utility to weight without weighing too much." }, { "code": null, "e": 4369, "s": 3973, "text": "Now that we’ve covered basic cvxpy syntax, we can solve the marketing optimization problem for our political candidate. Let’s say we had a model that takes in a constituent’s attributes and predicts the probability they will vote for our candidate for each combination of marketing materials we send them. I’m using fake data here but let’s pretend the model outputs the following probabilities:" }, { "code": null, "e": 4753, "s": 4369, "text": "print(test_probs[0:5])array([[0.0001, 0.0001, 0.3 , 0.0001, 0.2 , 0.0001, 0.2 , 0.3 ], [0.1 , 0.1 , 0.1 , 0.2 , 0.2 , 0.2 , 0.1 , 0.0001], [0.1 , 0.0001, 0.2 , 0.0001, 0.1 , 0.2 , 0.0001, 0.4 ], [0.3 , 0.0001, 0.0001, 0.2 , 0.1 , 0.2 , 0.2 , 0.0001], [0.2 , 0.3 , 0.1 , 0.0001, 0.2 , 0.1 , 0.1 , 0.0001]])" }, { "code": null, "e": 4946, "s": 4753, "text": "There are eight total probabilities per constituent because there are eight total combinations of materials we could send an individual. Here’s what the entries of each 1 x 8 vector represent:" }, { "code": null, "e": 5079, "s": 4946, "text": "[1 flyer, 1 pamphlet, 1 bumper sticker, flyer and pamphlet, flyer and bumper sticker, pamphlet and bumper sticker, all three, none]." }, { "code": null, "e": 5286, "s": 5079, "text": "For example, the first constituent has a 0.0001 probability of voting for our candidate if he received a flyer or pamphlet, but a 0.3 probability of voting for our candidate if we sent him a bumper sticker." }, { "code": null, "e": 5751, "s": 5286, "text": "Before we get into the cvxpy code, we’ll turn these probabilities into costs by taking the negative log. This makes the math work out nicer and it has a nice interpretation: if the probability is close to 1, the negative log will be close to 0. This means that there is little cost in sending that particular combination of materials to that constituent since we are certain it will lead them to vote for our candidate. Vice versa if the probability is close to 0." }, { "code": null, "e": 5899, "s": 5751, "text": "#clipping so that we don't take log of 0 or 1test_probs = np.clip(test_probs, 0.0001, 0.9999)#turning into costsmodel_costs = -np.log10(test_probs)" }, { "code": null, "e": 5998, "s": 5899, "text": "Finally, let’s say that we cannot send more than 150 flyers, 80 pamphlets, and 25 bumper stickers." }, { "code": null, "e": 6036, "s": 5998, "text": "supply = np.atleast_2d([150, 80, 25])" }, { "code": null, "e": 6100, "s": 6036, "text": "Now that we’ve done all the set-up, we can get to the fun part:" }, { "code": null, "e": 6277, "s": 6100, "text": "Creating the variable: We’ll use a cvxpy.Bool object again because we can only make binary choices here. We’ll specify that it must be the same shape as our probability matrix:" }, { "code": null, "e": 6454, "s": 6277, "text": "Creating the variable: We’ll use a cvxpy.Bool object again because we can only make binary choices here. We’ll specify that it must be the same shape as our probability matrix:" }, { "code": null, "e": 6496, "s": 6454, "text": "selection = cvxpy.Bool(*test_probs.shape)" }, { "code": null, "e": 6845, "s": 6496, "text": "2. Specifying the constraints: Our selection variable will only tell us which of the 8 choices we’ve made for each constituent, but it won’t tell how many total materials we’ve decided to send to them. We need a way to turn our 1 x 8 selection vector into a 1 x 3 vector. We can do so by multiplying by the selection vector by the following matrix:" }, { "code": null, "e": 7103, "s": 6845, "text": "TRANSFORMER = np.array([[1,0,0], [0,1,0], [0,0,1], [1,1,0], [1,0,1], [0,1,1], [1,1,1], [0,0,0]])" }, { "code": null, "e": 7171, "s": 7103, "text": "If this part is a little confusing, work out the following example:" }, { "code": null, "e": 7243, "s": 7171, "text": "print(np.dot(np.array([0,0,0,1,0,0,0,0]), TRANSFORMER))array([1, 1, 0])" }, { "code": null, "e": 7491, "s": 7243, "text": "The fourth entry of our decision vector represents sending a flyer and pamphlet to the constituent and multiplying by TRANSFORMER tells us just that! So we’ll tell cvxpy that multiplying our selection matrix by transformer can’t exceed our supply:" }, { "code": null, "e": 7572, "s": 7491, "text": "supply_constraint = cvxpy.sum_entries(selection * TRANSFORMER, axis=0) <= supply" }, { "code": null, "e": 7700, "s": 7572, "text": "I’m summing over the rows with cvxpy.sum_entries to aggregate the total number of materials we’ve sent across all constituents." }, { "code": null, "e": 7847, "s": 7700, "text": "We also need to ensure we’re making exactly once choice per constituent, otherwise the solver can attain zero cost by not sending anyone anything." }, { "code": null, "e": 8065, "s": 7847, "text": "# We must make our choice per constituent# remember that the last column is for \"no materials\"feasibility_constraint = cvxpy.sum_entries(selection, axis=1) == 1constraints = [supply_constraint, feasibility_constraint]" }, { "code": null, "e": 8447, "s": 8065, "text": "3. Formulating the objective function: The total cost of our assignment will be the sum of the costs we’ve incurred for each constituent. We’ll use the cvxpy.mul_elemwise function to multiply our selection matrix with our cost matrix, this will select the cost for each constituent, and the cvxpy.sum_elemwise function will compute the total cost by adding up the individual costs." }, { "code": null, "e": 8516, "s": 8447, "text": "cost = cvxpy.sum_entries(cvxpy.mul_elemwise(model_costs, selection))" }, { "code": null, "e": 8576, "s": 8516, "text": "The final step is to create the cvxpy.Problem and solve it." }, { "code": null, "e": 8703, "s": 8576, "text": "# Solving the problemproblem = cvxpy.Problem(cvxpy.Minimize(cost), constraints=constraints)problem.solve(solver=cvxpy.GLPK_MI)" }, { "code": null, "e": 8976, "s": 8703, "text": "That’s it! Below is a snapshot of what our final assignments look like. We decided not to send any materials to the first constituent. This makes sense because the probability of them voting for our candidate is 0.3 whether we send them a bumper sticker or nothing at all." }, { "code": null, "e": 9198, "s": 8976, "text": "It also turns out that the optimal assignment exhausts our supply of pamphlets and bumper stickers but only uses 83 of the total 150 flyers. We should tell our candidate that her flyers aren’t as persuasive as she thinks." }, { "code": null, "e": 9526, "s": 9198, "text": "print(hard_assignments.value[0:5])matrix([[0., 0., 0., 0., 0., 0., 0., 1.], [0., 0., 0., 1., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 0., 0., 1.], [1., 0., 0., 0., 0., 0., 0., 0.], [1., 0., 0., 0., 0., 0., 0., 0.]])print(np.dot(hard_assignments.value, TRANSFORMER).sum(axis=0))matrix([[83., 80., 25.]])" }, { "code": null, "e": 9566, "s": 9526, "text": "Here is all the code packaged together:" }, { "code": null, "e": 9996, "s": 9566, "text": "I hope you’ve enjoyed learning about integer programming problems and how to solve them in Python. Believe it or not, we’ve covered about 80% of the cvxpy knowledge you need to go out and solve your own optimization problems. I encourage you to read the official documentation to learn about the remaining 20%. CVXPY can solve more than just IP problems, check out their tutorials page to see what other problems cvxpy can solve." }, { "code": null, "e": 10167, "s": 9996, "text": "To install cvxpy, follow the directions on their website. I would also install cvxopt to make sure all the solvers that come packaged with cvxpy will work on your machine" } ]
Interface Arduino with Gas Sensor
In this article, we will see how to interface Arduino with the MQ-2 gas sensor. MQ2 gas sensor is used for detecting smoke and some flammable gases like LPG, Methane, etc. It changes its resistance depending on the type of the gas. This principle can be used to raise an alarm based on the concentration of the gas. An image of the MQ2 gas sensor is given above. As you can see, it has 4 pins. Out of these the Aout pin gives the Analog voltage in proportion to the gas concentration. Higher the gas concentration, higher the voltage on the Aout pin. Depending on your application, you can perform some trial and errors, and determine the threshold of Aout voltage above which you want to raise an alarm. Alternatively, you can adjust the potentiometer on the other side of the sensor to set the threshold, and then use the Dout pin to get digital value (whether concentration of gas is above or below threshold). The circuit diagram is shown below βˆ’ As you can see, Vcc of MQ2 is connected to 5V, GND to GND and Aout to A0. The code is pretty straightforward, as you can see below βˆ’ int sensorPin = A0; int sensorThreshold = 300; void setup() { // put your setup code here, to run once: Serial.begin(9600); pinMode(sensorPin, INPUT); } void loop() { // put your main code here, to run repeatedly: if (analogRead(sensorPin) > sensorThreshold) { Serial.println("Gas concentration too high!"); } else { Serial.println("Gas concentration in control"); } } As discussed earlier as well, you can determine the threshold using trial and error. Also, don’t touch the sensor after it has been active for some time, because it tends to heat up. Also, you can add other actions, like ringing a buzzer, once the sensor readings cross the threshold.
[ { "code": null, "e": 1378, "s": 1062, "text": "In this article, we will see how to interface Arduino with the MQ-2 gas sensor. MQ2 gas sensor is used for detecting smoke and some flammable gases like LPG, Methane, etc. It changes its resistance depending on the type of the gas. This principle can be used to raise an alarm based on the concentration of the gas." }, { "code": null, "e": 1767, "s": 1378, "text": "An image of the MQ2 gas sensor is given above. As you can see, it has 4 pins. Out of these the Aout pin gives the Analog voltage in proportion to the gas concentration. Higher the gas concentration, higher the voltage on the Aout pin. Depending on your application, you can perform some trial and errors, and determine the threshold of Aout voltage above which you want to raise an alarm." }, { "code": null, "e": 1976, "s": 1767, "text": "Alternatively, you can adjust the potentiometer on the other side of the sensor to set the threshold, and then use the Dout pin to get digital value (whether concentration of gas is above or below threshold)." }, { "code": null, "e": 2013, "s": 1976, "text": "The circuit diagram is shown below βˆ’" }, { "code": null, "e": 2087, "s": 2013, "text": "As you can see, Vcc of MQ2 is connected to 5V, GND to GND and Aout to A0." }, { "code": null, "e": 2146, "s": 2087, "text": "The code is pretty straightforward, as you can see below βˆ’" }, { "code": null, "e": 2550, "s": 2146, "text": "int sensorPin = A0;\nint sensorThreshold = 300;\n\nvoid setup() {\n // put your setup code here, to run once:\n Serial.begin(9600);\n pinMode(sensorPin, INPUT);\n}\n\nvoid loop() {\n // put your main code here, to run repeatedly:\n if (analogRead(sensorPin) > sensorThreshold) {\n Serial.println(\"Gas concentration too high!\");\n } else {\n Serial.println(\"Gas concentration in control\");\n }\n}" }, { "code": null, "e": 2835, "s": 2550, "text": "As discussed earlier as well, you can determine the threshold using trial and error. Also, don’t touch the sensor after it has been active for some time, because it tends to heat up. Also, you can add other actions, like ringing a buzzer, once the sensor readings cross the threshold." } ]
Tryit Editor v3.7
Tryit: HTML image - error in source
[]
Struts 2 - Interceptors
Interceptors are conceptually the same as servlet filters or the JDKs Proxy class. Interceptors allow for crosscutting functionality to be implemented separately from the action as well as the framework. You can achieve the following using interceptors βˆ’ Providing preprocessing logic before the action is called. Providing preprocessing logic before the action is called. Providing postprocessing logic after the action is called. Providing postprocessing logic after the action is called. Catching exceptions so that alternate processing can be performed. Catching exceptions so that alternate processing can be performed. Many of the features provided in the Struts2 framework are implemented using interceptors; Examples include exception handling, file uploading, lifecycle callbacks, etc. In fact, as Struts2 emphasizes much of its functionality on interceptors, it is not likely to have 7 or 8 interceptors assigned per action. Struts 2 framework provides a good list of out-of-the-box interceptors that come preconfigured and ready to use. Few of the important interceptors are listed below βˆ’ alias Allows parameters to have different name aliases across requests. checkbox Assists in managing check boxes by adding a parameter value of false for check boxes that are not checked. conversionError Places error information from converting strings to parameter types into the action's field errors. createSession Automatically creates an HTTP session if one does not already exist. debugging Provides several different debugging screens to the developer. execAndWait Sends the user to an intermediary waiting page while the action executes in the background. exception Maps exceptions that are thrown from an action to a result, allowing automatic exception handling via redirection. fileUpload Facilitates easy file uploading. i18n Keeps track of the selected locale during a user's session. logger Provides simple logging by outputting the name of the action being executed. params Sets the request parameters on the action. prepare This is typically used to do pre-processing work, such as setup database connections. profile Allows simple profiling information to be logged for actions. scope Stores and retrieves the action's state in the session or application scope. ServletConfig Provides the action with access to various servlet-based information. timer Provides simple profiling information in the form of how long the action takes to execute. token Checks the action for a valid token to prevent duplicate formsubmission. validation Provides validation support for actions Please look into Struts 2 documentation for complete detail on the abovementioned interceptors. But I will show you how to use an interceptor in general in your Struts application. Let us see how to use an already existing interceptor to our "Hello World" program. We will use the timer interceptor whose purpose is to measure how long it took to execute an action method. At the same time, I'm using params interceptor whose purpose is to send the request parameters to the action. You can try your example without using this interceptor and you will find that name property is not being set because parameter is not able to reach to the action. We will keep HelloWorldAction.java, web.xml, HelloWorld.jsp and index.jsp files as they have been created in Examples chapter but let us modify the struts.xml file to add an interceptor as follows βˆ’ <?xml version = "1.0" Encoding = "UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name = "struts.devMode" value = "true" /> <package name = "helloworld" extends = "struts-default"> <action name = "hello" class = "com.tutorialspoint.struts2.HelloWorldAction" method = "execute"> <interceptor-ref name = "params"/> <interceptor-ref name = "timer" /> <result name = "success">/HelloWorld.jsp</result> </action> </package> </struts> Right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat's webapps directory. Finally, start Tomcat server and try to access URL http://localhost:8080/HelloWorldStruts2/index.jsp. This will produce the following screen βˆ’ Now enter any word in the given text box and click Say Hello button to execute the defined action. Now if you will check the log generated, you will find the following text βˆ’ INFO: Server startup in 3539 ms 27/08/2011 8:40:53 PM com.opensymphony.xwork2.util.logging.commons.CommonsLogger info INFO: Executed action [//hello!execute] took 109 ms. Here bottom line is being generated because of timer interceptor which is telling that action took total 109ms to be executed. Using custom interceptors in your application is an elegant way to provide crosscutting application features. Creating a custom interceptor is easy; the interface that needs to be extended is the following Interceptor interface βˆ’ public interface Interceptor extends Serializable { void destroy(); void init(); String intercept(ActionInvocation invocation) throws Exception; } As the names suggest, the init() method provides a way to initialize the interceptor, and the destroy() method provides a facility for interceptor cleanup. Unlike actions, interceptors are reused across requests and need to be threadsafe, especially the intercept() method. The ActionInvocation object provides access to the runtime environment. It allows access to the action itself and methods to invoke the action and determine whether the action has already been invoked. If you have no need for initialization or cleanup code, the AbstractInterceptor class can be extended. This provides a default nooperation implementation of the init() and destroy() methods. Let us create the following MyInterceptor.java in Java Resources > src folder βˆ’ package com.tutorialspoint.struts2; import java.util.*; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.AbstractInterceptor; public class MyInterceptor extends AbstractInterceptor { public String intercept(ActionInvocation invocation)throws Exception { /* let us do some pre-processing */ String output = "Pre-Processing"; System.out.println(output); /* let us call action or next interceptor */ String result = invocation.invoke(); /* let us do some post-processing */ output = "Post-Processing"; System.out.println(output); return result; } } As you notice, actual action will be executed using the interceptor by invocation.invoke()call. So you can do some pre-processing and some postprocessing based on your requirement. The framework itself starts the process by making the first call to the ActionInvocation object's invoke(). Each time invoke() is called, ActionInvocation consults its state and executes whichever interceptor comes next. When all of the configured interceptors have been invoked, the invoke() method will cause the action itself to be executed. The following diagram shows the same concept through a request flow βˆ’ Let us create a java file HelloWorldAction.java under Java Resources > src with a package name com.tutorialspoint.struts2 with the contents given below. package com.tutorialspoint.struts2; import com.opensymphony.xwork2.ActionSupport; public class HelloWorldAction extends ActionSupport { private String name; public String execute() throws Exception { System.out.println("Inside action...."); return "success"; } public String getName() { return name; } public void setName(String name) { this.name = name; } } This is a same class which we have seen in previous examples. We have standard getters and setter methods for the "name" property and an execute method that returns the string "success". Let us create the below jsp file HelloWorld.jsp in the WebContent folder in your eclipse project. <%@ page contentType = "text/html; charset = UTF-8" %> <%@ taglib prefix = "s" uri = "/struts-tags" %> <html> <head> <title>Hello World</title> </head> <body> Hello World, <s:property value = "name"/> </body> </html> We also need to create index.jsp in the WebContent folder. This file will serve as the initial action URL where a user can click to tell the Struts 2 framework to call the a defined method of the HelloWorldAction class and render the HelloWorld.jsp view. <%@ page language = "java" contentType = "text/html; charset = ISO-8859-1" pageEncoding = "ISO-8859-1"%> <%@ taglib prefix = "s" uri = "/struts-tags"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Hello World</title> </head> <body> <h1>Hello World From Struts2</h1> <form action = "hello"> <label for = "name">Please enter your name</label><br/> <input type = "text" name = "name"/> <input type = "submit" value = "Say Hello"/> </form> </body> </html> The hello action defined in the above view file will be mapped to the HelloWorldAction class and its execute method using struts.xml file. Now, we need to register our interceptor and then call it as we had called default interceptor in previous example. To register a newly defined interceptor, the <interceptors>...</interceptors> tags are placed directly under the <package> tag insstruts.xml file. You can skip this step for a default interceptors as we did in our previous example. But here let us register and use it as follows βˆ’ <?xml version = "1.0" Encoding = "UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name = "struts.devMode" value = "true" /> <package name = "helloworld" extends = "struts-default"> <interceptors> <interceptor name = "myinterceptor" class = "com.tutorialspoint.struts2.MyInterceptor" /> </interceptors> <action name = "hello" class = "com.tutorialspoint.struts2.HelloWorldAction" method = "execute"> <interceptor-ref name = "params"/> <interceptor-ref name = "myinterceptor" /> <result name = "success">/HelloWorld.jsp</result> </action> </package> </struts> It should be noted that you can register more than one interceptors inside <package> tag and same time you can call more than one interceptors inside the <action> tag. You can call same interceptor with the different actions. The web.xml file needs to be created under the WEB-INF folder under WebContent as follows βˆ’ <?xml version = "1.0" Encoding = "UTF-8"?> <web-app xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns = "http://java.sun.com/xml/ns/javaee" xmlns:web = "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id = "WebApp_ID" version = "3.0"> <display-name>Struts 2</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <filter> <filter-name>struts2</filter-name> <filter-class> org.apache.struts2.dispatcher.FilterDispatcher </filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app> Right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat's webapps directory. Finally, start Tomcat server and try to access URL http://localhost:8080/HelloWorldStruts2/index.jsp. This will produce the following screen βˆ’ Now enter any word in the given text box and click Say Hello button to execute the defined action. Now if you will check the log generated, you will find the following text at the bottom βˆ’ Pre-Processing Inside action.... Post-Processing As you can imagine, having to configure multiple interceptor for each action would quickly become extremely unmanageable. For this reason, interceptors are managed with interceptor stacks. Here is an example, directly from the strutsdefault.xml file βˆ’ <interceptor-stack name = "basicStack"> <interceptor-ref name = "exception"/> <interceptor-ref name = "servlet-config"/> <interceptor-ref name = "prepare"/> <interceptor-ref name = "checkbox"/> <interceptor-ref name = "params"/> <interceptor-ref name = "conversionError"/> </interceptor-stack> The above stake is called basicStack and can be used in your configuration as shown below. This configuration node is placed under the <package .../> node. Each <interceptor-ref .../> tag references either an interceptor or an interceptor stack that has been configured before the current interceptor stack. It is therefore very important to ensure that the name is unique across all interceptor and interceptor stack configurations when configuring the initial interceptors and interceptor stacks. We have already seen how to apply interceptor to the action, applying interceptor stacks is no different. In fact, we use exactly the same tag βˆ’ <action name = "hello" class = "com.tutorialspoint.struts2.MyAction"> <interceptor-ref name = "basicStack"/> <result>view.jsp</result> </action The above registration of "basicStack" will register complete stake of all the six interceptors with hello action. This should be noted that interceptors are executed in the order, in which they have been configured. For example, in the above case, exception will be executed first, second would be servlet-config and so on. Print Add Notes Bookmark this page
[ { "code": null, "e": 2501, "s": 2246, "text": "Interceptors are conceptually the same as servlet filters or the JDKs Proxy class. Interceptors allow for crosscutting functionality to be implemented separately from the action as well as the framework. You can achieve the following using interceptors βˆ’" }, { "code": null, "e": 2560, "s": 2501, "text": "Providing preprocessing logic before the action is called." }, { "code": null, "e": 2619, "s": 2560, "text": "Providing preprocessing logic before the action is called." }, { "code": null, "e": 2678, "s": 2619, "text": "Providing postprocessing logic after the action is called." }, { "code": null, "e": 2737, "s": 2678, "text": "Providing postprocessing logic after the action is called." }, { "code": null, "e": 2804, "s": 2737, "text": "Catching exceptions so that alternate processing can be performed." }, { "code": null, "e": 2871, "s": 2804, "text": "Catching exceptions so that alternate processing can be performed." }, { "code": null, "e": 2962, "s": 2871, "text": "Many of the features provided in the Struts2 framework are implemented using interceptors;" }, { "code": null, "e": 3181, "s": 2962, "text": "Examples include exception handling, file uploading, lifecycle callbacks, etc. In fact, as Struts2 emphasizes much of its functionality on interceptors, it is not likely to have 7 or 8 interceptors assigned per action." }, { "code": null, "e": 3347, "s": 3181, "text": "Struts 2 framework provides a good list of out-of-the-box interceptors that come preconfigured and ready to use. Few of the important interceptors are listed below βˆ’" }, { "code": null, "e": 3353, "s": 3347, "text": "alias" }, { "code": null, "e": 3419, "s": 3353, "text": "Allows parameters to have different name aliases across requests." }, { "code": null, "e": 3428, "s": 3419, "text": "checkbox" }, { "code": null, "e": 3535, "s": 3428, "text": "Assists in managing check boxes by adding a parameter value of false for check boxes that are not checked." }, { "code": null, "e": 3551, "s": 3535, "text": "conversionError" }, { "code": null, "e": 3651, "s": 3551, "text": "Places error information from converting strings to parameter types into the action's field errors." }, { "code": null, "e": 3665, "s": 3651, "text": "createSession" }, { "code": null, "e": 3734, "s": 3665, "text": "Automatically creates an HTTP session if one does not already exist." }, { "code": null, "e": 3744, "s": 3734, "text": "debugging" }, { "code": null, "e": 3807, "s": 3744, "text": "Provides several different debugging screens to the developer." }, { "code": null, "e": 3819, "s": 3807, "text": "execAndWait" }, { "code": null, "e": 3911, "s": 3819, "text": "Sends the user to an intermediary waiting page while the action executes in the background." }, { "code": null, "e": 3921, "s": 3911, "text": "exception" }, { "code": null, "e": 4036, "s": 3921, "text": "Maps exceptions that are thrown from an action to a result, allowing automatic exception handling via redirection." }, { "code": null, "e": 4047, "s": 4036, "text": "fileUpload" }, { "code": null, "e": 4080, "s": 4047, "text": "Facilitates easy file uploading." }, { "code": null, "e": 4085, "s": 4080, "text": "i18n" }, { "code": null, "e": 4145, "s": 4085, "text": "Keeps track of the selected locale during a user's session." }, { "code": null, "e": 4152, "s": 4145, "text": "logger" }, { "code": null, "e": 4229, "s": 4152, "text": "Provides simple logging by outputting the name of the action being executed." }, { "code": null, "e": 4236, "s": 4229, "text": "params" }, { "code": null, "e": 4279, "s": 4236, "text": "Sets the request parameters on the action." }, { "code": null, "e": 4287, "s": 4279, "text": "prepare" }, { "code": null, "e": 4373, "s": 4287, "text": "This is typically used to do pre-processing work, such as setup database connections." }, { "code": null, "e": 4381, "s": 4373, "text": "profile" }, { "code": null, "e": 4443, "s": 4381, "text": "Allows simple profiling information to be logged for actions." }, { "code": null, "e": 4449, "s": 4443, "text": "scope" }, { "code": null, "e": 4526, "s": 4449, "text": "Stores and retrieves the action's state in the session or application scope." }, { "code": null, "e": 4540, "s": 4526, "text": "ServletConfig" }, { "code": null, "e": 4610, "s": 4540, "text": "Provides the action with access to various servlet-based information." }, { "code": null, "e": 4616, "s": 4610, "text": "timer" }, { "code": null, "e": 4707, "s": 4616, "text": "Provides simple profiling information in the form of how long the action takes to execute." }, { "code": null, "e": 4713, "s": 4707, "text": "token" }, { "code": null, "e": 4786, "s": 4713, "text": "Checks the action for a valid token to prevent duplicate formsubmission." }, { "code": null, "e": 4797, "s": 4786, "text": "validation" }, { "code": null, "e": 4837, "s": 4797, "text": "Provides validation support for actions" }, { "code": null, "e": 5018, "s": 4837, "text": "Please look into Struts 2 documentation for complete detail on the abovementioned interceptors. But I will show you how to use an interceptor in general in your Struts application." }, { "code": null, "e": 5484, "s": 5018, "text": "Let us see how to use an already existing interceptor to our \"Hello World\" program. We will use the timer interceptor whose purpose is to measure how long it took to execute an action method. At the same time, I'm using params interceptor whose purpose is to send the request parameters to the action. You can try your example without using this interceptor and you will find that name property is not being set because parameter is not able to reach to the action." }, { "code": null, "e": 5683, "s": 5484, "text": "We will keep HelloWorldAction.java, web.xml, HelloWorld.jsp and index.jsp files as they have been created in Examples chapter but let us modify the struts.xml file to add an interceptor as follows βˆ’" }, { "code": null, "e": 6307, "s": 5683, "text": "<?xml version = \"1.0\" Encoding = \"UTF-8\"?>\n<!DOCTYPE struts PUBLIC\n \"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN\"\n \"http://struts.apache.org/dtds/struts-2.0.dtd\">\n<struts>\n <constant name = \"struts.devMode\" value = \"true\" />\n \n <package name = \"helloworld\" extends = \"struts-default\">\n <action name = \"hello\" \n class = \"com.tutorialspoint.struts2.HelloWorldAction\"\n method = \"execute\">\n <interceptor-ref name = \"params\"/>\n <interceptor-ref name = \"timer\" />\n <result name = \"success\">/HelloWorld.jsp</result>\n </action>\n </package>\n</struts>" }, { "code": null, "e": 6588, "s": 6307, "text": "Right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat's webapps directory. Finally, start Tomcat server and try to access URL http://localhost:8080/HelloWorldStruts2/index.jsp. This will produce the following screen βˆ’" }, { "code": null, "e": 6763, "s": 6588, "text": "Now enter any word in the given text box and click Say Hello button to execute the defined action. Now if you will check the log generated, you will find the following text βˆ’" }, { "code": null, "e": 6935, "s": 6763, "text": "INFO: Server startup in 3539 ms\n27/08/2011 8:40:53 PM \ncom.opensymphony.xwork2.util.logging.commons.CommonsLogger info\nINFO: Executed action [//hello!execute] took 109 ms." }, { "code": null, "e": 7062, "s": 6935, "text": "Here bottom line is being generated because of timer interceptor which is telling that action took total 109ms to be executed." }, { "code": null, "e": 7292, "s": 7062, "text": "Using custom interceptors in your application is an elegant way to provide crosscutting application features. Creating a custom interceptor is easy; the interface that needs to be extended is the following Interceptor interface βˆ’" }, { "code": null, "e": 7451, "s": 7292, "text": "public interface Interceptor extends Serializable {\n void destroy();\n void init();\n String intercept(ActionInvocation invocation)\n throws Exception;\n}" }, { "code": null, "e": 7725, "s": 7451, "text": "As the names suggest, the init() method provides a way to initialize the interceptor, and the destroy() method provides a facility for interceptor cleanup. Unlike actions, interceptors are reused across requests and need to be threadsafe, especially the intercept() method." }, { "code": null, "e": 7927, "s": 7725, "text": "The ActionInvocation object provides access to the runtime environment. It allows access to the action itself and methods to invoke the action and determine whether the action has already been invoked." }, { "code": null, "e": 8118, "s": 7927, "text": "If you have no need for initialization or cleanup code, the AbstractInterceptor class can be extended. This provides a default nooperation implementation of the init() and destroy() methods." }, { "code": null, "e": 8198, "s": 8118, "text": "Let us create the following MyInterceptor.java in Java Resources > src folder βˆ’" }, { "code": null, "e": 8856, "s": 8198, "text": "package com.tutorialspoint.struts2;\n\nimport java.util.*;\nimport com.opensymphony.xwork2.ActionInvocation;\nimport com.opensymphony.xwork2.interceptor.AbstractInterceptor;\n\npublic class MyInterceptor extends AbstractInterceptor {\n\n public String intercept(ActionInvocation invocation)throws Exception {\n\n /* let us do some pre-processing */\n String output = \"Pre-Processing\"; \n System.out.println(output);\n\n /* let us call action or next interceptor */\n String result = invocation.invoke();\n\n /* let us do some post-processing */\n output = \"Post-Processing\"; \n System.out.println(output);\n\n return result;\n }\n}" }, { "code": null, "e": 9037, "s": 8856, "text": "As you notice, actual action will be executed using the interceptor by invocation.invoke()call. So you can do some pre-processing and some postprocessing based on your requirement." }, { "code": null, "e": 9382, "s": 9037, "text": "The framework itself starts the process by making the first call to the ActionInvocation object's invoke(). Each time invoke() is called, ActionInvocation consults its state and executes whichever interceptor comes next. When all of the configured interceptors have been invoked, the invoke() method will cause the action itself to be executed." }, { "code": null, "e": 9452, "s": 9382, "text": "The following diagram shows the same concept through a request flow βˆ’" }, { "code": null, "e": 9605, "s": 9452, "text": "Let us create a java file HelloWorldAction.java under Java Resources > src with a package name com.tutorialspoint.struts2 with the contents given below." }, { "code": null, "e": 10016, "s": 9605, "text": "package com.tutorialspoint.struts2;\n\nimport com.opensymphony.xwork2.ActionSupport;\n\npublic class HelloWorldAction extends ActionSupport {\n private String name;\n\n public String execute() throws Exception {\n System.out.println(\"Inside action....\");\n return \"success\";\n } \n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n}" }, { "code": null, "e": 10203, "s": 10016, "text": "This is a same class which we have seen in previous examples. We have standard getters and setter methods for the \"name\" property and an execute method that returns the string \"success\"." }, { "code": null, "e": 10301, "s": 10203, "text": "Let us create the below jsp file HelloWorld.jsp in the WebContent folder in your eclipse project." }, { "code": null, "e": 10547, "s": 10301, "text": "<%@ page contentType = \"text/html; charset = UTF-8\" %>\n<%@ taglib prefix = \"s\" uri = \"/struts-tags\" %>\n\n<html>\n <head>\n <title>Hello World</title>\n </head>\n \n <body>\n Hello World, <s:property value = \"name\"/>\n </body>\n</html>" }, { "code": null, "e": 10802, "s": 10547, "text": "We also need to create index.jsp in the WebContent folder. This file will serve as the initial action URL where a user can click to tell the Struts 2 framework to call the a defined method of the HelloWorldAction class and render the HelloWorld.jsp view." }, { "code": null, "e": 11411, "s": 10802, "text": "<%@ page language = \"java\" contentType = \"text/html; charset = ISO-8859-1\"\n pageEncoding = \"ISO-8859-1\"%>\n<%@ taglib prefix = \"s\" uri = \"/struts-tags\"%>\n <!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \n \"http://www.w3.org/TR/html4/loose.dtd\">\n\n<html>\n <head>\n <title>Hello World</title>\n </head>\n \n <body>\n <h1>Hello World From Struts2</h1>\n <form action = \"hello\">\n <label for = \"name\">Please enter your name</label><br/>\n <input type = \"text\" name = \"name\"/>\n <input type = \"submit\" value = \"Say Hello\"/>\n </form>\n </body>\n</html>" }, { "code": null, "e": 11550, "s": 11411, "text": "The hello action defined in the above view file will be mapped to the HelloWorldAction class and its execute method using struts.xml file." }, { "code": null, "e": 11947, "s": 11550, "text": "Now, we need to register our interceptor and then call it as we had called default interceptor in previous example. To register a newly defined interceptor, the <interceptors>...</interceptors> tags are placed directly under the <package> tag insstruts.xml file. You can skip this step for a default interceptors as we did in our previous example. But here let us register and use it as follows βˆ’" }, { "code": null, "e": 12734, "s": 11947, "text": "<?xml version = \"1.0\" Encoding = \"UTF-8\"?>\n<!DOCTYPE struts PUBLIC\n \"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN\"\n \"http://struts.apache.org/dtds/struts-2.0.dtd\">\n\n<struts>\n <constant name = \"struts.devMode\" value = \"true\" />\n <package name = \"helloworld\" extends = \"struts-default\">\n\n <interceptors>\n <interceptor name = \"myinterceptor\"\n class = \"com.tutorialspoint.struts2.MyInterceptor\" />\n </interceptors>\n\n <action name = \"hello\" \n class = \"com.tutorialspoint.struts2.HelloWorldAction\" \n method = \"execute\">\n <interceptor-ref name = \"params\"/>\n <interceptor-ref name = \"myinterceptor\" />\n <result name = \"success\">/HelloWorld.jsp</result>\n </action>\n\n </package>\n</struts>" }, { "code": null, "e": 12960, "s": 12734, "text": "It should be noted that you can register more than one interceptors inside <package> tag and same time you can call more than one interceptors inside the <action> tag. You can call same interceptor with the different actions." }, { "code": null, "e": 13052, "s": 12960, "text": "The web.xml file needs to be created under the WEB-INF folder under WebContent as follows βˆ’" }, { "code": null, "e": 13866, "s": 13052, "text": "<?xml version = \"1.0\" Encoding = \"UTF-8\"?>\n<web-app xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xmlns = \"http://java.sun.com/xml/ns/javaee\" \n xmlns:web = \"http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd\"\n xsi:schemaLocation = \"http://java.sun.com/xml/ns/javaee \n http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd\"\n id = \"WebApp_ID\" version = \"3.0\">\n \n <display-name>Struts 2</display-name>\n \n <welcome-file-list>\n <welcome-file>index.jsp</welcome-file>\n </welcome-file-list>\n \n <filter>\n <filter-name>struts2</filter-name>\n <filter-class>\n org.apache.struts2.dispatcher.FilterDispatcher\n </filter-class>\n </filter>\n\n <filter-mapping>\n <filter-name>struts2</filter-name>\n <url-pattern>/*</url-pattern>\n </filter-mapping>\n</web-app>" }, { "code": null, "e": 14147, "s": 13866, "text": "Right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat's webapps directory. Finally, start Tomcat server and try to access URL http://localhost:8080/HelloWorldStruts2/index.jsp. This will produce the following screen βˆ’" }, { "code": null, "e": 14336, "s": 14147, "text": "Now enter any word in the given text box and click Say Hello button to execute the defined action. Now if you will check the log generated, you will find the following text at the bottom βˆ’" }, { "code": null, "e": 14385, "s": 14336, "text": "Pre-Processing\nInside action....\nPost-Processing" }, { "code": null, "e": 14637, "s": 14385, "text": "As you can imagine, having to configure multiple interceptor for each action would quickly become extremely unmanageable. For this reason, interceptors are managed with interceptor stacks. Here is an example, directly from the strutsdefault.xml file βˆ’" }, { "code": null, "e": 14949, "s": 14637, "text": "<interceptor-stack name = \"basicStack\">\n <interceptor-ref name = \"exception\"/>\n <interceptor-ref name = \"servlet-config\"/>\n <interceptor-ref name = \"prepare\"/>\n <interceptor-ref name = \"checkbox\"/>\n <interceptor-ref name = \"params\"/>\n <interceptor-ref name = \"conversionError\"/>\n</interceptor-stack>" }, { "code": null, "e": 15448, "s": 14949, "text": "The above stake is called basicStack and can be used in your configuration as shown below. This configuration node is placed under the <package .../> node. Each <interceptor-ref .../> tag references either an interceptor or an interceptor stack that has been configured before the current interceptor stack. It is therefore very important to ensure that the name is unique across all interceptor and interceptor stack configurations when configuring the initial interceptors and interceptor stacks." }, { "code": null, "e": 15593, "s": 15448, "text": "We have already seen how to apply interceptor to the action, applying interceptor stacks is no different. In fact, we use exactly the same tag βˆ’" }, { "code": null, "e": 15743, "s": 15593, "text": "<action name = \"hello\" class = \"com.tutorialspoint.struts2.MyAction\">\n <interceptor-ref name = \"basicStack\"/>\n <result>view.jsp</result>\n</action" }, { "code": null, "e": 16068, "s": 15743, "text": "The above registration of \"basicStack\" will register complete stake of all the six interceptors with hello action. This should be noted that interceptors are executed in the order, in which they have been configured. For example, in the above case, exception will be executed first, second would be servlet-config and so on." }, { "code": null, "e": 16075, "s": 16068, "text": " Print" }, { "code": null, "e": 16086, "s": 16075, "text": " Add Notes" } ]
Group data.table by Multiple Columns in R - GeeksforGeeks
23 Sep, 2021 In this article, we will discuss how to group data.table by multiple columns in R programming language. The package data.table can be used to work with data tables and subsetting and organizing data. It can be downloaded and installed into the workspace using the following command : library(data.table) The column at a specified index can be extracted using the list subsetting, i.e. [, operator. The new column can be added in the second argument assigned to a predefined or a user-defined function defined over a set of columns of data.table. The by argument can be added to group the data using a set of columns from the data table. The list() method can be used to specify a set of columns of the data.table to group the data by. Example: Group data.table by multiple columns R library(data.table) # creating first data framedata_frame <- data.table(col1 = rep(LETTERS[1:3],each=2), col2 = c(5:10), col3 = c(TRUE,FALSE) ) print ("Original DataFrame")print (data_frame) # group by col1,col3data_mod <- data_frame[ , count:=sum(col2), by = list(col1,col3)] # print modified data frameprint ("Modified DataFrame") print(data_mod) Output: [1] "Original DataFrame" col1 col2 col3 1: A 5 TRUE 2: A 6 FALSE 3: B 7 TRUE 4: B 8 FALSE 5: C 9 TRUE 6: C 10 FALSE [1] "Modified DataFrame" col1 col2 col3 count 1: A 5 TRUE 5 2: A 6 FALSE 6 3: B 7 TRUE 7 4: B 8 FALSE 8 5: C 9 TRUE 9 6: C 10 FALSE 10 In the above example, since none of the groups are the same, therefore, the new column β€œcount” values are equivalent to the col2 values. In case there are columns belonging to the same groups, the sum is generated corresponding to each column. Example: Group data.table by multiple columns R library(data.table) # creating first data framedata_frame <- data.table(col1 = rep(LETTERS[1:3],each=2), col2 = c(1:6), col3 = TRUE ) print ("Original DataFrame")print (data_frame) # group by col1,col3data_mod <- data_frame[ , count:=sum(col2), by = list(col1,col3)] # print modified data frameprint ("Modified DataFrame") print(data_mod) Output: [1] "Original DataFrame" col1 col2 col3 1: A 1 TRUE 2: A 2 TRUE 3: B 3 TRUE 4: B 4 TRUE 5: C 5 TRUE 6: C 6 TRUE [1] "Modified DataFrame" col1 col2 col3 count 1: A 1 TRUE 3 2: A 2 TRUE 3 3: B 3 TRUE 7 4: B 4 TRUE 7 5: C 5 TRUE 11 6: C 6 TRUE 11 Grouping of data can also be done using all the columns of the data.table, as indicated in the following code snippet. Example: Group data.table by multiple columns R library(data.table) # creating first data framedata_frame <- data.table(col1 = rep(LETTERS[1:3],each=2), col2 = c(1,1,3,4,5,6), col3 = 1 )print ("Original DataFrame")print (data_frame) # group by col1,col3data_mod <- data_frame[ , count:=sum(col2), by = list(col1,col2,col3)] # print modified data frameprint ("Modified DataFrame") print(data_mod) Output: [1] "Original DataFrame" col1 col2 col3 1: A 1 1 2: A 1 1 3: B 3 1 4: B 4 1 5: C 5 1 6: C 6 1 [1] "Modified DataFrame" col1 col2 col3 count 1: A 1 1 1 2: A 1 1 1 3: B 3 1 3 4: B 4 1 4 5: C 5 1 5 6: C 6 1 6 Picked R DataTable R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? How to import an Excel File into R ? How to filter R dataframe by multiple conditions? R - if statement Replace Specific Characters in String in R Time Series Analysis in R
[ { "code": null, "e": 25242, "s": 25214, "text": "\n23 Sep, 2021" }, { "code": null, "e": 25346, "s": 25242, "text": "In this article, we will discuss how to group data.table by multiple columns in R programming language." }, { "code": null, "e": 25527, "s": 25346, "text": "The package data.table can be used to work with data tables and subsetting and organizing data. It can be downloaded and installed into the workspace using the following command : " }, { "code": null, "e": 25547, "s": 25527, "text": "library(data.table)" }, { "code": null, "e": 25979, "s": 25547, "text": "The column at a specified index can be extracted using the list subsetting, i.e. [, operator. The new column can be added in the second argument assigned to a predefined or a user-defined function defined over a set of columns of data.table. The by argument can be added to group the data using a set of columns from the data table. The list() method can be used to specify a set of columns of the data.table to group the data by. " }, { "code": null, "e": 26025, "s": 25979, "text": "Example: Group data.table by multiple columns" }, { "code": null, "e": 26027, "s": 26025, "text": "R" }, { "code": "library(data.table) # creating first data framedata_frame <- data.table(col1 = rep(LETTERS[1:3],each=2), col2 = c(5:10), col3 = c(TRUE,FALSE) ) print (\"Original DataFrame\")print (data_frame) # group by col1,col3data_mod <- data_frame[ , count:=sum(col2), by = list(col1,col3)] # print modified data frameprint (\"Modified DataFrame\") print(data_mod) ", "e": 26496, "s": 26027, "text": null }, { "code": null, "e": 26504, "s": 26496, "text": "Output:" }, { "code": null, "e": 26876, "s": 26504, "text": "[1] \"Original DataFrame\"\n col1 col2 col3 \n1: A 5 TRUE \n2: A 6 FALSE \n3: B 7 TRUE \n4: B 8 FALSE \n5: C 9 TRUE \n6: C 10 FALSE \n[1] \"Modified DataFrame\" \n col1 col2 col3 count \n1: A 5 TRUE 5 \n2: A 6 FALSE 6 \n3: B 7 TRUE 7 \n4: B 8 FALSE 8 \n5: C 9 TRUE 9 \n6: C 10 FALSE 10" }, { "code": null, "e": 27014, "s": 26876, "text": "In the above example, since none of the groups are the same, therefore, the new column β€œcount” values are equivalent to the col2 values. " }, { "code": null, "e": 27121, "s": 27014, "text": "In case there are columns belonging to the same groups, the sum is generated corresponding to each column." }, { "code": null, "e": 27168, "s": 27121, "text": "Example: Group data.table by multiple columns" }, { "code": null, "e": 27170, "s": 27168, "text": "R" }, { "code": "library(data.table) # creating first data framedata_frame <- data.table(col1 = rep(LETTERS[1:3],each=2), col2 = c(1:6), col3 = TRUE ) print (\"Original DataFrame\")print (data_frame) # group by col1,col3data_mod <- data_frame[ , count:=sum(col2), by = list(col1,col3)] # print modified data frameprint (\"Modified DataFrame\") print(data_mod)", "e": 27609, "s": 27170, "text": null }, { "code": null, "e": 27617, "s": 27609, "text": "Output:" }, { "code": null, "e": 27976, "s": 27617, "text": "[1] \"Original DataFrame\" \n col1 col2 col3 \n1: A 1 TRUE \n2: A 2 TRUE \n3: B 3 TRUE \n4: B 4 TRUE \n5: C 5 TRUE \n6: C 6 TRUE \n[1] \"Modified DataFrame\" \n col1 col2 col3 count \n1: A 1 TRUE 3 \n2: A 2 TRUE 3 \n3: B 3 TRUE 7 \n4: B 4 TRUE 7 \n5: C 5 TRUE 11 \n6: C 6 TRUE 11" }, { "code": null, "e": 28095, "s": 27976, "text": "Grouping of data can also be done using all the columns of the data.table, as indicated in the following code snippet." }, { "code": null, "e": 28141, "s": 28095, "text": "Example: Group data.table by multiple columns" }, { "code": null, "e": 28143, "s": 28141, "text": "R" }, { "code": "library(data.table) # creating first data framedata_frame <- data.table(col1 = rep(LETTERS[1:3],each=2), col2 = c(1,1,3,4,5,6), col3 = 1 )print (\"Original DataFrame\")print (data_frame) # group by col1,col3data_mod <- data_frame[ , count:=sum(col2), by = list(col1,col2,col3)] # print modified data frameprint (\"Modified DataFrame\") print(data_mod)", "e": 28590, "s": 28143, "text": null }, { "code": null, "e": 28598, "s": 28590, "text": "Output:" }, { "code": null, "e": 28951, "s": 28598, "text": "[1] \"Original DataFrame\" \ncol1 col2 col3 \n1: A 1 1 \n2: A 1 1 \n3: B 3 1 \n4: B 4 1 \n5: C 5 1 \n6: C 6 1 \n[1] \"Modified DataFrame\" \ncol1 col2 col3 count \n1: A 1 1 1 \n2: A 1 1 1 \n3: B 3 1 3 \n4: B 4 1 4 \n5: C 5 1 5 \n6: C 6 1 6" }, { "code": null, "e": 28958, "s": 28951, "text": "Picked" }, { "code": null, "e": 28970, "s": 28958, "text": "R DataTable" }, { "code": null, "e": 28981, "s": 28970, "text": "R Language" }, { "code": null, "e": 29079, "s": 28981, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29088, "s": 29079, "text": "Comments" }, { "code": null, "e": 29101, "s": 29088, "text": "Old Comments" }, { "code": null, "e": 29153, "s": 29101, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 29191, "s": 29153, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 29226, "s": 29191, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 29284, "s": 29226, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 29333, "s": 29284, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 29370, "s": 29333, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 29420, "s": 29370, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 29437, "s": 29420, "text": "R - if statement" }, { "code": null, "e": 29480, "s": 29437, "text": "Replace Specific Characters in String in R" } ]
C++ Program For Finding The Middle Element Of A Given Linked List - GeeksforGeeks
08 Dec, 2021 Given a singly linked list, find the middle of the linked list. For example, if the given linked list is 1->2->3->4->5 then the output should be 3. If there are even nodes, then there would be two middle nodes, we need to print the second middle element. For example, if given linked list is 1->2->3->4->5->6 then the output should be 4. Method 1: Traverse the whole linked list and count the no. of nodes. Now traverse the list again till count/2 and return the node at count/2. Method 2: Traverse linked list using two pointers. Move one pointer by one and the other pointers by two. When the fast pointer reaches the end slow pointer will reach the middle of the linked list. Below image shows how printMiddle function works in the code : C++ // C++ program for the above approach #include <iostream>using namespace std; class Node{ public: int data; Node *next;}; class NodeOperation{ public: // Function to add a new node void pushNode(class Node** head_ref,int data_val){ // Allocate node class Node *new_node = new Node(); // Put in the data new_node->data = data_val; // 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; } // A utility function to print a given linked list void printNode(class Node *head){ while(head != NULL){ cout <<head->data << "->"; head = head->next; } cout << "NULL" << endl; } void printMiddle(class Node *head){ struct Node *slow_ptr = head; struct Node *fast_ptr = head; if (head!=NULL) { while (fast_ptr != NULL && fast_ptr->next != NULL) { fast_ptr = fast_ptr->next->next; slow_ptr = slow_ptr->next; } cout << "The middle element is [" << slow_ptr->data << "]" << endl; } }}; // Driver Codeint main(){ class Node *head = NULL; class NodeOperation *temp = new NodeOperation(); for(int i=5; i>0; i--){ temp->pushNode(&head, i); temp->printNode(head); temp->printMiddle(head); } return 0;} 5->NULL The middle element is [5] 4->5->NULL The middle element is [5] 3->4->5->NULL The middle element is [4] 2->3->4->5->NULL The middle element is [4] 1->2->3->4->5->NULL The middle element is [3] Method 3: Initialize mid element as head and initialize a counter as 0. Traverse the list from head, while traversing increment the counter and change mid to mid->next whenever the counter is odd. So the mid will move only half of the total length of the list. Thanks to Narendra Kangralkar for suggesting this method. C++ #include <bits/stdc++.h>using namespace std; // Link list node struct node{ int data; struct node* next;}; // Function to get the middle of// the linked listvoid printMiddle(struct node* head){ int count = 0; struct node* mid = head; while (head != NULL) { // Update mid, when 'count' // is odd number if (count & 1) mid = mid->next; ++count; head = head->next; } // If empty list is provided if (mid != NULL) printf("The middle element is [%d] ", mid->data);} 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;} // A utility function to print // a given linked listvoid printList(struct node* ptr){ while (ptr != NULL) { printf("%d->", ptr->data); ptr = ptr->next; } printf("NULL");} // Driver codeint main(){ // Start with the empty list struct node* head = NULL; int i; for(i = 5; i > 0; i--) { push(&head, i); printList(head); printMiddle(head); } return 0;} // This code is contributed by ac121102 5->NULL The middle element is [5] 4->5->NULL The middle element is [5] 3->4->5->NULL The middle element is [4] 2->3->4->5->NULL The middle element is [4] 1->2->3->4->5->NULL The middle element is [3] Please refer complete article on Find the middle of a given linked list for more details! Adobe Amazon Flipkart GE Hike Linked Lists MAQ Software Microsoft Morgan Stanley Nagarro Payu Qualcomm Samsung Veritas VMWare Wipro Zoho C++ C++ Programs Linked List VMWare Zoho Flipkart Morgan Stanley Amazon Microsoft Samsung Hike Payu MAQ Software Adobe Wipro Qualcomm Nagarro GE Veritas Linked List 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++ Header files in C/C++ and its uses How to return multiple values from a function in C or C++? C++ Program for QuickSort Program to print ASCII Value of a character CSV file management using C++
[ { "code": null, "e": 24176, "s": 24148, "text": "\n08 Dec, 2021" }, { "code": null, "e": 24515, "s": 24176, "text": "Given a singly linked list, find the middle of the linked list. For example, if the given linked list is 1->2->3->4->5 then the output should be 3. If there are even nodes, then there would be two middle nodes, we need to print the second middle element. For example, if given linked list is 1->2->3->4->5->6 then the output should be 4. " }, { "code": null, "e": 24658, "s": 24515, "text": "Method 1: Traverse the whole linked list and count the no. of nodes. Now traverse the list again till count/2 and return the node at count/2. " }, { "code": null, "e": 24857, "s": 24658, "text": "Method 2: Traverse linked list using two pointers. Move one pointer by one and the other pointers by two. When the fast pointer reaches the end slow pointer will reach the middle of the linked list." }, { "code": null, "e": 24920, "s": 24857, "text": "Below image shows how printMiddle function works in the code :" }, { "code": null, "e": 24924, "s": 24920, "text": "C++" }, { "code": "// C++ program for the above approach #include <iostream>using namespace std; class Node{ public: int data; Node *next;}; class NodeOperation{ public: // Function to add a new node void pushNode(class Node** head_ref,int data_val){ // Allocate node class Node *new_node = new Node(); // Put in the data new_node->data = data_val; // 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; } // A utility function to print a given linked list void printNode(class Node *head){ while(head != NULL){ cout <<head->data << \"->\"; head = head->next; } cout << \"NULL\" << endl; } void printMiddle(class Node *head){ struct Node *slow_ptr = head; struct Node *fast_ptr = head; if (head!=NULL) { while (fast_ptr != NULL && fast_ptr->next != NULL) { fast_ptr = fast_ptr->next->next; slow_ptr = slow_ptr->next; } cout << \"The middle element is [\" << slow_ptr->data << \"]\" << endl; } }}; // Driver Codeint main(){ class Node *head = NULL; class NodeOperation *temp = new NodeOperation(); for(int i=5; i>0; i--){ temp->pushNode(&head, i); temp->printNode(head); temp->printMiddle(head); } return 0;}", "e": 26433, "s": 24924, "text": null }, { "code": null, "e": 26637, "s": 26433, "text": "5->NULL\nThe middle element is [5]\n\n4->5->NULL\nThe middle element is [5]\n\n3->4->5->NULL\nThe middle element is [4]\n\n2->3->4->5->NULL\nThe middle element is [4]\n\n1->2->3->4->5->NULL\nThe middle element is [3]" }, { "code": null, "e": 26958, "s": 26637, "text": "Method 3: Initialize mid element as head and initialize a counter as 0. Traverse the list from head, while traversing increment the counter and change mid to mid->next whenever the counter is odd. So the mid will move only half of the total length of the list. Thanks to Narendra Kangralkar for suggesting this method. " }, { "code": null, "e": 26962, "s": 26958, "text": "C++" }, { "code": "#include <bits/stdc++.h>using namespace std; // Link list node struct node{ int data; struct node* next;}; // Function to get the middle of// the linked listvoid printMiddle(struct node* head){ int count = 0; struct node* mid = head; while (head != NULL) { // Update mid, when 'count' // is odd number if (count & 1) mid = mid->next; ++count; head = head->next; } // If empty list is provided if (mid != NULL) printf(\"The middle element is [%d] \", mid->data);} 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;} // A utility function to print // a given linked listvoid printList(struct node* ptr){ while (ptr != NULL) { printf(\"%d->\", ptr->data); ptr = ptr->next; } printf(\"NULL\");} // Driver codeint main(){ // Start with the empty list struct node* head = NULL; int i; for(i = 5; i > 0; i--) { push(&head, i); printList(head); printMiddle(head); } return 0;} // This code is contributed by ac121102", "e": 28380, "s": 26962, "text": null }, { "code": null, "e": 28584, "s": 28380, "text": "5->NULL\nThe middle element is [5]\n\n4->5->NULL\nThe middle element is [5]\n\n3->4->5->NULL\nThe middle element is [4]\n\n2->3->4->5->NULL\nThe middle element is [4]\n\n1->2->3->4->5->NULL\nThe middle element is [3]" }, { "code": null, "e": 28674, "s": 28584, "text": "Please refer complete article on Find the middle of a given linked list for more details!" }, { "code": null, "e": 28680, "s": 28674, "text": "Adobe" }, { "code": null, "e": 28687, "s": 28680, "text": "Amazon" }, { "code": null, "e": 28696, "s": 28687, "text": "Flipkart" }, { "code": null, "e": 28699, "s": 28696, "text": "GE" }, { "code": null, "e": 28704, "s": 28699, "text": "Hike" }, { "code": null, "e": 28717, "s": 28704, "text": "Linked Lists" }, { "code": null, "e": 28730, "s": 28717, "text": "MAQ Software" }, { "code": null, "e": 28740, "s": 28730, "text": "Microsoft" }, { "code": null, "e": 28755, "s": 28740, "text": "Morgan Stanley" }, { "code": null, "e": 28763, "s": 28755, "text": "Nagarro" }, { "code": null, "e": 28768, "s": 28763, "text": "Payu" }, { "code": null, "e": 28777, "s": 28768, "text": "Qualcomm" }, { "code": null, "e": 28785, "s": 28777, "text": "Samsung" }, { "code": null, "e": 28793, "s": 28785, "text": "Veritas" }, { "code": null, "e": 28800, "s": 28793, "text": "VMWare" }, { "code": null, "e": 28806, "s": 28800, "text": "Wipro" }, { "code": null, "e": 28811, "s": 28806, "text": "Zoho" }, { "code": null, "e": 28815, "s": 28811, "text": "C++" }, { "code": null, "e": 28828, "s": 28815, "text": "C++ Programs" }, { "code": null, "e": 28840, "s": 28828, "text": "Linked List" }, { "code": null, "e": 28847, "s": 28840, "text": "VMWare" }, { "code": null, "e": 28852, "s": 28847, "text": "Zoho" }, { "code": null, "e": 28861, "s": 28852, "text": "Flipkart" }, { "code": null, "e": 28876, "s": 28861, "text": "Morgan Stanley" }, { "code": null, "e": 28883, "s": 28876, "text": "Amazon" }, { "code": null, "e": 28893, "s": 28883, "text": "Microsoft" }, { "code": null, "e": 28901, "s": 28893, "text": "Samsung" }, { "code": null, "e": 28906, "s": 28901, "text": "Hike" }, { "code": null, "e": 28911, "s": 28906, "text": "Payu" }, { "code": null, "e": 28924, "s": 28911, "text": "MAQ Software" }, { "code": null, "e": 28930, "s": 28924, "text": "Adobe" }, { "code": null, "e": 28936, "s": 28930, "text": "Wipro" }, { "code": null, "e": 28945, "s": 28936, "text": "Qualcomm" }, { "code": null, "e": 28953, "s": 28945, "text": "Nagarro" }, { "code": null, "e": 28956, "s": 28953, "text": "GE" }, { "code": null, "e": 28964, "s": 28956, "text": "Veritas" }, { "code": null, "e": 28976, "s": 28964, "text": "Linked List" }, { "code": null, "e": 28980, "s": 28976, "text": "CPP" }, { "code": null, "e": 29078, "s": 28980, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29087, "s": 29078, "text": "Comments" }, { "code": null, "e": 29100, "s": 29087, "text": "Old Comments" }, { "code": null, "e": 29128, "s": 29100, "text": "Operator Overloading in C++" }, { "code": null, "e": 29149, "s": 29128, "text": "Iterators in C++ STL" }, { "code": null, "e": 29169, "s": 29149, "text": "Polymorphism in C++" }, { "code": null, "e": 29202, "s": 29169, "text": "Friend class and function in C++" }, { "code": null, "e": 29226, "s": 29202, "text": "Sorting a vector in C++" }, { "code": null, "e": 29261, "s": 29226, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 29320, "s": 29261, "text": "How to return multiple values from a function in C or C++?" }, { "code": null, "e": 29346, "s": 29320, "text": "C++ Program for QuickSort" }, { "code": null, "e": 29390, "s": 29346, "text": "Program to print ASCII Value of a character" } ]
8086 program for selection sort - GeeksforGeeks
22 May, 2018 Problem – Write an assembly language program in 8086 microprocessor to sort a given array of n numbers using Selection Sort. Assumptions – The number of elements in the array is stored at offset 500. The array starts from offset 501. Example – Algorithm – We first find the smallest number in the array.Swap the smallest number from the first element of the array.Keep repeating the process till all elements are traversed. We first find the smallest number in the array. Swap the smallest number from the first element of the array. Keep repeating the process till all elements are traversed. Program – Explanation – Registers AH, AL, BX, CX, DL, SI, DI are used for general purpose: AL - Stored the smallest number AH - Stores the counter for the inner loop BX - Stores the offset of the smallest number of each iteration of the outer loop CX - Stores the counter for the outer loop DL - Helps in swapping the elements SI - Pointer DI - Pointer MOV SI, 500: stores 0500 in SI.MOV CL, [SI]: stores the content at offset SI in CL.XOR CH, CH: stores the result of logical operation XOR b/w CH and CH in CH.INC SI: increase the value of SI by 1.DEC CX: decrease the value of CX by 1.MOV AH, CL: stores the contents of CL in AH.CMP AL, [SI]: compares the content of AL with content at offset SI. If AL < [SI] – Sets Carry Flag(i.e. Carry Flag = 1).JC 41F: jumps to offset 041F, if carry flag is set(1).JNZ 417: jumps to offset 0417, if zero flag is reset(0).XCHG DL, [BX]: swaps the content of DL with content at offset BX.LOOP 40C: decrease the value of CX by 1 and check whether Zero Flag is set(1) or not. If Zero Flag is reset(0), then it jumps to offset 040C.HLT: terminates the program. MOV SI, 500: stores 0500 in SI. MOV CL, [SI]: stores the content at offset SI in CL. XOR CH, CH: stores the result of logical operation XOR b/w CH and CH in CH. INC SI: increase the value of SI by 1. DEC CX: decrease the value of CX by 1. MOV AH, CL: stores the contents of CL in AH. CMP AL, [SI]: compares the content of AL with content at offset SI. If AL < [SI] – Sets Carry Flag(i.e. Carry Flag = 1). JC 41F: jumps to offset 041F, if carry flag is set(1). JNZ 417: jumps to offset 0417, if zero flag is reset(0). XCHG DL, [BX]: swaps the content of DL with content at offset BX. LOOP 40C: decrease the value of CX by 1 and check whether Zero Flag is set(1) or not. If Zero Flag is reset(0), then it jumps to offset 040C. HLT: terminates the program. microprocessor system-programming Computer Organization & Architecture Sorting Sorting microprocessor Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Architecture of 8085 microprocessor Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard) Direct Access Media (DMA) Controller in Computer Architecture Pin diagram of 8086 microprocessor Computer Organization | Different Instruction Cycles
[ { "code": null, "e": 24858, "s": 24830, "text": "\n22 May, 2018" }, { "code": null, "e": 24983, "s": 24858, "text": "Problem – Write an assembly language program in 8086 microprocessor to sort a given array of n numbers using Selection Sort." }, { "code": null, "e": 25092, "s": 24983, "text": "Assumptions – The number of elements in the array is stored at offset 500. The array starts from offset 501." }, { "code": null, "e": 25102, "s": 25092, "text": "Example –" }, { "code": null, "e": 25114, "s": 25102, "text": "Algorithm –" }, { "code": null, "e": 25282, "s": 25114, "text": "We first find the smallest number in the array.Swap the smallest number from the first element of the array.Keep repeating the process till all elements are traversed." }, { "code": null, "e": 25330, "s": 25282, "text": "We first find the smallest number in the array." }, { "code": null, "e": 25392, "s": 25330, "text": "Swap the smallest number from the first element of the array." }, { "code": null, "e": 25452, "s": 25392, "text": "Keep repeating the process till all elements are traversed." }, { "code": null, "e": 25462, "s": 25452, "text": "Program –" }, { "code": null, "e": 25543, "s": 25462, "text": "Explanation – Registers AH, AL, BX, CX, DL, SI, DI are used for general purpose:" }, { "code": null, "e": 25812, "s": 25543, "text": "AL - Stored the smallest number\nAH - Stores the counter for the inner loop\nBX - Stores the offset of the smallest \n number of each iteration of the outer loop\nCX - Stores the counter for the outer loop\nDL - Helps in swapping the elements\nSI - Pointer\nDI - Pointer " }, { "code": null, "e": 26555, "s": 25812, "text": "MOV SI, 500: stores 0500 in SI.MOV CL, [SI]: stores the content at offset SI in CL.XOR CH, CH: stores the result of logical operation XOR b/w CH and CH in CH.INC SI: increase the value of SI by 1.DEC CX: decrease the value of CX by 1.MOV AH, CL: stores the contents of CL in AH.CMP AL, [SI]: compares the content of AL with content at offset SI. If AL < [SI] – Sets Carry Flag(i.e. Carry Flag = 1).JC 41F: jumps to offset 041F, if carry flag is set(1).JNZ 417: jumps to offset 0417, if zero flag is reset(0).XCHG DL, [BX]: swaps the content of DL with content at offset BX.LOOP 40C: decrease the value of CX by 1 and check whether Zero Flag is set(1) or not. If Zero Flag is reset(0), then it jumps to offset 040C.HLT: terminates the program." }, { "code": null, "e": 26587, "s": 26555, "text": "MOV SI, 500: stores 0500 in SI." }, { "code": null, "e": 26640, "s": 26587, "text": "MOV CL, [SI]: stores the content at offset SI in CL." }, { "code": null, "e": 26716, "s": 26640, "text": "XOR CH, CH: stores the result of logical operation XOR b/w CH and CH in CH." }, { "code": null, "e": 26755, "s": 26716, "text": "INC SI: increase the value of SI by 1." }, { "code": null, "e": 26794, "s": 26755, "text": "DEC CX: decrease the value of CX by 1." }, { "code": null, "e": 26839, "s": 26794, "text": "MOV AH, CL: stores the contents of CL in AH." }, { "code": null, "e": 26960, "s": 26839, "text": "CMP AL, [SI]: compares the content of AL with content at offset SI. If AL < [SI] – Sets Carry Flag(i.e. Carry Flag = 1)." }, { "code": null, "e": 27015, "s": 26960, "text": "JC 41F: jumps to offset 041F, if carry flag is set(1)." }, { "code": null, "e": 27072, "s": 27015, "text": "JNZ 417: jumps to offset 0417, if zero flag is reset(0)." }, { "code": null, "e": 27138, "s": 27072, "text": "XCHG DL, [BX]: swaps the content of DL with content at offset BX." }, { "code": null, "e": 27280, "s": 27138, "text": "LOOP 40C: decrease the value of CX by 1 and check whether Zero Flag is set(1) or not. If Zero Flag is reset(0), then it jumps to offset 040C." }, { "code": null, "e": 27309, "s": 27280, "text": "HLT: terminates the program." }, { "code": null, "e": 27324, "s": 27309, "text": "microprocessor" }, { "code": null, "e": 27343, "s": 27324, "text": "system-programming" }, { "code": null, "e": 27380, "s": 27343, "text": "Computer Organization & Architecture" }, { "code": null, "e": 27388, "s": 27380, "text": "Sorting" }, { "code": null, "e": 27396, "s": 27388, "text": "Sorting" }, { "code": null, "e": 27411, "s": 27396, "text": "microprocessor" }, { "code": null, "e": 27509, "s": 27411, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27545, "s": 27509, "text": "Architecture of 8085 microprocessor" }, { "code": null, "e": 27636, "s": 27545, "text": "Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard)" }, { "code": null, "e": 27698, "s": 27636, "text": "Direct Access Media (DMA) Controller in Computer Architecture" }, { "code": null, "e": 27733, "s": 27698, "text": "Pin diagram of 8086 microprocessor" } ]
Add a percentage (%) sign at the end to each value while using MySQL SELECT statement
To add percentage sign at the end, use CONCAT() function. Let us first create a table βˆ’ mysql> create table DemoTable ( StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, StudentName varchar(100), StudentScore int ); Query OK, 0 rows affected (0.68 sec) Insert some records in the table using insert command βˆ’ mysql> insert into DemoTable(StudentName,StudentScore) values('John',65); Query OK, 1 row affected (0.09 sec) mysql> insert into DemoTable(StudentName,StudentScore) values('Chris',98); Query OK, 1 row affected (0.30 sec) mysql> insert into DemoTable(StudentName,StudentScore) values('Robert',91); Query OK, 1 row affected (0.09 sec) Display all records from the table using select statement βˆ’ mysql> select *from DemoTable; This will produce the following output βˆ’ +-----------+-------------+--------------+ | StudentId | StudentName | StudentScore | +-----------+-------------+--------------+ | 1 | John | 65 | | 2 | Chris | 98 | | 3 | Robert | 91 | +-----------+-------------+--------------+ 3 rows in set (0.00 sec) Following is the query to add a percentage (%) sign to each value at the end while using MySQL SELECT statement βˆ’ mysql> select StudentId,StudentName,concat(StudentScore,'%') AS StudentScore from DemoTable; This will produce the following output βˆ’ +-----------+-------------+--------------+ | StudentId | StudentName | StudentScore | +-----------+-------------+--------------+ | 1 | John | 65% | | 2 | Chris | 98% | | 3 | Robert | 91% | +-----------+-------------+--------------+ 3 rows in set (0.00 sec)
[ { "code": null, "e": 1150, "s": 1062, "text": "To add percentage sign at the end, use CONCAT() function. Let us first create a table βˆ’" }, { "code": null, "e": 1325, "s": 1150, "text": "mysql> create table DemoTable\n(\n StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n StudentName varchar(100),\n StudentScore int\n);\nQuery OK, 0 rows affected (0.68 sec)" }, { "code": null, "e": 1381, "s": 1325, "text": "Insert some records in the table using insert command βˆ’" }, { "code": null, "e": 1714, "s": 1381, "text": "mysql> insert into DemoTable(StudentName,StudentScore) values('John',65);\nQuery OK, 1 row affected (0.09 sec)\nmysql> insert into DemoTable(StudentName,StudentScore) values('Chris',98);\nQuery OK, 1 row affected (0.30 sec)\nmysql> insert into DemoTable(StudentName,StudentScore) values('Robert',91);\nQuery OK, 1 row affected (0.09 sec)" }, { "code": null, "e": 1774, "s": 1714, "text": "Display all records from the table using select statement βˆ’" }, { "code": null, "e": 1805, "s": 1774, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 1846, "s": 1805, "text": "This will produce the following output βˆ’" }, { "code": null, "e": 2172, "s": 1846, "text": "+-----------+-------------+--------------+\n| StudentId | StudentName | StudentScore |\n+-----------+-------------+--------------+\n| 1 | John | 65 |\n| 2 | Chris | 98 |\n| 3 | Robert | 91 |\n+-----------+-------------+--------------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 2286, "s": 2172, "text": "Following is the query to add a percentage (%) sign to each value at the end while using MySQL SELECT statement βˆ’" }, { "code": null, "e": 2379, "s": 2286, "text": "mysql> select StudentId,StudentName,concat(StudentScore,'%') AS StudentScore from DemoTable;" }, { "code": null, "e": 2420, "s": 2379, "text": "This will produce the following output βˆ’" }, { "code": null, "e": 2746, "s": 2420, "text": "+-----------+-------------+--------------+\n| StudentId | StudentName | StudentScore |\n+-----------+-------------+--------------+\n| 1 | John | 65% |\n| 2 | Chris | 98% |\n| 3 | Robert | 91% |\n+-----------+-------------+--------------+\n3 rows in set (0.00 sec)" } ]
Spring Boot MockMvc JUnit Test Example - onlinetutorialspoint
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws In this tutorial, we are going to write JUnit test cases for the Spring Boot controller. Spring MVC test framework provides MockMvc class to test the controllers by initiating the Servlet container. Here I am going to write unit test cases for our previous Spring Boot Exception Handling Example. Spring Boot 2.0.4 Spring Boot Starter Test 2.0.4 JUnit 4.12 Java8 <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> A simple rest controller which provides all crud operations on ItemRepoitory. package com.onlinetutorialspoint.controller; import com.onlinetutorialspoint.exception.ItemNotFoundException; import com.onlinetutorialspoint.model.Item; import com.onlinetutorialspoint.repo.ItemRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController public class ItemController { @Autowired ItemRepository itemRepo; @RequestMapping("/getAllItems") @ResponseBody public ResponseEntity<List<Item>> getAllItems(){ List<Item> items = itemRepo.getAllItems(); return new ResponseEntity<List<Item>>(items, HttpStatus.OK); } @GetMapping("/item/{itemId}") @ResponseBody public ResponseEntity<Item> getItem(@PathVariable int itemId){ if(itemId <= 0){ throw new ItemNotFoundException("Invalid ItemId"); } Item item = itemRepo.getItem(itemId); return new ResponseEntity<Item>(item, HttpStatus.OK); } @PostMapping(value = "/addItem",consumes = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<Item> addItem(@RequestBody Item item){ itemRepo.addItem(item); return new ResponseEntity<Item>(item, HttpStatus.CREATED); } @PutMapping("/updateItem") @ResponseBody public ResponseEntity<Item> updateItem(@RequestBody Item item){ if(item != null){ itemRepo.updateItem(item); } return new ResponseEntity<Item>(item, HttpStatus.OK); } @DeleteMapping("/delete/{id}") @ResponseBody public ResponseEntity<Void> deleteItem(@PathVariable int id){ itemRepo.deleteItem(id); return new ResponseEntity<Void>(HttpStatus.ACCEPTED); } } Creating ItemControllerTest to perform all test cases against ItemController class. package com.onlinetutorialspoint.controller; import com.onlinetutorialspoint.model.Item; import com.onlinetutorialspoint.repo.ItemRepository; import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import java.util.Arrays; import java.util.List; @RunWith(SpringRunner.class) public class ItemControllerTest { private MockMvc mockMvc; @InjectMocks ItemController itemController; @Mock ItemRepository itemRepository; @Before public void setUp(){ mockMvc = MockMvcBuilders.standaloneSetup(itemController) .build(); } @Test public void getAllItems() throws Exception { List<Item> items = Arrays.asList(new Item(1,"iPhoneX","Mobiles")); Mockito.when(itemRepository.getAllItems()).thenReturn(items); mockMvc.perform(MockMvcRequestBuilders.get("/getAllItems")) .andExpect(MockMvcResultMatchers.status().isOk()); } @Test public void getItem() throws Exception{ Item item = new Item(1,"iPhoneX","Mobiles"); Mockito.when(itemRepository.getItem(1)).thenReturn(item); mockMvc.perform(MockMvcRequestBuilders.get("/item/1") .accept(MediaType.APPLICATION_JSON)) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.jsonPath("$.id", Matchers.is(1))) .andExpect(MockMvcResultMatchers.jsonPath("$.name",Matchers.is("iPhoneX"))) .andExpect(MockMvcResultMatchers.jsonPath("$.category",Matchers.is("Mobiles"))); Mockito.verify(itemRepository).getItem(1); } @Test public void addItem() throws Exception { String jsonString = "{\n" + "\"id\":1,\n" + "\"name\":\"iPhoneX\",\n" + "\"category\":\"Mobiles\"\n" + "}"; Item item = new Item(1,"iPhoneX","Mobiles"); mockMvc.perform(MockMvcRequestBuilders.post("/addItem") .contentType(MediaType.APPLICATION_JSON) .content(jsonString)) .andExpect(MockMvcResultMatchers.status().isCreated()) .andExpect(MockMvcResultMatchers.jsonPath("$.id", Matchers.is(1))) .andExpect(MockMvcResultMatchers.jsonPath("$.name",Matchers.is("iPhoneX"))) .andExpect(MockMvcResultMatchers.jsonPath("$.category",Matchers.is("Mobiles"))); } @Test public void updateItem() throws Exception { String jsonString = "{\n" + "\"id\":1,\n" + "\"name\":\"iPhoneX\",\n" + "\"category\":\"Mobiles\"\n" + "}"; Item item = new Item(1,"iPhoneX","Mobiles"); mockMvc.perform(MockMvcRequestBuilders.put("/updateItem") .contentType(MediaType.APPLICATION_JSON) .content(jsonString)) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.jsonPath("$.id", Matchers.is(1))) .andExpect(MockMvcResultMatchers.jsonPath("$.name",Matchers.is("iPhoneX"))) .andExpect(MockMvcResultMatchers.jsonPath("$.category",Matchers.is("Mobiles"))); } @Test public void deleteItem() throws Exception{ mockMvc.perform(MockMvcRequestBuilders.delete("/delete/1") .accept(MediaType.APPLICATION_JSON)) .andExpect(MockMvcResultMatchers.status().isAccepted()); } } Run It. Spring Boot MVC Test Happy Learning πŸ™‚ How to fix BeanDefinitionOverrideException Spring Boot Hazelcast Cache Example Spring Boot EhCache Example Spring boot exception handling rest service (CRUD) operations Spring Boot Redis Cache Example – Redis Server Spring Boot DataRest Example RepositoryRestResource Simple Spring Boot Example Spring Boot MongoDB + Spring Data Example How to change Spring Boot Tomcat Port Number How To Change Spring Boot Context Path How to Create own Spring Boot Error Page How to set Spring Boot Tomcat session timeout Spring Boot JdbcTemplate CRUD Operations Mysql Spring Boot H2 Database + JDBC Template Example Spring Boot JNDI Configuration – External Tomcat How to fix BeanDefinitionOverrideException Spring Boot Hazelcast Cache Example Spring Boot EhCache Example Spring boot exception handling rest service (CRUD) operations Spring Boot Redis Cache Example – Redis Server Spring Boot DataRest Example RepositoryRestResource Simple Spring Boot Example Spring Boot MongoDB + Spring Data Example How to change Spring Boot Tomcat Port Number How To Change Spring Boot Context Path How to Create own Spring Boot Error Page How to set Spring Boot Tomcat session timeout Spring Boot JdbcTemplate CRUD Operations Mysql Spring Boot H2 Database + JDBC Template Example Spring Boot JNDI Configuration – External Tomcat Yash Patel December 17, 2021 at 2:51 pm - Reply How can i get this source code? Yash Patel December 17, 2021 at 2:51 pm - Reply How can i get this source code? How can i get this source code? Ξ” Spring Boot – Hello World Spring Boot – MVC Example Spring Boot- Change Context Path Spring Boot – Change Tomcat Port Number Spring Boot – Change Tomcat to Jetty Server Spring Boot – Tomcat session timeout Spring Boot – Enable Random Port Spring Boot – Properties File Spring Boot – Beans Lazy Loading Spring Boot – Set Favicon image Spring Boot – Set Custom Banner Spring Boot – Set Application TimeZone Spring Boot – Send Mail Spring Boot – FileUpload Ajax Spring Boot – Actuator Spring Boot – Actuator Database Health Check Spring Boot – Swagger Spring Boot – Enable CORS Spring Boot – External Apache ActiveMQ Setup Spring Boot – Inmemory Apache ActiveMq Spring Boot – Scheduler Job Spring Boot – Exception Handling Spring Boot – Hibernate CRUD Spring Boot – JPA Integration CRUD Spring Boot – JPA DataRest CRUD Spring Boot – JdbcTemplate CRUD Spring Boot – Multiple Data Sources Config Spring Boot – JNDI Configuration Spring Boot – H2 Database CRUD Spring Boot – MongoDB CRUD Spring Boot – Redis Data CRUD Spring Boot – MVC Login Form Validation Spring Boot – Custom Error Pages Spring Boot – iText PDF Spring Boot – Enable SSL (HTTPs) Spring Boot – Basic Authentication Spring Boot – In Memory Basic Authentication Spring Boot – Security MySQL Database Integration Spring Boot – Redis Cache – Redis Server Spring Boot – Hazelcast Cache Spring Boot – EhCache Spring Boot – Kafka Producer Spring Boot – Kafka Consumer Spring Boot – Kafka JSON Message to Kafka Topic Spring Boot – RabbitMQ Publisher Spring Boot – RabbitMQ Consumer Spring Boot – SOAP Consumer Spring Boot – Soap WebServices Spring Boot – Batch Csv to Database Spring Boot – Eureka Server Spring Boot – MockMvc JUnit Spring Boot – Docker Deployment
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 487, "s": 398, "text": "In this tutorial, we are going to write JUnit test cases for the Spring Boot controller." }, { "code": null, "e": 597, "s": 487, "text": "Spring MVC test framework provides MockMvc class to test the controllers by initiating the Servlet container." }, { "code": null, "e": 695, "s": 597, "text": "Here I am going to write unit test cases for our previous Spring Boot Exception Handling Example." }, { "code": null, "e": 713, "s": 695, "text": "Spring Boot 2.0.4" }, { "code": null, "e": 744, "s": 713, "text": "Spring Boot Starter Test 2.0.4" }, { "code": null, "e": 755, "s": 744, "text": "JUnit 4.12" }, { "code": null, "e": 761, "s": 755, "text": "Java8" }, { "code": null, "e": 1079, "s": 761, "text": "<dependencies>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-web</artifactId>\n </dependency>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-test</artifactId>\n <scope>test</scope>\n </dependency>\n</dependencies>" }, { "code": null, "e": 1157, "s": 1079, "text": "A simple rest controller which provides all crud operations on ItemRepoitory." }, { "code": null, "e": 3032, "s": 1157, "text": "package com.onlinetutorialspoint.controller;\n\nimport com.onlinetutorialspoint.exception.ItemNotFoundException;\nimport com.onlinetutorialspoint.model.Item;\nimport com.onlinetutorialspoint.repo.ItemRepository;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.http.MediaType;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.web.bind.annotation.*;\n\nimport java.util.List;\n\n@RestController\npublic class ItemController {\n @Autowired\n ItemRepository itemRepo;\n\n @RequestMapping(\"/getAllItems\")\n @ResponseBody\n public ResponseEntity<List<Item>> getAllItems(){\n List<Item> items = itemRepo.getAllItems();\n return new ResponseEntity<List<Item>>(items, HttpStatus.OK);\n }\n\n @GetMapping(\"/item/{itemId}\")\n @ResponseBody\n public ResponseEntity<Item> getItem(@PathVariable int itemId){\n if(itemId <= 0){\n throw new ItemNotFoundException(\"Invalid ItemId\");\n }\n Item item = itemRepo.getItem(itemId);\n return new ResponseEntity<Item>(item, HttpStatus.OK);\n }\n\n @PostMapping(value = \"/addItem\",consumes = MediaType.APPLICATION_JSON_VALUE)\n public ResponseEntity<Item> addItem(@RequestBody Item item){\n itemRepo.addItem(item);\n return new ResponseEntity<Item>(item, HttpStatus.CREATED);\n }\n\n @PutMapping(\"/updateItem\")\n @ResponseBody\n public ResponseEntity<Item> updateItem(@RequestBody Item item){\n if(item != null){\n itemRepo.updateItem(item);\n }\n return new ResponseEntity<Item>(item, HttpStatus.OK);\n }\n\n @DeleteMapping(\"/delete/{id}\")\n @ResponseBody\n public ResponseEntity<Void> deleteItem(@PathVariable int id){\n itemRepo.deleteItem(id);\n return new ResponseEntity<Void>(HttpStatus.ACCEPTED);\n }\n}\n" }, { "code": null, "e": 3116, "s": 3032, "text": "Creating ItemControllerTest to perform all test cases against ItemController class." }, { "code": null, "e": 7080, "s": 3116, "text": "package com.onlinetutorialspoint.controller;\n\nimport com.onlinetutorialspoint.model.Item;\nimport com.onlinetutorialspoint.repo.ItemRepository;\nimport org.hamcrest.Matchers;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.mockito.InjectMocks;\nimport org.mockito.Mock;\nimport org.mockito.Mockito;\nimport org.springframework.http.MediaType;\nimport org.springframework.test.context.junit4.SpringRunner;\nimport org.springframework.test.web.servlet.MockMvc;\nimport org.springframework.test.web.servlet.request.MockMvcRequestBuilders;\nimport org.springframework.test.web.servlet.result.MockMvcResultMatchers;\nimport org.springframework.test.web.servlet.setup.MockMvcBuilders;\n\nimport java.util.Arrays;\nimport java.util.List;\n\n@RunWith(SpringRunner.class)\npublic class ItemControllerTest {\n\n private MockMvc mockMvc;\n @InjectMocks\n ItemController itemController;\n @Mock\n ItemRepository itemRepository;\n\n @Before\n public void setUp(){\n mockMvc = MockMvcBuilders.standaloneSetup(itemController)\n .build();\n }\n @Test\n public void getAllItems() throws Exception {\n List<Item> items = Arrays.asList(new Item(1,\"iPhoneX\",\"Mobiles\"));\n Mockito.when(itemRepository.getAllItems()).thenReturn(items);\n mockMvc.perform(MockMvcRequestBuilders.get(\"/getAllItems\"))\n .andExpect(MockMvcResultMatchers.status().isOk());\n\n }\n\n @Test\n public void getItem() throws Exception{\n Item item = new Item(1,\"iPhoneX\",\"Mobiles\");\n Mockito.when(itemRepository.getItem(1)).thenReturn(item);\n mockMvc.perform(MockMvcRequestBuilders.get(\"/item/1\")\n .accept(MediaType.APPLICATION_JSON))\n .andExpect(MockMvcResultMatchers.status().isOk())\n .andExpect(MockMvcResultMatchers.jsonPath(\"$.id\", Matchers.is(1)))\n .andExpect(MockMvcResultMatchers.jsonPath(\"$.name\",Matchers.is(\"iPhoneX\")))\n .andExpect(MockMvcResultMatchers.jsonPath(\"$.category\",Matchers.is(\"Mobiles\")));\n Mockito.verify(itemRepository).getItem(1);\n }\n\n @Test\n public void addItem() throws Exception {\n String jsonString = \"{\\n\" +\n \"\\\"id\\\":1,\\n\" +\n \"\\\"name\\\":\\\"iPhoneX\\\",\\n\" +\n \"\\\"category\\\":\\\"Mobiles\\\"\\n\" +\n \"}\";\n Item item = new Item(1,\"iPhoneX\",\"Mobiles\");\n mockMvc.perform(MockMvcRequestBuilders.post(\"/addItem\")\n .contentType(MediaType.APPLICATION_JSON)\n .content(jsonString))\n .andExpect(MockMvcResultMatchers.status().isCreated())\n .andExpect(MockMvcResultMatchers.jsonPath(\"$.id\", Matchers.is(1)))\n .andExpect(MockMvcResultMatchers.jsonPath(\"$.name\",Matchers.is(\"iPhoneX\")))\n .andExpect(MockMvcResultMatchers.jsonPath(\"$.category\",Matchers.is(\"Mobiles\")));\n }\n\n @Test\n public void updateItem() throws Exception {\n String jsonString = \"{\\n\" +\n \"\\\"id\\\":1,\\n\" +\n \"\\\"name\\\":\\\"iPhoneX\\\",\\n\" +\n \"\\\"category\\\":\\\"Mobiles\\\"\\n\" +\n \"}\";\n Item item = new Item(1,\"iPhoneX\",\"Mobiles\");\n mockMvc.perform(MockMvcRequestBuilders.put(\"/updateItem\")\n .contentType(MediaType.APPLICATION_JSON)\n .content(jsonString))\n .andExpect(MockMvcResultMatchers.status().isOk())\n .andExpect(MockMvcResultMatchers.jsonPath(\"$.id\", Matchers.is(1)))\n .andExpect(MockMvcResultMatchers.jsonPath(\"$.name\",Matchers.is(\"iPhoneX\")))\n .andExpect(MockMvcResultMatchers.jsonPath(\"$.category\",Matchers.is(\"Mobiles\")));\n }\n\n @Test\n public void deleteItem() throws Exception{\n mockMvc.perform(MockMvcRequestBuilders.delete(\"/delete/1\")\n .accept(MediaType.APPLICATION_JSON))\n .andExpect(MockMvcResultMatchers.status().isAccepted());\n }\n}" }, { "code": null, "e": 7088, "s": 7080, "text": "Run It." }, { "code": null, "e": 7109, "s": 7088, "text": "Spring Boot MVC Test" }, { "code": null, "e": 7126, "s": 7109, "text": "Happy Learning πŸ™‚" }, { "code": null, "e": 7780, "s": 7126, "text": "\nHow to fix BeanDefinitionOverrideException\nSpring Boot Hazelcast Cache Example\nSpring Boot EhCache Example\nSpring boot exception handling rest service (CRUD) operations\nSpring Boot Redis Cache Example – Redis Server\nSpring Boot DataRest Example RepositoryRestResource\nSimple Spring Boot Example\nSpring Boot MongoDB + Spring Data Example\nHow to change Spring Boot Tomcat Port Number\nHow To Change Spring Boot Context Path\nHow to Create own Spring Boot Error Page\nHow to set Spring Boot Tomcat session timeout\nSpring Boot JdbcTemplate CRUD Operations Mysql\nSpring Boot H2 Database + JDBC Template Example\nSpring Boot JNDI Configuration – External Tomcat\n" }, { "code": null, "e": 7823, "s": 7780, "text": "How to fix BeanDefinitionOverrideException" }, { "code": null, "e": 7859, "s": 7823, "text": "Spring Boot Hazelcast Cache Example" }, { "code": null, "e": 7887, "s": 7859, "text": "Spring Boot EhCache Example" }, { "code": null, "e": 7949, "s": 7887, "text": "Spring boot exception handling rest service (CRUD) operations" }, { "code": null, "e": 7996, "s": 7949, "text": "Spring Boot Redis Cache Example – Redis Server" }, { "code": null, "e": 8048, "s": 7996, "text": "Spring Boot DataRest Example RepositoryRestResource" }, { "code": null, "e": 8075, "s": 8048, "text": "Simple Spring Boot Example" }, { "code": null, "e": 8117, "s": 8075, "text": "Spring Boot MongoDB + Spring Data Example" }, { "code": null, "e": 8162, "s": 8117, "text": "How to change Spring Boot Tomcat Port Number" }, { "code": null, "e": 8201, "s": 8162, "text": "How To Change Spring Boot Context Path" }, { "code": null, "e": 8242, "s": 8201, "text": "How to Create own Spring Boot Error Page" }, { "code": null, "e": 8288, "s": 8242, "text": "How to set Spring Boot Tomcat session timeout" }, { "code": null, "e": 8335, "s": 8288, "text": "Spring Boot JdbcTemplate CRUD Operations Mysql" }, { "code": null, "e": 8383, "s": 8335, "text": "Spring Boot H2 Database + JDBC Template Example" }, { "code": null, "e": 8432, "s": 8383, "text": "Spring Boot JNDI Configuration – External Tomcat" }, { "code": null, "e": 8525, "s": 8432, "text": "\n\n\n\n\n\nYash Patel\nDecember 17, 2021 at 2:51 pm - Reply \n\nHow can i get this source code?\n\n\n\n\n" }, { "code": null, "e": 8616, "s": 8525, "text": "\n\n\n\n\nYash Patel\nDecember 17, 2021 at 2:51 pm - Reply \n\nHow can i get this source code?\n\n\n\n" }, { "code": null, "e": 8648, "s": 8616, "text": "How can i get this source code?" }, { "code": null, "e": 8654, "s": 8652, "text": "Ξ”" }, { "code": null, "e": 8681, "s": 8654, "text": " Spring Boot – Hello World" }, { "code": null, "e": 8708, "s": 8681, "text": " Spring Boot – MVC Example" }, { "code": null, "e": 8742, "s": 8708, "text": " Spring Boot- Change Context Path" }, { "code": null, "e": 8783, "s": 8742, "text": " Spring Boot – Change Tomcat Port Number" }, { "code": null, "e": 8828, "s": 8783, "text": " Spring Boot – Change Tomcat to Jetty Server" }, { "code": null, "e": 8866, "s": 8828, "text": " Spring Boot – Tomcat session timeout" }, { "code": null, "e": 8900, "s": 8866, "text": " Spring Boot – Enable Random Port" }, { "code": null, "e": 8931, "s": 8900, "text": " Spring Boot – Properties File" }, { "code": null, "e": 8965, "s": 8931, "text": " Spring Boot – Beans Lazy Loading" }, { "code": null, "e": 8998, "s": 8965, "text": " Spring Boot – Set Favicon image" }, { "code": null, "e": 9031, "s": 8998, "text": " Spring Boot – Set Custom Banner" }, { "code": null, "e": 9071, "s": 9031, "text": " Spring Boot – Set Application TimeZone" }, { "code": null, "e": 9096, "s": 9071, "text": " Spring Boot – Send Mail" }, { "code": null, "e": 9127, "s": 9096, "text": " Spring Boot – FileUpload Ajax" }, { "code": null, "e": 9151, "s": 9127, "text": " Spring Boot – Actuator" }, { "code": null, "e": 9197, "s": 9151, "text": " Spring Boot – Actuator Database Health Check" }, { "code": null, "e": 9220, "s": 9197, "text": " Spring Boot – Swagger" }, { "code": null, "e": 9247, "s": 9220, "text": " Spring Boot – Enable CORS" }, { "code": null, "e": 9293, "s": 9247, "text": " Spring Boot – External Apache ActiveMQ Setup" }, { "code": null, "e": 9333, "s": 9293, "text": " Spring Boot – Inmemory Apache ActiveMq" }, { "code": null, "e": 9362, "s": 9333, "text": " Spring Boot – Scheduler Job" }, { "code": null, "e": 9396, "s": 9362, "text": " Spring Boot – Exception Handling" }, { "code": null, "e": 9426, "s": 9396, "text": " Spring Boot – Hibernate CRUD" }, { "code": null, "e": 9462, "s": 9426, "text": " Spring Boot – JPA Integration CRUD" }, { "code": null, "e": 9495, "s": 9462, "text": " Spring Boot – JPA DataRest CRUD" }, { "code": null, "e": 9528, "s": 9495, "text": " Spring Boot – JdbcTemplate CRUD" }, { "code": null, "e": 9572, "s": 9528, "text": " Spring Boot – Multiple Data Sources Config" }, { "code": null, "e": 9606, "s": 9572, "text": " Spring Boot – JNDI Configuration" }, { "code": null, "e": 9638, "s": 9606, "text": " Spring Boot – H2 Database CRUD" }, { "code": null, "e": 9666, "s": 9638, "text": " Spring Boot – MongoDB CRUD" }, { "code": null, "e": 9697, "s": 9666, "text": " Spring Boot – Redis Data CRUD" }, { "code": null, "e": 9738, "s": 9697, "text": " Spring Boot – MVC Login Form Validation" }, { "code": null, "e": 9772, "s": 9738, "text": " Spring Boot – Custom Error Pages" }, { "code": null, "e": 9797, "s": 9772, "text": " Spring Boot – iText PDF" }, { "code": null, "e": 9831, "s": 9797, "text": " Spring Boot – Enable SSL (HTTPs)" }, { "code": null, "e": 9867, "s": 9831, "text": " Spring Boot – Basic Authentication" }, { "code": null, "e": 9913, "s": 9867, "text": " Spring Boot – In Memory Basic Authentication" }, { "code": null, "e": 9964, "s": 9913, "text": " Spring Boot – Security MySQL Database Integration" }, { "code": null, "e": 10006, "s": 9964, "text": " Spring Boot – Redis Cache – Redis Server" }, { "code": null, "e": 10037, "s": 10006, "text": " Spring Boot – Hazelcast Cache" }, { "code": null, "e": 10060, "s": 10037, "text": " Spring Boot – EhCache" }, { "code": null, "e": 10090, "s": 10060, "text": " Spring Boot – Kafka Producer" }, { "code": null, "e": 10120, "s": 10090, "text": " Spring Boot – Kafka Consumer" }, { "code": null, "e": 10169, "s": 10120, "text": " Spring Boot – Kafka JSON Message to Kafka Topic" }, { "code": null, "e": 10203, "s": 10169, "text": " Spring Boot – RabbitMQ Publisher" }, { "code": null, "e": 10236, "s": 10203, "text": " Spring Boot – RabbitMQ Consumer" }, { "code": null, "e": 10265, "s": 10236, "text": " Spring Boot – SOAP Consumer" }, { "code": null, "e": 10297, "s": 10265, "text": " Spring Boot – Soap WebServices" }, { "code": null, "e": 10334, "s": 10297, "text": " Spring Boot – Batch Csv to Database" }, { "code": null, "e": 10363, "s": 10334, "text": " Spring Boot – Eureka Server" }, { "code": null, "e": 10392, "s": 10363, "text": " Spring Boot – MockMvc JUnit" } ]
Protobuf - Enums
enum is one of the composite datatypes of Protobuf. It translates to an enum in the languages that we use, for example, Java. Continuing with our theater example, following is the syntax that we need to have to instruct Protobuf that we will be creating an enum βˆ’ syntax = "proto3"; package theater; option java_package = "com.tutorialspoint.theater"; message Theater { enum PAYMENT_SYSTEM{ CASH = 0; CREDIT_CARD = 1; DEBIT_CARD = 2; APP = 3; } PAYMENT_SYSTEM payment = 7; } Now our message class contains an Enum for payment. Each of them also has a position which is what Protobuf uses while serialization and deserialization. Each attribute of a member needs to have a unique number assigned. We define the enum and use it below as the data type along with "payment" attribute. Note that although we have defined enum inside the message class, it can also reside outside of it. To use Protobuf, we will now have to use protoc binary to create the required classes from this ".proto" file. Let us see how to do that βˆ’ protoc --java_out=java/src/main/java proto_files\theater.proto The above command should create the required files and now we can use it in our Java code. First, we will create a writer to write the theater information βˆ’ package com.tutorialspoint.theater; import java.io.FileOutputStream; import java.io.IOException; import com.tutorialspoint.theater.TheaterOuterClass.Theater; import com.tutorialspoint.theater.TheaterOuterClass.Theater.PAYMENT_SYSTEM; public class TheaterWriter{ public static void main(String[] args) throws IOException { Theater theater = Theater.newBuilder() .setPayment(PAYMENT_SYSTEM.CREDIT_CARD) .build(); String filename = "theater_protobuf_output"; System.out.println("Saving theater information to file: " + filename); try(FileOutputStream output = new FileOutputStream(filename)){ theater.writeTo(output); } System.out.println("Saved theater information with following data to disk: \n" + theater); } } Next, we have a reader to read the theater information βˆ’ package com.tutorialspoint.theater; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import com.tutorialspoint.greeting.Greeting.Greet; import com.tutorialspoint.theater.TheaterOuterClass.Theater; import com.tutorialspoint.theater.TheaterOuterClass.Theater.Builder; public class TheaterReader{ public static void main(String[] args) throws IOException { Builder theaterBuilder = Theater.newBuilder(); String filename = "theater_protobuf_output"; System.out.println("Reading from file " + filename); try(FileInputStream input = new FileInputStream(filename)) { Theater theater = theaterBuilder.mergeFrom(input).build(); System.out.println(theater.getBaseTicketPrice()); System.out.println(theater); } } } Now, post compilation, let us execute the writer first βˆ’ > java -cp .\target\protobuf-tutorial-1.0.jar com.tutorialspoint.theater.TheaterWriter Saving theater information to file: theater_protobuf_output Saved theater information with following data to disk: payment: CREDIT_CARD Now, let us execute the reader to read from the same file βˆ’ java -cp .\target\protobuf-tutorial-1.0.jar com.tutorialspoint.theater.TheaterReader Reading from file theater_protobuf_output payment: CREDIT_CARD So, as we see, we are able to read the serialized enum by deserializing the binary data to Theater object. In the next chapter, we will take a look at Protobuf lists. Print Add Notes Bookmark this page
[ { "code": null, "e": 2171, "s": 2045, "text": "enum is one of the composite datatypes of Protobuf. It translates to an enum in the languages that we use, for example, Java." }, { "code": null, "e": 2309, "s": 2171, "text": "Continuing with our theater example, following is the syntax that we need to have to instruct Protobuf that we will be creating an enum βˆ’" }, { "code": null, "e": 2563, "s": 2309, "text": "syntax = \"proto3\";\npackage theater;\noption java_package = \"com.tutorialspoint.theater\";\n \nmessage Theater {\n enum PAYMENT_SYSTEM{\n CASH = 0;\n CREDIT_CARD = 1;\n DEBIT_CARD = 2;\n APP = 3; \n }\n PAYMENT_SYSTEM payment = 7;\n}\n" }, { "code": null, "e": 2784, "s": 2563, "text": "Now our message class contains an Enum for payment. Each of them also has a position which is what Protobuf uses while serialization and deserialization. Each attribute of a member needs to have a unique number assigned." }, { "code": null, "e": 2969, "s": 2784, "text": "We define the enum and use it below as the data type along with \"payment\" attribute. Note that although we have defined enum inside the message class, it can also reside outside of it." }, { "code": null, "e": 3108, "s": 2969, "text": "To use Protobuf, we will now have to use protoc binary to create the required classes from this \".proto\" file. Let us see how to do that βˆ’" }, { "code": null, "e": 3173, "s": 3108, "text": "protoc --java_out=java/src/main/java proto_files\\theater.proto\n" }, { "code": null, "e": 3330, "s": 3173, "text": "The above command should create the required files and now we can use it in our Java code. First, we will create a writer to write the theater information βˆ’" }, { "code": null, "e": 4126, "s": 3330, "text": "package com.tutorialspoint.theater;\n\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport com.tutorialspoint.theater.TheaterOuterClass.Theater;\nimport com.tutorialspoint.theater.TheaterOuterClass.Theater.PAYMENT_SYSTEM;\n\npublic class TheaterWriter{\n public static void main(String[] args) throws IOException {\n Theater theater = Theater.newBuilder()\n .setPayment(PAYMENT_SYSTEM.CREDIT_CARD)\n .build();\n\t\t\n String filename = \"theater_protobuf_output\";\n System.out.println(\"Saving theater information to file: \" + filename);\n\t\t\n try(FileOutputStream output = new FileOutputStream(filename)){\n theater.writeTo(output);\n }\n\t \n System.out.println(\"Saved theater information with following data to disk: \\n\" + theater);\n }\n}\t" }, { "code": null, "e": 4183, "s": 4126, "text": "Next, we have a reader to read the theater information βˆ’" }, { "code": null, "e": 5006, "s": 4183, "text": "package com.tutorialspoint.theater;\n\nimport java.io.FileInputStream;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport com.tutorialspoint.greeting.Greeting.Greet;\nimport com.tutorialspoint.theater.TheaterOuterClass.Theater;\nimport com.tutorialspoint.theater.TheaterOuterClass.Theater.Builder;\n\npublic class TheaterReader{\n public static void main(String[] args) throws IOException {\n Builder theaterBuilder = Theater.newBuilder();\n\n String filename = \"theater_protobuf_output\";\n System.out.println(\"Reading from file \" + filename);\n \n try(FileInputStream input = new FileInputStream(filename)) {\n Theater theater = theaterBuilder.mergeFrom(input).build();\n System.out.println(theater.getBaseTicketPrice());\n System.out.println(theater);\n }\n }\n}" }, { "code": null, "e": 5063, "s": 5006, "text": "Now, post compilation, let us execute the writer first βˆ’" }, { "code": null, "e": 5288, "s": 5063, "text": "> java -cp .\\target\\protobuf-tutorial-1.0.jar com.tutorialspoint.theater.TheaterWriter\n\nSaving theater information to file: theater_protobuf_output\nSaved theater information with following data to disk:\npayment: CREDIT_CARD\n" }, { "code": null, "e": 5348, "s": 5288, "text": "Now, let us execute the reader to read from the same file βˆ’" }, { "code": null, "e": 5498, "s": 5348, "text": "java -cp .\\target\\protobuf-tutorial-1.0.jar com.tutorialspoint.theater.TheaterReader\n\nReading from file theater_protobuf_output\npayment: CREDIT_CARD\n" }, { "code": null, "e": 5665, "s": 5498, "text": "So, as we see, we are able to read the serialized enum by deserializing the binary data to Theater object. In the next chapter, we will take a look at Protobuf lists." }, { "code": null, "e": 5672, "s": 5665, "text": " Print" }, { "code": null, "e": 5683, "s": 5672, "text": " Add Notes" } ]
Practical Guide to Outlier Detection Methods | by A. Tayyip Saka | Towards Data Science
I am going to talk about the details of four outlier detection methodologies implemented in R Studio. I will be mentioning what the outlier is, why it is important and why outliers occur. These methods are as follows: Tukey’s MethodTwitter Anomaly DetectionZ-score MethodMean Absolute Deviation(MADe) Method Tukey’s Method Twitter Anomaly Detection Z-score Method Mean Absolute Deviation(MADe) Method To put simply, an outlier is a data point that differs greatly (much smaller or larger than) from other values in a dataset. Outliers may be because of random variation or may demonstrate something scientifically interesting. In any event, we should not simply eliminate the outlying observation before a careful investigation. It is significant to understand them and their occurrence in the right context of the study to be able to cope with them. Why do outliers occur? There are several reasons for outliers: 1. Some observations in the sample are extreme; 2. The data are inappropriately scaled; 3. Errors were made on data entry. Dataset and Pre-Processing My public dataset that shows weekly sales of the company from 2014 to 2017 provides β€œyear”, β€œweek” and β€œsales” columns as shown below. The dimension of a dataset is 201 x 3 and data includes NA values. I looked at the week of blank values then fulfilled blanks by taking an average of observations whose week is the same with blank values in the dataset. dim(sales_data)[1] 201 3sum(is.na(sales_data$Sales))[1] 4 The line graph points out sales of beverage in Turkey starting from 2014 to 2017. Now, it is time to dive deeper into outlier detection methods. Tukey’s Method(Box Whisker) Tukey’s Method(Box Whisker) Minimum value: The smallest value in the data set(Q1–1.5*IQR)First quartile: The value below which the lower 25% of the data are contained (Q1)Median value: The middle number in a range of numbers (Q2)Third quartile: The value above which the upper 25% of the data are contained (Q3)Maximum value: The largest value in the data set (Q3+1.5*IQR)InterQuartile Range(IQR): Range of observations in a dataset (Q3-Q1) Minimum value: The smallest value in the data set(Q1–1.5*IQR) First quartile: The value below which the lower 25% of the data are contained (Q1) Median value: The middle number in a range of numbers (Q2) Third quartile: The value above which the upper 25% of the data are contained (Q3) Maximum value: The largest value in the data set (Q3+1.5*IQR) InterQuartile Range(IQR): Range of observations in a dataset (Q3-Q1) This method is particularly useful for indicating whether a distribution is skewed and whether there are potential unusual observations in the data set. β€œggplot” is one of the powerful data visualization packages in R; hence I used β€œggplot” package to draw box-plot of sales. As shown above, blue points are identified as outliers and red point shows the median of a dataset. The data is left-skewed. The model detected 8 outliers in the dataset as shown on the left table. I can clearly say that these data points differ from the remaining of the dataset. In fact, the sales value of outlier points is above 115,000. 2. Twitter Anomaly Detection AnomalyDetection is an open-source R package to detect anomalies which is robust, from a statistical standpoint, in the presence of seasonality and an underlying trend. The AnomalyDetection package can be used in a wide variety of contexts such as new software release, user engagement posts, and financial engineering problems. The underlying algorithm β€” known as Seasonal Hybrid ESD builds upon the Generalized ESD test for detecting anomalies. It can be used to find both global as well as local anomalies. It can be seen below that I implemented Twitter Anomaly and then the model found 6 outliers in the dataset in comparison with Tukey’s method by taking the alpha value as 0.05. Outlier points are identified as a circle in the table. The table below shows which data points labeled as outliers. The index cumulatively shows week numbers of sales. These outliers belong to generally years 2014 and 2015. 3. Z-score Method Z-score finds the distribution of data where mean is 0 and the standard deviation is 1. The Z-score method relies on the mean and standard deviation of data to gauge the central tendency and dispersion. This is problematic on several occasions since the mean and standard deviation are highly affected by outliers. From a statistical perspective, using a cut-off of 1.96 would give you an equivalent p-value of p = 0.05. As a result, this method detected 8 extreme points among 201 observations. The Z-score method accords with Box-Whisker on this dataset. Most of these points appeared in the year 2014. 4. MADe Method In statistics, the median absolute deviation (MAD) is a robust measure of the variability of univariate data. Besides, MAD is similar to the standard deviation but it is less sensitive to extreme values in the data than the standard deviation. I first computed the median, and then for each data point, I computed the distance between that value and the median. The MAD is defined as the median of these distances. Then, this quantity (MAD) needs to be multiplied by 1.4826 to assure it approximates the actual standard deviation. Median and MADe are employed to detect outliers by applying formulas below. As a result of the MADe method, 9 outliers are found method as shown above. Final Notes I performed four outlier detection methods and each method may produce different results on a dataset. Therefore, you must select one of them to observe outliers or can label the most common points among all methods as extreme points. In that case, there are 6 common extreme points among methods I mentioned above. As a next step, outlier points will be transformed by considering different ways before forecasting modeling. This will result in a more accurate forecasting model. You can see all codes here and next story will be coming soon ...
[ { "code": null, "e": 390, "s": 172, "text": "I am going to talk about the details of four outlier detection methodologies implemented in R Studio. I will be mentioning what the outlier is, why it is important and why outliers occur. These methods are as follows:" }, { "code": null, "e": 480, "s": 390, "text": "Tukey’s MethodTwitter Anomaly DetectionZ-score MethodMean Absolute Deviation(MADe) Method" }, { "code": null, "e": 495, "s": 480, "text": "Tukey’s Method" }, { "code": null, "e": 521, "s": 495, "text": "Twitter Anomaly Detection" }, { "code": null, "e": 536, "s": 521, "text": "Z-score Method" }, { "code": null, "e": 573, "s": 536, "text": "Mean Absolute Deviation(MADe) Method" }, { "code": null, "e": 1023, "s": 573, "text": "To put simply, an outlier is a data point that differs greatly (much smaller or larger than) from other values in a dataset. Outliers may be because of random variation or may demonstrate something scientifically interesting. In any event, we should not simply eliminate the outlying observation before a careful investigation. It is significant to understand them and their occurrence in the right context of the study to be able to cope with them." }, { "code": null, "e": 1046, "s": 1023, "text": "Why do outliers occur?" }, { "code": null, "e": 1209, "s": 1046, "text": "There are several reasons for outliers: 1. Some observations in the sample are extreme; 2. The data are inappropriately scaled; 3. Errors were made on data entry." }, { "code": null, "e": 1236, "s": 1209, "text": "Dataset and Pre-Processing" }, { "code": null, "e": 1371, "s": 1236, "text": "My public dataset that shows weekly sales of the company from 2014 to 2017 provides β€œyear”, β€œweek” and β€œsales” columns as shown below." }, { "code": null, "e": 1591, "s": 1371, "text": "The dimension of a dataset is 201 x 3 and data includes NA values. I looked at the week of blank values then fulfilled blanks by taking an average of observations whose week is the same with blank values in the dataset." }, { "code": null, "e": 1651, "s": 1591, "text": "dim(sales_data)[1] 201 3sum(is.na(sales_data$Sales))[1] 4" }, { "code": null, "e": 1733, "s": 1651, "text": "The line graph points out sales of beverage in Turkey starting from 2014 to 2017." }, { "code": null, "e": 1796, "s": 1733, "text": "Now, it is time to dive deeper into outlier detection methods." }, { "code": null, "e": 1824, "s": 1796, "text": "Tukey’s Method(Box Whisker)" }, { "code": null, "e": 1852, "s": 1824, "text": "Tukey’s Method(Box Whisker)" }, { "code": null, "e": 2265, "s": 1852, "text": "Minimum value: The smallest value in the data set(Q1–1.5*IQR)First quartile: The value below which the lower 25% of the data are contained (Q1)Median value: The middle number in a range of numbers (Q2)Third quartile: The value above which the upper 25% of the data are contained (Q3)Maximum value: The largest value in the data set (Q3+1.5*IQR)InterQuartile Range(IQR): Range of observations in a dataset (Q3-Q1)" }, { "code": null, "e": 2327, "s": 2265, "text": "Minimum value: The smallest value in the data set(Q1–1.5*IQR)" }, { "code": null, "e": 2410, "s": 2327, "text": "First quartile: The value below which the lower 25% of the data are contained (Q1)" }, { "code": null, "e": 2469, "s": 2410, "text": "Median value: The middle number in a range of numbers (Q2)" }, { "code": null, "e": 2552, "s": 2469, "text": "Third quartile: The value above which the upper 25% of the data are contained (Q3)" }, { "code": null, "e": 2614, "s": 2552, "text": "Maximum value: The largest value in the data set (Q3+1.5*IQR)" }, { "code": null, "e": 2683, "s": 2614, "text": "InterQuartile Range(IQR): Range of observations in a dataset (Q3-Q1)" }, { "code": null, "e": 2836, "s": 2683, "text": "This method is particularly useful for indicating whether a distribution is skewed and whether there are potential unusual observations in the data set." }, { "code": null, "e": 3084, "s": 2836, "text": "β€œggplot” is one of the powerful data visualization packages in R; hence I used β€œggplot” package to draw box-plot of sales. As shown above, blue points are identified as outliers and red point shows the median of a dataset. The data is left-skewed." }, { "code": null, "e": 3301, "s": 3084, "text": "The model detected 8 outliers in the dataset as shown on the left table. I can clearly say that these data points differ from the remaining of the dataset. In fact, the sales value of outlier points is above 115,000." }, { "code": null, "e": 3330, "s": 3301, "text": "2. Twitter Anomaly Detection" }, { "code": null, "e": 3840, "s": 3330, "text": "AnomalyDetection is an open-source R package to detect anomalies which is robust, from a statistical standpoint, in the presence of seasonality and an underlying trend. The AnomalyDetection package can be used in a wide variety of contexts such as new software release, user engagement posts, and financial engineering problems. The underlying algorithm β€” known as Seasonal Hybrid ESD builds upon the Generalized ESD test for detecting anomalies. It can be used to find both global as well as local anomalies." }, { "code": null, "e": 4072, "s": 3840, "text": "It can be seen below that I implemented Twitter Anomaly and then the model found 6 outliers in the dataset in comparison with Tukey’s method by taking the alpha value as 0.05. Outlier points are identified as a circle in the table." }, { "code": null, "e": 4241, "s": 4072, "text": "The table below shows which data points labeled as outliers. The index cumulatively shows week numbers of sales. These outliers belong to generally years 2014 and 2015." }, { "code": null, "e": 4259, "s": 4241, "text": "3. Z-score Method" }, { "code": null, "e": 4574, "s": 4259, "text": "Z-score finds the distribution of data where mean is 0 and the standard deviation is 1. The Z-score method relies on the mean and standard deviation of data to gauge the central tendency and dispersion. This is problematic on several occasions since the mean and standard deviation are highly affected by outliers." }, { "code": null, "e": 4864, "s": 4574, "text": "From a statistical perspective, using a cut-off of 1.96 would give you an equivalent p-value of p = 0.05. As a result, this method detected 8 extreme points among 201 observations. The Z-score method accords with Box-Whisker on this dataset. Most of these points appeared in the year 2014." }, { "code": null, "e": 4879, "s": 4864, "text": "4. MADe Method" }, { "code": null, "e": 5123, "s": 4879, "text": "In statistics, the median absolute deviation (MAD) is a robust measure of the variability of univariate data. Besides, MAD is similar to the standard deviation but it is less sensitive to extreme values in the data than the standard deviation." }, { "code": null, "e": 5410, "s": 5123, "text": "I first computed the median, and then for each data point, I computed the distance between that value and the median. The MAD is defined as the median of these distances. Then, this quantity (MAD) needs to be multiplied by 1.4826 to assure it approximates the actual standard deviation." }, { "code": null, "e": 5486, "s": 5410, "text": "Median and MADe are employed to detect outliers by applying formulas below." }, { "code": null, "e": 5562, "s": 5486, "text": "As a result of the MADe method, 9 outliers are found method as shown above." }, { "code": null, "e": 5574, "s": 5562, "text": "Final Notes" }, { "code": null, "e": 5890, "s": 5574, "text": "I performed four outlier detection methods and each method may produce different results on a dataset. Therefore, you must select one of them to observe outliers or can label the most common points among all methods as extreme points. In that case, there are 6 common extreme points among methods I mentioned above." }, { "code": null, "e": 6055, "s": 5890, "text": "As a next step, outlier points will be transformed by considering different ways before forecasting modeling. This will result in a more accurate forecasting model." } ]
Modular Multiplication - GeeksforGeeks
19 Dec, 2021 Below are some interesting properties of Modular Multiplication (a x b) mod m = ((a mod m) x (b mod m)) mod m (a x b x c) mod m = ((a mod m) x (b mod m) x (c mod m)) mod m The same property holds for more than three numbers. The above formula is the extended version of the following formula: Example 1: Find the remainder of 15 x 17 x 19 when divided by 7. Solution: On dividing 15 by 7 we get 1 as remainder. On dividing 17 by 7 we get 3 as remainder. On dividing 19 by 7 we get 5 as remainder. Remainder of the expression (15 x 17 x 19)/7 will be equal to (1 x 3 x 5)/7. Combined remainder will be equal to remainder of 15/7 i.e. 1. Example 2: Find the remainder of 1421 x 1423 x 1425 when divided by 12. Solution: On dividing 1421 by 12 we get 5 as remainder. On dividing 1423 by 12 we get 7 as remainder. On dividing 1425 by 12 we get 9 as remainder. Rem [(1421 x 1423 x 1425)/12] = Rem [(5 x 7 x 9)/12] Rem [(35 x 9)/12] = Rem [(11 x 9)/12] Rem [99/12] = 3. How is it useful? If we need to find remainder of multiplication of two large numbers, we can avoid doing the multiplication of large numbers, especially helpful in programming where multiplication of large numbers can cause overflow. Proof: If we prove for two numbers, then we can easily generalize it. Let us see proof for two numbers. Let a % m = r1 and b % m = r2 Then a and b can be written as (using quotient theorem). Here q1 is quotient when we divide a by m and r1 is remainder. Similar meanings are there for q2 and r2 a = m x q1 + r1 b = m x q2 + r2 LHS = (a x b) % m = ((m x q1 + r1 ) x (m x q2 + r2) ) % m = (m x m x q1 x q2 + m x q1 x r2 + m x q2 x r1 + r1 x r2 ) % m = (m x (m x q1 x q2 + q1 x r2 + q2 x r1) + r1 x r2 ) % m We can eliminate the multiples of m when we take the mod m. LHS = (r1 x r2) % m RHS = (a % m x b % m) % m = (r1 x r2) % m Hence, LHS = RHS mortyohhgezz Modular Arithmetic Engineering Mathematics GATE CS Mathematical Mathematical Modular Arithmetic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Newton's Divided Difference Interpolation Formula Arrow Symbols in LaTeX Set Notations in LaTeX Activation Functions Mathematics | Graph Isomorphisms and Connectivity Layers of OSI Model ACID Properties in DBMS Normal Forms in DBMS Types of Operating Systems
[ { "code": null, "e": 24932, "s": 24904, "text": "\n19 Dec, 2021" }, { "code": null, "e": 24997, "s": 24932, "text": "Below are some interesting properties of Modular Multiplication " }, { "code": null, "e": 25046, "s": 24999, "text": "(a x b) mod m = ((a mod m) x (b mod m)) mod m " }, { "code": null, "e": 25109, "s": 25046, "text": "(a x b x c) mod m = ((a mod m) x (b mod m) x (c mod m)) mod m " }, { "code": null, "e": 25162, "s": 25109, "text": "The same property holds for more than three numbers." }, { "code": null, "e": 25233, "s": 25164, "text": "The above formula is the extended version of the following formula: " }, { "code": null, "e": 25577, "s": 25233, "text": "Example 1: Find the remainder of 15 x 17 x 19 when divided by 7. Solution: On dividing 15 by 7 we get 1 as remainder. On dividing 17 by 7 we get 3 as remainder. On dividing 19 by 7 we get 5 as remainder. Remainder of the expression (15 x 17 x 19)/7 will be equal to (1 x 3 x 5)/7. Combined remainder will be equal to remainder of 15/7 i.e. 1. " }, { "code": null, "e": 25906, "s": 25577, "text": "Example 2: Find the remainder of 1421 x 1423 x 1425 when divided by 12. Solution: On dividing 1421 by 12 we get 5 as remainder. On dividing 1423 by 12 we get 7 as remainder. On dividing 1425 by 12 we get 9 as remainder. Rem [(1421 x 1423 x 1425)/12] = Rem [(5 x 7 x 9)/12] Rem [(35 x 9)/12] = Rem [(11 x 9)/12] Rem [99/12] = 3. " }, { "code": null, "e": 26142, "s": 25906, "text": "How is it useful? If we need to find remainder of multiplication of two large numbers, we can avoid doing the multiplication of large numbers, especially helpful in programming where multiplication of large numbers can cause overflow. " }, { "code": null, "e": 26248, "s": 26142, "text": "Proof: If we prove for two numbers, then we can easily generalize it. Let us see proof for two numbers. " }, { "code": null, "e": 26851, "s": 26248, "text": "Let a % m = r1\nand b % m = r2\n\nThen a and b can be written as (using quotient\ntheorem). Here q1 is quotient when we divide \na by m and r1 is remainder. Similar meanings \nare there for q2 and r2\na = m x q1 + r1\nb = m x q2 + r2\n\nLHS = (a x b) % m\n\n = ((m x q1 + r1 ) x (m x q2 + r2) ) % m\n\n = (m x m x q1 x q2 + \n m x q1 x r2 + \n m x q2 x r1 + r1 x r2 ) % m\n\n = (m x (m x q1 x q2 + q1 x r2 + \n q2 x r1) + \n r1 x r2 ) % m\n\nWe can eliminate the multiples of m when\nwe take the mod m.\nLHS = (r1 x r2) % m\n\nRHS = (a % m x b % m) % m\n = (r1 x r2) % m\n\nHence, LHS = RHS" }, { "code": null, "e": 26866, "s": 26853, "text": "mortyohhgezz" }, { "code": null, "e": 26885, "s": 26866, "text": "Modular Arithmetic" }, { "code": null, "e": 26909, "s": 26885, "text": "Engineering Mathematics" }, { "code": null, "e": 26917, "s": 26909, "text": "GATE CS" }, { "code": null, "e": 26930, "s": 26917, "text": "Mathematical" }, { "code": null, "e": 26943, "s": 26930, "text": "Mathematical" }, { "code": null, "e": 26962, "s": 26943, "text": "Modular Arithmetic" }, { "code": null, "e": 27060, "s": 26962, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27069, "s": 27060, "text": "Comments" }, { "code": null, "e": 27082, "s": 27069, "text": "Old Comments" }, { "code": null, "e": 27132, "s": 27082, "text": "Newton's Divided Difference Interpolation Formula" }, { "code": null, "e": 27155, "s": 27132, "text": "Arrow Symbols in LaTeX" }, { "code": null, "e": 27178, "s": 27155, "text": "Set Notations in LaTeX" }, { "code": null, "e": 27199, "s": 27178, "text": "Activation Functions" }, { "code": null, "e": 27249, "s": 27199, "text": "Mathematics | Graph Isomorphisms and Connectivity" }, { "code": null, "e": 27269, "s": 27249, "text": "Layers of OSI Model" }, { "code": null, "e": 27293, "s": 27269, "text": "ACID Properties in DBMS" }, { "code": null, "e": 27314, "s": 27293, "text": "Normal Forms in DBMS" } ]
Stack Data Structure in Javascript
A stack is an Abstract Data Type (ADT), commonly used in most programming languages. It is named stack as it behaves like a real-world stack, for example – a deck of cards or a pile of plates, etc. A stack allows operations at one end only. This feature makes it LIFO data structure. LIFO stands for Last-in-first-out. Here, the element which is placed (inserted or added) last, is accessed first. In stack terminology, insertion operation is called PUSH operation and removal operation is called POP operation. The following diagram shows the operations on the stack βˆ’ Following is the complete Javascript class to represent a Stack βˆ’ class Stack { constructor(maxSize) { // Set default max size if not provided if (isNaN(maxSize)) { maxSize = 10; } this.maxSize = maxSize; // Init an array that'll contain the stack values. this.container = []; } display() { console.log(this.container); } isEmpty() { return this.container.length === 0; } isFull() { return this.container.length >= this.maxSize; } push(element) { // Check if stack is full if (this.isFull()) { console.log("Stack Overflow!") return; } this.container.push(element) } pop() { // Check if empty if (this.isEmpty()) { console.log("Stack Underflow!") return; } this.container.pop() } peek() { if (isEmpty()) { console.log("Stack Underflow!"); return; } return this.container[this.container.length - 1]; } clear() { this.container = []; } }
[ { "code": null, "e": 1260, "s": 1062, "text": "A stack is an Abstract Data Type (ADT), commonly used in most programming languages. It is named stack as it behaves like a real-world stack, for example – a deck of cards or a pile of plates, etc." }, { "code": null, "e": 1574, "s": 1260, "text": "A stack allows operations at one end only. This feature makes it LIFO data structure. LIFO stands for Last-in-first-out. Here, the element which is placed (inserted or added) last, is accessed first. In stack terminology, insertion operation is called PUSH operation and removal operation is called POP operation." }, { "code": null, "e": 1632, "s": 1574, "text": "The following diagram shows the operations on the stack βˆ’" }, { "code": null, "e": 1698, "s": 1632, "text": "Following is the complete Javascript class to represent a Stack βˆ’" }, { "code": null, "e": 2662, "s": 1698, "text": "class Stack {\n constructor(maxSize) { // Set default max size if not provided\n if (isNaN(maxSize)) {\n maxSize = 10;\n }\n this.maxSize = maxSize; // Init an array that'll contain the stack values.\n this.container = [];\n }\n display() {\n console.log(this.container);\n }\n isEmpty() {\n return this.container.length === 0;\n }\n isFull() {\n return this.container.length >= this.maxSize;\n }\n push(element) { // Check if stack is full\n if (this.isFull()) {\n console.log(\"Stack Overflow!\") return;\n }\n this.container.push(element)\n }\n pop() { // Check if empty\n if (this.isEmpty()) {\n console.log(\"Stack Underflow!\") return;\n }\n this.container.pop()\n }\n peek() {\n if (isEmpty()) {\n console.log(\"Stack Underflow!\");\n return;\n }\n return this.container[this.container.length - 1];\n }\n clear() {\n this.container = [];\n }\n}" } ]
Conversion of whole String to uppercase or lowercase using STL in C++ - GeeksforGeeks
06 Jul, 2017 Given a string, convert the whole string to uppercase or lowercase using STL in C++. Examples: For uppercase conversion Input : s = "String" Output : s = "STRING" For lowercase conversion Input : s = "String" Output : s = "string" Functions used :transform : Performs a transformation on given array/string.toupper(int c) : Returns upper case version of character c. If c is already in uppercase, return c itself.tolower(int c) : Returns lower case version of character c. If c is already in lowercase, return c itself. // C++ program to convert whole string to// uppercase or lowercase using STL.#include<bits/stdc++.h>using namespace std; int main(){ // su is the string which is converted to uppercase string su = "Jatin Goyal"; // using transform() function and ::toupper in STL transform(su.begin(), su.end(), su.begin(), ::toupper); cout << su << endl; // sl is the string which is converted to lowercase string sl = "Jatin Goyal"; // using transform() function and ::tolower in STL transform(sl.begin(), sl.end(), sl.begin(), ::tolower); cout << sl << endl; return 0;} Output: JATIN GOYAL jatin goyal This article is contributed by Jatin Goyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. cpp-strings-library STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inheritance in C++ Map in C++ Standard Template Library (STL) C++ Classes and Objects Bitwise Operators in C/C++ Operator Overloading in C++ Constructors in C++ Socket Programming in C/C++ Virtual Function in C++ Templates in C++ with Examples Copy Constructor in C++
[ { "code": null, "e": 24798, "s": 24770, "text": "\n06 Jul, 2017" }, { "code": null, "e": 24883, "s": 24798, "text": "Given a string, convert the whole string to uppercase or lowercase using STL in C++." }, { "code": null, "e": 24893, "s": 24883, "text": "Examples:" }, { "code": null, "e": 25031, "s": 24893, "text": "For uppercase conversion\nInput : s = \"String\"\nOutput : s = \"STRING\"\n\nFor lowercase conversion\nInput : s = \"String\"\nOutput : s = \"string\"\n" }, { "code": null, "e": 25320, "s": 25031, "text": "Functions used :transform : Performs a transformation on given array/string.toupper(int c) : Returns upper case version of character c. If c is already in uppercase, return c itself.tolower(int c) : Returns lower case version of character c. If c is already in lowercase, return c itself." }, { "code": "// C++ program to convert whole string to// uppercase or lowercase using STL.#include<bits/stdc++.h>using namespace std; int main(){ // su is the string which is converted to uppercase string su = \"Jatin Goyal\"; // using transform() function and ::toupper in STL transform(su.begin(), su.end(), su.begin(), ::toupper); cout << su << endl; // sl is the string which is converted to lowercase string sl = \"Jatin Goyal\"; // using transform() function and ::tolower in STL transform(sl.begin(), sl.end(), sl.begin(), ::tolower); cout << sl << endl; return 0;}", "e": 25918, "s": 25320, "text": null }, { "code": null, "e": 25926, "s": 25918, "text": "Output:" }, { "code": null, "e": 25951, "s": 25926, "text": "JATIN GOYAL\njatin goyal\n" }, { "code": null, "e": 26250, "s": 25951, "text": "This article is contributed by Jatin Goyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 26375, "s": 26250, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 26395, "s": 26375, "text": "cpp-strings-library" }, { "code": null, "e": 26399, "s": 26395, "text": "STL" }, { "code": null, "e": 26403, "s": 26399, "text": "C++" }, { "code": null, "e": 26407, "s": 26403, "text": "STL" }, { "code": null, "e": 26411, "s": 26407, "text": "CPP" }, { "code": null, "e": 26509, "s": 26411, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26528, "s": 26509, "text": "Inheritance in C++" }, { "code": null, "e": 26571, "s": 26528, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 26595, "s": 26571, "text": "C++ Classes and Objects" }, { "code": null, "e": 26622, "s": 26595, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 26650, "s": 26622, "text": "Operator Overloading in C++" }, { "code": null, "e": 26670, "s": 26650, "text": "Constructors in C++" }, { "code": null, "e": 26698, "s": 26670, "text": "Socket Programming in C/C++" }, { "code": null, "e": 26722, "s": 26698, "text": "Virtual Function in C++" }, { "code": null, "e": 26753, "s": 26722, "text": "Templates in C++ with Examples" } ]
How to redirect if JavaScript is not enabled in a browser?
To redirect if JavaScript is not enabled in the web browser, add a script to the <noscript> tag. Let us say you need to redirect to index.php if JavaScript is not enabled. Here’s how you can do this: <!DOCTYPE html> <html> <head> <title>HTML noscript Tag</title> </head> <body> <script> <!-- document.write("Hello JavaScript!") --> </script> <noscript> <style>html{display:none;}</style> <meta http-equiv="refresh" content="0.0;url=nojs/index.php”> </body> </html> Above, we first use CSS style, since we do not want the actual page to be visible if JavaScript is disabled in the web browser.
[ { "code": null, "e": 1235, "s": 1062, "text": "To redirect if JavaScript is not enabled in the web browser, add a script to the <noscript> tag. Let us say you need to redirect to index.php if JavaScript is not enabled. " }, { "code": null, "e": 1263, "s": 1235, "text": "Here’s how you can do this:" }, { "code": null, "e": 1622, "s": 1263, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML noscript Tag</title>\n </head>\n \n <body>\n <script>\n <!--\n document.write(\"Hello JavaScript!\")\n -->\n </script>\n \n <noscript>\n <style>html{display:none;}</style>\n <meta http-equiv=\"refresh\" content=\"0.0;url=nojs/index.php”>\n </body>\n</html>" }, { "code": null, "e": 1750, "s": 1622, "text": "Above, we first use CSS style, since we do not want the actual page to be visible if JavaScript is disabled in the web browser." } ]
Flatten a list of DataFrames - GeeksforGeeks
02 Dec, 2020 In this article, we are going to see how to flatten a list of DataFrames. Flattening is defined as Converting or Changing data format to a narrow format. The advantage of the flattened list is Increases the computing speed and Good understanding of data. Example: Let consider, the data frame that contains values like payments in four months. Actually, the data is stored in a list format. Note: 0,1,2 are the indices of the records Flattening means assigning lists separately for each author. We are going to perform flatten operations on the list using data frames. Method 1: Step 1: Create a simple data frame. Python3 #importing pandas moduleimport pandas as pd #creating dataframe with 2 columnsdf = pd.DataFrame(data=[[[ 300, 400, 500, 600], 'sravan_payment'], [[ 300, 322, 333, 233], 'bobby_payment']], index=[ 0, 1], columns=[ 'A', 'B']) display(df) Output: Step 2: iterate each row with a specific column. Python3 flatdata = pd.DataFrame([( index, value) for ( index, values) in df[ 'A' ].iteritems() for value in values], columns = [ 'index', 'A']).set_index( 'index' ) df = df.drop( 'A', axis = 1 ).join( flatdata )display(df) Output: Methods 2: Using the flatten methods. We are going to apply the flatten function for the above code. Python3 #importing pandas module for dataframe.import pandas as pd df = pd.DataFrame(data=[[[ 300, 400, 500, 600], 'sravan_payment'], [[ 300, 322, 333, 233], 'bobby_payment']], index = [ 0, 1], columns = [ 'A', 'B'])display(df) Output: Python3 df.values.flatten() Output: Python pandas-dataFrame Python Pandas-exercise Python-pandas Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Selecting rows in pandas DataFrame based on conditions Check if element exists in list in Python Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n02 Dec, 2020" }, { "code": null, "e": 24547, "s": 24292, "text": "In this article, we are going to see how to flatten a list of DataFrames. Flattening is defined as Converting or Changing data format to a narrow format. The advantage of the flattened list is Increases the computing speed and Good understanding of data." }, { "code": null, "e": 24556, "s": 24547, "text": "Example:" }, { "code": null, "e": 24683, "s": 24556, "text": "Let consider, the data frame that contains values like payments in four months. Actually, the data is stored in a list format." }, { "code": null, "e": 24729, "s": 24683, "text": "Note: 0,1,2 are the indices of the records " }, { "code": null, "e": 24790, "s": 24729, "text": "Flattening means assigning lists separately for each author." }, { "code": null, "e": 24864, "s": 24790, "text": "We are going to perform flatten operations on the list using data frames." }, { "code": null, "e": 24874, "s": 24864, "text": "Method 1:" }, { "code": null, "e": 24910, "s": 24874, "text": "Step 1: Create a simple data frame." }, { "code": null, "e": 24918, "s": 24910, "text": "Python3" }, { "code": "#importing pandas moduleimport pandas as pd #creating dataframe with 2 columnsdf = pd.DataFrame(data=[[[ 300, 400, 500, 600], 'sravan_payment'], [[ 300, 322, 333, 233], 'bobby_payment']], index=[ 0, 1], columns=[ 'A', 'B']) display(df)", "e": 25198, "s": 24918, "text": null }, { "code": null, "e": 25206, "s": 25198, "text": "Output:" }, { "code": null, "e": 25255, "s": 25206, "text": "Step 2: iterate each row with a specific column." }, { "code": null, "e": 25263, "s": 25255, "text": "Python3" }, { "code": "flatdata = pd.DataFrame([( index, value) for ( index, values) in df[ 'A' ].iteritems() for value in values], columns = [ 'index', 'A']).set_index( 'index' ) df = df.drop( 'A', axis = 1 ).join( flatdata )display(df)", "e": 25531, "s": 25263, "text": null }, { "code": null, "e": 25539, "s": 25531, "text": "Output:" }, { "code": null, "e": 25577, "s": 25539, "text": "Methods 2: Using the flatten methods." }, { "code": null, "e": 25640, "s": 25577, "text": "We are going to apply the flatten function for the above code." }, { "code": null, "e": 25648, "s": 25640, "text": "Python3" }, { "code": "#importing pandas module for dataframe.import pandas as pd df = pd.DataFrame(data=[[[ 300, 400, 500, 600], 'sravan_payment'], [[ 300, 322, 333, 233], 'bobby_payment']], index = [ 0, 1], columns = [ 'A', 'B'])display(df)", "e": 25911, "s": 25648, "text": null }, { "code": null, "e": 25919, "s": 25911, "text": "Output:" }, { "code": null, "e": 25927, "s": 25919, "text": "Python3" }, { "code": "df.values.flatten()", "e": 25947, "s": 25927, "text": null }, { "code": null, "e": 25955, "s": 25947, "text": "Output:" }, { "code": null, "e": 25979, "s": 25955, "text": "Python pandas-dataFrame" }, { "code": null, "e": 26002, "s": 25979, "text": "Python Pandas-exercise" }, { "code": null, "e": 26016, "s": 26002, "text": "Python-pandas" }, { "code": null, "e": 26040, "s": 26016, "text": "Technical Scripter 2020" }, { "code": null, "e": 26047, "s": 26040, "text": "Python" }, { "code": null, "e": 26066, "s": 26047, "text": "Technical Scripter" }, { "code": null, "e": 26164, "s": 26066, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26196, "s": 26164, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26252, "s": 26196, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26294, "s": 26252, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26349, "s": 26294, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26391, "s": 26349, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26413, "s": 26391, "text": "Defaultdict in Python" }, { "code": null, "e": 26452, "s": 26413, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26483, "s": 26452, "text": "Python | os.path.join() method" }, { "code": null, "e": 26512, "s": 26483, "text": "Create a directory in Python" } ]
How to create "Add to cart" button in Bootstrap ? - GeeksforGeeks
15 Jul, 2021 Bootstrap includes a large variety of button styles, each having some common and some different attributes in them. The β€œadd to cart” button acts as a container like a typical shopping cart in a mall, where you collect the stuff that you want to purchase. β€œAdd to cart” buttons are usually provided on e-commerce websites and are also used on other websites which include purchasing products. Bootstrap CDN Links: Before the code, you just need to include the following library or script for adding the β€œadd to cart” button in the application.<script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js”></script><script src=”https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js”> </script> Before the code, you just need to include the following library or script for adding the β€œadd to cart” button in the application. <script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js”></script><script src=”https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js”> </script> To include a small cart-icon that we have used in the example below, you just need to add this stylesheet to your program.<link rel=”stylesheet” href=”https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css”> To include a small cart-icon that we have used in the example below, you just need to add this stylesheet to your program. <link rel=”stylesheet” href=”https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css”> And you also need to include the following class wherever you want to display the cart-icon.<span class=”glyphicon glyphicon-shopping-cart”> </span> And you also need to include the following class wherever you want to display the cart-icon. <span class=”glyphicon glyphicon-shopping-cart”> </span> Example: HTML <!DOCTYPE html><html> <head> <title>Bootstrap Shopping Cart</title> <meta name="viewport" content= "width=device-width, initial-scale=1" /> <!-- CSS only --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css" /> <!-- JavaScript Bundle with Popper --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"> </script> <!--CSS Code--> <style> .container { margin-top: 30px; color: green; } span { color: green; } </style></head> <!--Body tag--><body> <div class="container" align="center"> <h2>GeeksforGeeks</h2> <h3>Shopping-cart</h3> <p> <button type="button" class="btn btn-default btn-sm"> <span class="glyphicon glyphicon-shopping-cart"> </span> <b> Add to Cart </b> </button> </p> </div></body> </html> Output: Now, as you can see in the output, we have included the Add to cart button in our HTML body with a little cart icon on it. Bootstrap-Questions HTML-Questions Picked Bootstrap CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Show Images on Click using HTML ? How to set Bootstrap Timepicker using datetimepicker library ? How to Use Bootstrap with React? Tailwind CSS vs Bootstrap How to keep gap between columns using Bootstrap? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? How to update Node.js and NPM to next version ? Types of CSS (Cascading Style Sheet)
[ { "code": null, "e": 25231, "s": 25203, "text": "\n15 Jul, 2021" }, { "code": null, "e": 25624, "s": 25231, "text": "Bootstrap includes a large variety of button styles, each having some common and some different attributes in them. The β€œadd to cart” button acts as a container like a typical shopping cart in a mall, where you collect the stuff that you want to purchase. β€œAdd to cart” buttons are usually provided on e-commerce websites and are also used on other websites which include purchasing products." }, { "code": null, "e": 25645, "s": 25624, "text": "Bootstrap CDN Links:" }, { "code": null, "e": 25956, "s": 25645, "text": "Before the code, you just need to include the following library or script for adding the β€œadd to cart” button in the application.<script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js”></script><script src=”https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js”> </script> " }, { "code": null, "e": 26086, "s": 25956, "text": "Before the code, you just need to include the following library or script for adding the β€œadd to cart” button in the application." }, { "code": null, "e": 26267, "s": 26086, "text": "<script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js”></script><script src=”https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js”> </script>" }, { "code": null, "e": 26492, "s": 26269, "text": "To include a small cart-icon that we have used in the example below, you just need to add this stylesheet to your program.<link rel=”stylesheet” href=”https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css”>" }, { "code": null, "e": 26615, "s": 26492, "text": "To include a small cart-icon that we have used in the example below, you just need to add this stylesheet to your program." }, { "code": null, "e": 26716, "s": 26615, "text": "<link rel=”stylesheet” href=”https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css”>" }, { "code": null, "e": 26865, "s": 26716, "text": "And you also need to include the following class wherever you want to display the cart-icon.<span class=”glyphicon glyphicon-shopping-cart”> </span>" }, { "code": null, "e": 26958, "s": 26865, "text": "And you also need to include the following class wherever you want to display the cart-icon." }, { "code": null, "e": 27015, "s": 26958, "text": "<span class=”glyphicon glyphicon-shopping-cart”> </span>" }, { "code": null, "e": 27024, "s": 27015, "text": "Example:" }, { "code": null, "e": 27029, "s": 27024, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Bootstrap Shopping Cart</title> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1\" /> <!-- CSS only --> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css\" /> <!-- JavaScript Bundle with Popper --> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js\"> </script> <!--CSS Code--> <style> .container { margin-top: 30px; color: green; } span { color: green; } </style></head> <!--Body tag--><body> <div class=\"container\" align=\"center\"> <h2>GeeksforGeeks</h2> <h3>Shopping-cart</h3> <p> <button type=\"button\" class=\"btn btn-default btn-sm\"> <span class=\"glyphicon glyphicon-shopping-cart\"> </span> <b> Add to Cart </b> </button> </p> </div></body> </html>", "e": 28156, "s": 27029, "text": null }, { "code": null, "e": 28287, "s": 28156, "text": "Output: Now, as you can see in the output, we have included the Add to cart button in our HTML body with a little cart icon on it." }, { "code": null, "e": 28307, "s": 28287, "text": "Bootstrap-Questions" }, { "code": null, "e": 28322, "s": 28307, "text": "HTML-Questions" }, { "code": null, "e": 28329, "s": 28322, "text": "Picked" }, { "code": null, "e": 28339, "s": 28329, "text": "Bootstrap" }, { "code": null, "e": 28343, "s": 28339, "text": "CSS" }, { "code": null, "e": 28360, "s": 28343, "text": "Web Technologies" }, { "code": null, "e": 28458, "s": 28360, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28467, "s": 28458, "text": "Comments" }, { "code": null, "e": 28480, "s": 28467, "text": "Old Comments" }, { "code": null, "e": 28521, "s": 28480, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 28584, "s": 28521, "text": "How to set Bootstrap Timepicker using datetimepicker library ?" }, { "code": null, "e": 28617, "s": 28584, "text": "How to Use Bootstrap with React?" }, { "code": null, "e": 28643, "s": 28617, "text": "Tailwind CSS vs Bootstrap" }, { "code": null, "e": 28692, "s": 28643, "text": "How to keep gap between columns using Bootstrap?" }, { "code": null, "e": 28754, "s": 28692, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 28804, "s": 28754, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 28862, "s": 28804, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 28910, "s": 28862, "text": "How to update Node.js and NPM to next version ?" } ]
Program to find longest path between two nodes of a tree in Python
Suppose we have a binary tree; we have to find the longest path between any two nodes in the tree. So, if the input is like then the output will be 5 To solve this, we will follow these steps: ans := 0 ans := 0 Define a function getMaxPath() . This will take node Define a function getMaxPath() . This will take node if node is null, thenreturn 0 if node is null, then return 0 return 0 leftCnt := getMaxPath(left of node) leftCnt := getMaxPath(left of node) rightCnt := getMaxPath(right of node) rightCnt := getMaxPath(right of node) temp := 1 + maximum of leftCnt and rightCnt temp := 1 + maximum of leftCnt and rightCnt ans := maximum of ans and l+r+1 ans := maximum of ans and l+r+1 From the main method do the following βˆ’ From the main method do the following βˆ’ getMaxPath(root) getMaxPath(root) return ans return ans Let us see the following implementation to get better understanding βˆ’ Live Demo class TreeNode: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def solve(self, root): self.ans = 0 def getMaxPath(root): if root is None: return 0 l = getMaxPath(root.left) r = getMaxPath(root.right) temp = max(l, r) + 1 self.ans = max(self.ans, l + r + 1) return temp getMaxPath(root) return self.ans ob = Solution() root = TreeNode(2) root.left = TreeNode(10) root.right = TreeNode(4) root.right.left = TreeNode(8) root.right.right = TreeNode(2) root.right.left.left = TreeNode(6) print(ob.solve(root)) root = TreeNode(2) root.left = TreeNode(10) root.right = TreeNode(4) root.right.left = TreeNode(8) root.right.right = TreeNode(2) root.right.left.left = TreeNode(6) 5
[ { "code": null, "e": 1161, "s": 1062, "text": "Suppose we have a binary tree; we have to find the longest path between any two nodes in the\ntree." }, { "code": null, "e": 1186, "s": 1161, "text": "So, if the input is like" }, { "code": null, "e": 1214, "s": 1186, "text": " then the output will be 5 " }, { "code": null, "e": 1257, "s": 1214, "text": "To solve this, we will follow these steps:" }, { "code": null, "e": 1266, "s": 1257, "text": "ans := 0" }, { "code": null, "e": 1275, "s": 1266, "text": "ans := 0" }, { "code": null, "e": 1328, "s": 1275, "text": "Define a function getMaxPath() . This will take node" }, { "code": null, "e": 1381, "s": 1328, "text": "Define a function getMaxPath() . This will take node" }, { "code": null, "e": 1411, "s": 1381, "text": "if node is null, thenreturn 0" }, { "code": null, "e": 1433, "s": 1411, "text": "if node is null, then" }, { "code": null, "e": 1442, "s": 1433, "text": "return 0" }, { "code": null, "e": 1451, "s": 1442, "text": "return 0" }, { "code": null, "e": 1487, "s": 1451, "text": "leftCnt := getMaxPath(left of node)" }, { "code": null, "e": 1523, "s": 1487, "text": "leftCnt := getMaxPath(left of node)" }, { "code": null, "e": 1561, "s": 1523, "text": "rightCnt := getMaxPath(right of node)" }, { "code": null, "e": 1599, "s": 1561, "text": "rightCnt := getMaxPath(right of node)" }, { "code": null, "e": 1643, "s": 1599, "text": "temp := 1 + maximum of leftCnt and rightCnt" }, { "code": null, "e": 1687, "s": 1643, "text": "temp := 1 + maximum of leftCnt and rightCnt" }, { "code": null, "e": 1719, "s": 1687, "text": "ans := maximum of ans and l+r+1" }, { "code": null, "e": 1751, "s": 1719, "text": "ans := maximum of ans and l+r+1" }, { "code": null, "e": 1791, "s": 1751, "text": "From the main method do the following βˆ’" }, { "code": null, "e": 1831, "s": 1791, "text": "From the main method do the following βˆ’" }, { "code": null, "e": 1848, "s": 1831, "text": "getMaxPath(root)" }, { "code": null, "e": 1865, "s": 1848, "text": "getMaxPath(root)" }, { "code": null, "e": 1876, "s": 1865, "text": "return ans" }, { "code": null, "e": 1887, "s": 1876, "text": "return ans" }, { "code": null, "e": 1957, "s": 1887, "text": "Let us see the following implementation to get better understanding βˆ’" }, { "code": null, "e": 1968, "s": 1957, "text": " Live Demo" }, { "code": null, "e": 2656, "s": 1968, "text": "class TreeNode:\n def __init__(self, val, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\nclass Solution:\n def solve(self, root):\n self.ans = 0\n def getMaxPath(root):\n if root is None:\n return 0\n l = getMaxPath(root.left)\n r = getMaxPath(root.right)\n temp = max(l, r) + 1\n self.ans = max(self.ans, l + r + 1)\n return temp\n getMaxPath(root)\n return self.ans\nob = Solution()\nroot = TreeNode(2)\nroot.left = TreeNode(10)\nroot.right = TreeNode(4)\nroot.right.left = TreeNode(8)\nroot.right.right = TreeNode(2)\nroot.right.left.left = TreeNode(6)\nprint(ob.solve(root))" }, { "code": null, "e": 2821, "s": 2656, "text": "root = TreeNode(2)\nroot.left = TreeNode(10)\nroot.right = TreeNode(4)\nroot.right.left = TreeNode(8)\nroot.right.right = TreeNode(2)\nroot.right.left.left = TreeNode(6)" }, { "code": null, "e": 2823, "s": 2821, "text": "5" } ]
How to write a MySQL stored function that updates the values in a table?
As we know that function is best used when we want to return a result. Hence, when we will create stored functions for manipulating tables like to Insert or Update values then it would be more or less like stored procedures. In the following example, we are creating a stored function named β€˜tbl_update’ which will update the values in a table named β€˜student_marks’. mysql> Select * from student_marks// +---------+------+---------+---------+---------+ | Name | Math | English | Science | History | +---------+------+---------+---------+---------+ | Raman | 95 | 89 | 85 | 81 | | Rahul | 90 | 87 | 86 | 81 | | Mohit | 90 | 85 | 86 | 81 | | Saurabh | NULL | NULL | NULL | NULL | +---------+------+---------+---------+---------+ 4 rows in set (0.00 sec) mysql> Create Function tbl_Update(S_name Varchar(50),M1 INT,M2 INT,M3 INT,M4 INT) -> RETURNS INT -> DETERMINISTIC -> BEGIN -> UPDATE student_marks SET Math = M1,English = M2, Science = M3, History =M4 WHERE Name = S_name; -> RETURN 1; -> END // Query OK, 0 rows affected (0.03 sec) mysql> Select tbl_update('Saurabh',85,69,75,82); +------------------------------------+ | tbl_update('Saurabh',85,69,75,82) | +------------------------------------+ | 1 | +------------------------------------+ 1 row in set (0.07 sec) mysql> Select * from Student_marks; +---------+------+---------+---------+---------+ | Name | Math | English | Science | History | +---------+------+---------+---------+---------+ | Raman | 95 | 89 | 85 | 81 | | Rahul | 90 | 87 | 86 | 81 | | Mohit | 90 | 85 | 86 | 81 | | Saurabh | 85 | 69 | 75 | 82 | +---------+------+---------+---------+---------+ 4 rows in set (0.00 sec)
[ { "code": null, "e": 1429, "s": 1062, "text": "As we know that function is best used when we want to return a result. Hence, when we will create stored functions for manipulating tables like to Insert or Update values then it would be more or less like stored procedures. In the following example, we are creating a stored function named β€˜tbl_update’ which will update the values in a table named β€˜student_marks’." }, { "code": null, "e": 2913, "s": 1429, "text": "mysql> Select * from student_marks//\n+---------+------+---------+---------+---------+\n| Name | Math | English | Science | History |\n+---------+------+---------+---------+---------+\n| Raman | 95 | 89 | 85 | 81 |\n| Rahul | 90 | 87 | 86 | 81 |\n| Mohit | 90 | 85 | 86 | 81 |\n| Saurabh | NULL | NULL | NULL | NULL |\n+---------+------+---------+---------+---------+\n4 rows in set (0.00 sec)\n\nmysql> Create Function tbl_Update(S_name Varchar(50),M1 INT,M2 INT,M3 INT,M4 INT)\n -> RETURNS INT\n -> DETERMINISTIC\n -> BEGIN\n -> UPDATE student_marks SET Math = M1,English = M2, Science = M3, History =M4 WHERE Name = S_name;\n -> RETURN 1;\n -> END //\nQuery OK, 0 rows affected (0.03 sec)\n\nmysql> Select tbl_update('Saurabh',85,69,75,82);\n+------------------------------------+\n| tbl_update('Saurabh',85,69,75,82) |\n+------------------------------------+\n| 1 |\n+------------------------------------+\n1 row in set (0.07 sec)\n\nmysql> Select * from Student_marks;\n+---------+------+---------+---------+---------+\n| Name | Math | English | Science | History |\n+---------+------+---------+---------+---------+\n| Raman | 95 | 89 | 85 | 81 |\n| Rahul | 90 | 87 | 86 | 81 |\n| Mohit | 90 | 85 | 86 | 81 |\n| Saurabh | 85 | 69 | 75 | 82 |\n+---------+------+---------+---------+---------+\n4 rows in set (0.00 sec)" } ]
Here’s How Apache Flink Stores Your State data | by Kartik Khare | Towards Data Science
One of the significant features of Apache Flink is its ability to do stateful processing. The API to store and retrieve state data is simple which makes it a joy to use. However, behind that API lies a system to manage your data while providing persistence guarantees and that’s what we’ll be understanding in this article. We’ll be looking at 3 parts of the State Management β€” State BackendData FormatPersistence and Failure Recovery State Backend Data Format Persistence and Failure Recovery Let’s first look at where the state is actually stored. Flink provides three backend storage for your state out of the box. These are Memory state backendFile System (FS) state backendRocksDB state backend Memory state backend File System (FS) state backend RocksDB state backend This storage persists the data in the memory of each task manager’s Heap. Hence, this makes it extremely fast in access. In spite of this performance, this state should never be used in production jobs. That’s because the state creates a backup of the data (also known as checkpointing) in the job manager memory which puts unnecessary pressure on the job manager's operational stability. Another limitation of this backend that the total state size of a task can’t exceed 10MB. It can be configured to a higher limit but is not advised by the authors due to performance consideration. This is the default backend used by Flink in case nothing is configured. This backend is similar to Memory state backend except for the fact that it stores the backup on the filesystem rather than job manager memory. The filesystem can be task manager's local filesystem or a durable store such as HDFS/S3. This state is also limited by the heap memory and hence should be used for cases when you have fewer data and require high performance. This backend uses RocksDB by Facebook to store the data. If you are not aware of RocksDB, it’s an embeddable key-value store which offers ACID guarantees. It is based on LevelDB by Google but offers much better write performance. Flink chose to use RocksDB instead of some of the most popular embeddable storage such as SQLlite because of its high write performance which comes from the LSM architecture based design. Since RocksDB also maintains an in-memory table (also known as mem-table) along with bloom filters, reading recent data also is extremely fast. Each task manager maintains its own Rocks DB file and the backup of this state is checkpointed to a durable store such as HDFS. This is the only backend which offers support for incremental checkpointing i.e. taking a backup of only modified data rather than complete data. If your applications require a large state to store, this should be your choice. However, since it requires disk access and serialization/deserialization, it is comparatively slower than the rest of the backends. Let’s look at how the data is actually stored once you create a state in your application. The storage format differs according to the backend. However, the common part is both the key and the value of the state are stored in byte arrays created using Flink’s own Type serializers. We’ll be using RocksDB backend for demonstration. Each task manager has multiple RocksDB folders with each folder a database in itself. Each database contains multiple column families defined by the name given in the state descriptors. Each column family contain key-value pairs where the key is the operator’s key and value is the state’s data. As an example. let’s look at the state of this example job This job contains two stateful functions which are defined as If you run this job and set Rocksdb as state backend in the flink-conf.yml file, following directories, get generated on every task manager. drwxr-xr-x 4 abc 74715970 128B Sep 23 03:19 job_127b2b84f80b368b8edfe02b2762d10d_op_KeyedProcessOperator_0d49016af99997646695a030f69aa7ee__1_1__uuid_65b50444-5857-4940-9f8c-77326cc79279/dbdrwxr-xr-x 4 abc 74715970 128B Sep 23 03:20 job_127b2b84f80b368b8edfe02b2762d10d_op_StreamFlatMap_11f49afc24b1cce91c7169b1e5140284__1_1__uuid_19b333d3-3278-4e51-93c8-ac6c3608507c/db Here’s how the directory names are defined The names are composed of 3 parts JOB_ID: The random id assigned to your job when the job graph is created.OPERATOR_ID: This is the combination of Base Class of operator, Murmur3 Hash of operator uid, index of the task and the overall parallelism of the task. e.g. for our StatefulMapTest function, these 4 parts turn out to be JOB_ID: The random id assigned to your job when the job graph is created. OPERATOR_ID: This is the combination of Base Class of operator, Murmur3 Hash of operator uid, index of the task and the overall parallelism of the task. e.g. for our StatefulMapTest function, these 4 parts turn out to be StreamFlatMap Murmur3_128(β€œstateful_map_test”) -> 11f49afc24b1cce91c7169b1e5140284 1, since there can be only a single task in a job with a parallelism of 1 and hence task index is 1 1, since I set the parallelism of 1 while executing the job 3. UUID: This is just a random UUID generated while creating the directories. Each of these directories contains an instance of RocksDB. The file structure of RocksDB will be -rw-r--r-- 1 abc 74715970 21K Sep 23 03:20 000011.sst-rw-r--r-- 1 abc 74715970 21K Sep 23 03:20 000012.sst-rw-r--r-- 1 abc 74715970 0B Sep 23 03:36 000015.log-rw-r--r-- 1 abc 74715970 16B Sep 23 03:36 CURRENT-rw-r--r-- 1 abc 74715970 33B Sep 23 03:18 IDENTITY-rw-r--r-- 1 abc 74715970 0B Sep 23 03:33 LOCK-rw-r--r-- 1 abc 74715970 34K Sep 23 03:36 LOG-rw-r--r-- 1 abc 74715970 339B Sep 23 03:36 MANIFEST-000014-rw-r--r-- 1 abc 74715970 10K Sep 23 03:36 OPTIONS-000017 The .sst files are the SSTable files of the Rocksdb which contain the actual data. LOG file contains the commit log.MANIFEST contains metadata such as column families.OPTIONS contain the configuration used to create RocksDB instance. Let’s open this DB using RocksDB java API. We’ll take a look at the StatefulMapTest functions directory. The following code prints all the column family names which are present in the DB. The output of the above piece of code turns out to be defaultpreviousIntnextInt We can also print all the key-value pairs inside each column family. This can be done using below piece of code In our case, it will print out key-value pairs such as (testing123, 1423), (testing456, 1212) etc. TestInputView here is just Flink specific construct which is used to read Byte Array data streams. Flink provides persistence for your application state using a mechanism called Checkpointing. It takes a snapshot of the state on periodic intervals and then stores it in a durable store such as HDFS/S3. This allows the Flink application to resume from this backup in case of failures. Checkpointing is disabled by default for a Flink job. To enable it, you can add the following piece of code to your application This will configure your application to take a snapshot of your state every 60 seconds and put it to job manager/HDFS/S3 for future recovery. In case of HDFS/S3, the directory used to store the checkpoint can be configured with state.checkpoints.dir in flink-conf.yml. The final directory structure of a checkpoint looks like hdfs:///path/to/state.checkpoints.dir/{JOB_ID}/chk-{CHECKPOINT_ID}/ JOB_ID is your application’s unique ID and checkpoint ID is auto-incremental numeric id. To restore the state from checkpoint at the start of the application, simply run flink-1.9.0/bin/flink run -s hdfs:///path/to/state.checkpoints.dir/{JOB_ID}/chk-{CHECKPOINT_ID}/ path/to//your/jar You can extend your stateful functions with Checkpointed Function which provide the ability to modify the state upon initialization and taking the snapshot. The previous StatefulProcess function can be extended to use this interface. This completes our deep dive into Flink state and now you can be sure that your state is well preserved by the application. If you want to get started with State processing Apache Flink, these are some useful links to the official docs - Working with StateState BackendsState Processor API Working with State State Backends State Processor API
[ { "code": null, "e": 342, "s": 172, "text": "One of the significant features of Apache Flink is its ability to do stateful processing. The API to store and retrieve state data is simple which makes it a joy to use." }, { "code": null, "e": 496, "s": 342, "text": "However, behind that API lies a system to manage your data while providing persistence guarantees and that’s what we’ll be understanding in this article." }, { "code": null, "e": 550, "s": 496, "text": "We’ll be looking at 3 parts of the State Management β€”" }, { "code": null, "e": 607, "s": 550, "text": "State BackendData FormatPersistence and Failure Recovery" }, { "code": null, "e": 621, "s": 607, "text": "State Backend" }, { "code": null, "e": 633, "s": 621, "text": "Data Format" }, { "code": null, "e": 666, "s": 633, "text": "Persistence and Failure Recovery" }, { "code": null, "e": 722, "s": 666, "text": "Let’s first look at where the state is actually stored." }, { "code": null, "e": 800, "s": 722, "text": "Flink provides three backend storage for your state out of the box. These are" }, { "code": null, "e": 872, "s": 800, "text": "Memory state backendFile System (FS) state backendRocksDB state backend" }, { "code": null, "e": 893, "s": 872, "text": "Memory state backend" }, { "code": null, "e": 924, "s": 893, "text": "File System (FS) state backend" }, { "code": null, "e": 946, "s": 924, "text": "RocksDB state backend" }, { "code": null, "e": 1335, "s": 946, "text": "This storage persists the data in the memory of each task manager’s Heap. Hence, this makes it extremely fast in access. In spite of this performance, this state should never be used in production jobs. That’s because the state creates a backup of the data (also known as checkpointing) in the job manager memory which puts unnecessary pressure on the job manager's operational stability." }, { "code": null, "e": 1532, "s": 1335, "text": "Another limitation of this backend that the total state size of a task can’t exceed 10MB. It can be configured to a higher limit but is not advised by the authors due to performance consideration." }, { "code": null, "e": 1605, "s": 1532, "text": "This is the default backend used by Flink in case nothing is configured." }, { "code": null, "e": 1839, "s": 1605, "text": "This backend is similar to Memory state backend except for the fact that it stores the backup on the filesystem rather than job manager memory. The filesystem can be task manager's local filesystem or a durable store such as HDFS/S3." }, { "code": null, "e": 1975, "s": 1839, "text": "This state is also limited by the heap memory and hence should be used for cases when you have fewer data and require high performance." }, { "code": null, "e": 2205, "s": 1975, "text": "This backend uses RocksDB by Facebook to store the data. If you are not aware of RocksDB, it’s an embeddable key-value store which offers ACID guarantees. It is based on LevelDB by Google but offers much better write performance." }, { "code": null, "e": 2537, "s": 2205, "text": "Flink chose to use RocksDB instead of some of the most popular embeddable storage such as SQLlite because of its high write performance which comes from the LSM architecture based design. Since RocksDB also maintains an in-memory table (also known as mem-table) along with bloom filters, reading recent data also is extremely fast." }, { "code": null, "e": 2665, "s": 2537, "text": "Each task manager maintains its own Rocks DB file and the backup of this state is checkpointed to a durable store such as HDFS." }, { "code": null, "e": 2811, "s": 2665, "text": "This is the only backend which offers support for incremental checkpointing i.e. taking a backup of only modified data rather than complete data." }, { "code": null, "e": 3024, "s": 2811, "text": "If your applications require a large state to store, this should be your choice. However, since it requires disk access and serialization/deserialization, it is comparatively slower than the rest of the backends." }, { "code": null, "e": 3115, "s": 3024, "text": "Let’s look at how the data is actually stored once you create a state in your application." }, { "code": null, "e": 3306, "s": 3115, "text": "The storage format differs according to the backend. However, the common part is both the key and the value of the state are stored in byte arrays created using Flink’s own Type serializers." }, { "code": null, "e": 3356, "s": 3306, "text": "We’ll be using RocksDB backend for demonstration." }, { "code": null, "e": 3542, "s": 3356, "text": "Each task manager has multiple RocksDB folders with each folder a database in itself. Each database contains multiple column families defined by the name given in the state descriptors." }, { "code": null, "e": 3652, "s": 3542, "text": "Each column family contain key-value pairs where the key is the operator’s key and value is the state’s data." }, { "code": null, "e": 3711, "s": 3652, "text": "As an example. let’s look at the state of this example job" }, { "code": null, "e": 3773, "s": 3711, "text": "This job contains two stateful functions which are defined as" }, { "code": null, "e": 3914, "s": 3773, "text": "If you run this job and set Rocksdb as state backend in the flink-conf.yml file, following directories, get generated on every task manager." }, { "code": null, "e": 4294, "s": 3914, "text": "drwxr-xr-x 4 abc 74715970 128B Sep 23 03:19 job_127b2b84f80b368b8edfe02b2762d10d_op_KeyedProcessOperator_0d49016af99997646695a030f69aa7ee__1_1__uuid_65b50444-5857-4940-9f8c-77326cc79279/dbdrwxr-xr-x 4 abc 74715970 128B Sep 23 03:20 job_127b2b84f80b368b8edfe02b2762d10d_op_StreamFlatMap_11f49afc24b1cce91c7169b1e5140284__1_1__uuid_19b333d3-3278-4e51-93c8-ac6c3608507c/db" }, { "code": null, "e": 4337, "s": 4294, "text": "Here’s how the directory names are defined" }, { "code": null, "e": 4371, "s": 4337, "text": "The names are composed of 3 parts" }, { "code": null, "e": 4665, "s": 4371, "text": "JOB_ID: The random id assigned to your job when the job graph is created.OPERATOR_ID: This is the combination of Base Class of operator, Murmur3 Hash of operator uid, index of the task and the overall parallelism of the task. e.g. for our StatefulMapTest function, these 4 parts turn out to be" }, { "code": null, "e": 4739, "s": 4665, "text": "JOB_ID: The random id assigned to your job when the job graph is created." }, { "code": null, "e": 4960, "s": 4739, "text": "OPERATOR_ID: This is the combination of Base Class of operator, Murmur3 Hash of operator uid, index of the task and the overall parallelism of the task. e.g. for our StatefulMapTest function, these 4 parts turn out to be" }, { "code": null, "e": 4974, "s": 4960, "text": "StreamFlatMap" }, { "code": null, "e": 5043, "s": 4974, "text": "Murmur3_128(β€œstateful_map_test”) -> 11f49afc24b1cce91c7169b1e5140284" }, { "code": null, "e": 5143, "s": 5043, "text": "1, since there can be only a single task in a job with a parallelism of 1 and hence task index is 1" }, { "code": null, "e": 5203, "s": 5143, "text": "1, since I set the parallelism of 1 while executing the job" }, { "code": null, "e": 5281, "s": 5203, "text": "3. UUID: This is just a random UUID generated while creating the directories." }, { "code": null, "e": 5378, "s": 5281, "text": "Each of these directories contains an instance of RocksDB. The file structure of RocksDB will be" }, { "code": null, "e": 5892, "s": 5378, "text": "-rw-r--r-- 1 abc 74715970 21K Sep 23 03:20 000011.sst-rw-r--r-- 1 abc 74715970 21K Sep 23 03:20 000012.sst-rw-r--r-- 1 abc 74715970 0B Sep 23 03:36 000015.log-rw-r--r-- 1 abc 74715970 16B Sep 23 03:36 CURRENT-rw-r--r-- 1 abc 74715970 33B Sep 23 03:18 IDENTITY-rw-r--r-- 1 abc 74715970 0B Sep 23 03:33 LOCK-rw-r--r-- 1 abc 74715970 34K Sep 23 03:36 LOG-rw-r--r-- 1 abc 74715970 339B Sep 23 03:36 MANIFEST-000014-rw-r--r-- 1 abc 74715970 10K Sep 23 03:36 OPTIONS-000017" }, { "code": null, "e": 6126, "s": 5892, "text": "The .sst files are the SSTable files of the Rocksdb which contain the actual data. LOG file contains the commit log.MANIFEST contains metadata such as column families.OPTIONS contain the configuration used to create RocksDB instance." }, { "code": null, "e": 6231, "s": 6126, "text": "Let’s open this DB using RocksDB java API. We’ll take a look at the StatefulMapTest functions directory." }, { "code": null, "e": 6368, "s": 6231, "text": "The following code prints all the column family names which are present in the DB. The output of the above piece of code turns out to be" }, { "code": null, "e": 6394, "s": 6368, "text": "defaultpreviousIntnextInt" }, { "code": null, "e": 6506, "s": 6394, "text": "We can also print all the key-value pairs inside each column family. This can be done using below piece of code" }, { "code": null, "e": 6605, "s": 6506, "text": "In our case, it will print out key-value pairs such as (testing123, 1423), (testing456, 1212) etc." }, { "code": null, "e": 6704, "s": 6605, "text": "TestInputView here is just Flink specific construct which is used to read Byte Array data streams." }, { "code": null, "e": 6990, "s": 6704, "text": "Flink provides persistence for your application state using a mechanism called Checkpointing. It takes a snapshot of the state on periodic intervals and then stores it in a durable store such as HDFS/S3. This allows the Flink application to resume from this backup in case of failures." }, { "code": null, "e": 7118, "s": 6990, "text": "Checkpointing is disabled by default for a Flink job. To enable it, you can add the following piece of code to your application" }, { "code": null, "e": 7387, "s": 7118, "text": "This will configure your application to take a snapshot of your state every 60 seconds and put it to job manager/HDFS/S3 for future recovery. In case of HDFS/S3, the directory used to store the checkpoint can be configured with state.checkpoints.dir in flink-conf.yml." }, { "code": null, "e": 7444, "s": 7387, "text": "The final directory structure of a checkpoint looks like" }, { "code": null, "e": 7512, "s": 7444, "text": "hdfs:///path/to/state.checkpoints.dir/{JOB_ID}/chk-{CHECKPOINT_ID}/" }, { "code": null, "e": 7601, "s": 7512, "text": "JOB_ID is your application’s unique ID and checkpoint ID is auto-incremental numeric id." }, { "code": null, "e": 7682, "s": 7601, "text": "To restore the state from checkpoint at the start of the application, simply run" }, { "code": null, "e": 7797, "s": 7682, "text": "flink-1.9.0/bin/flink run -s hdfs:///path/to/state.checkpoints.dir/{JOB_ID}/chk-{CHECKPOINT_ID}/ path/to//your/jar" }, { "code": null, "e": 8031, "s": 7797, "text": "You can extend your stateful functions with Checkpointed Function which provide the ability to modify the state upon initialization and taking the snapshot. The previous StatefulProcess function can be extended to use this interface." }, { "code": null, "e": 8155, "s": 8031, "text": "This completes our deep dive into Flink state and now you can be sure that your state is well preserved by the application." }, { "code": null, "e": 8269, "s": 8155, "text": "If you want to get started with State processing Apache Flink, these are some useful links to the official docs -" }, { "code": null, "e": 8321, "s": 8269, "text": "Working with StateState BackendsState Processor API" }, { "code": null, "e": 8340, "s": 8321, "text": "Working with State" }, { "code": null, "e": 8355, "s": 8340, "text": "State Backends" } ]
Groovy - Dates & Times compareTo()
Compares two Dates for ordering. public int compareTo(Date anotherDate) anotherDate – the Date to be compared. Return Value βˆ’ The value 0 if the argument Date is equal to this Date; a value less than 0 if this Date is before the Date argument; and a value greater than 0 if this Date is after the Date argument. Following is an example of the usage of this method βˆ’ class Example { static void main(String[] args) { Date olddate = new Date("05/11/2015"); Date newdate = new Date("05/11/2015"); Date latestdate = new Date(); System.out.println(olddate.compareTo(newdate)); System.out.println(latestdate.compareTo(newdate)); } } When we run the above program, we will get the following result βˆ’ 0 1 52 Lectures 8 hours Krishna Sakinala 49 Lectures 2.5 hours Packt Publishing Print Add Notes Bookmark this page
[ { "code": null, "e": 2271, "s": 2238, "text": "Compares two Dates for ordering." }, { "code": null, "e": 2311, "s": 2271, "text": "public int compareTo(Date anotherDate)\n" }, { "code": null, "e": 2350, "s": 2311, "text": "anotherDate – the Date to be compared." }, { "code": null, "e": 2551, "s": 2350, "text": "Return Value βˆ’ The value 0 if the argument Date is equal to this Date; a value less than 0 if this Date is before the Date argument; and a value greater than 0 if this Date is after the Date argument." }, { "code": null, "e": 2605, "s": 2551, "text": "Following is an example of the usage of this method βˆ’" }, { "code": null, "e": 2913, "s": 2605, "text": "class Example { \n static void main(String[] args) { \n Date olddate = new Date(\"05/11/2015\"); \n Date newdate = new Date(\"05/11/2015\"); \n Date latestdate = new Date(); \n\t\t\n System.out.println(olddate.compareTo(newdate)); \n System.out.println(latestdate.compareTo(newdate)); \n } \n}" }, { "code": null, "e": 2979, "s": 2913, "text": "When we run the above program, we will get the following result βˆ’" }, { "code": null, "e": 2986, "s": 2979, "text": "0 \n1 \n" }, { "code": null, "e": 3019, "s": 2986, "text": "\n 52 Lectures \n 8 hours \n" }, { "code": null, "e": 3037, "s": 3019, "text": " Krishna Sakinala" }, { "code": null, "e": 3072, "s": 3037, "text": "\n 49 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3090, "s": 3072, "text": " Packt Publishing" }, { "code": null, "e": 3097, "s": 3090, "text": " Print" }, { "code": null, "e": 3108, "s": 3097, "text": " Add Notes" } ]
Construct a linked list from 2D matrix (Iterative Approach) - GeeksforGeeks
30 Dec, 2020 Given a matrix, the task is to construct a linked list matrix in which each node is connected to its right and down node.Example: Input: [1 2 3 4 5 6 7 8 9] Output: 1 -> 2 -> 3 -> NULL | | | v v v 4 -> 5 -> 6 -> NULL | | | v v v 7 -> 8 -> 9 -> NULL | | | v v v NULL NULL NULL A recursive solution for this problem has been already discussed in this post. Below is an iterative approach for the problem: The idea is to create m linked lists (m = number of rows) whose each node stores its right node. The head pointers of each m linked lists are stored in an array of nodes. Then, traverse m lists, for every ith and (i+1)th list, set the down pointers of each node of ith list to its corresponding node of (i+1)th list. Below is the implementation of the above approach: C++ Java Python3 C# // C++ program to construct a linked// list from 2D matrix | Iterative Approach#include <bits/stdc++.h>using namespace std; // struct node of linked liststruct node { int data; node *right, *down;}; // utility function to create a new node with given datanode* newNode(int d){ node* temp = new node; temp->data = d; temp->right = temp->down = NULL; return temp;} // utility function to print the linked list pointed to by head pointervoid display(node* head){ node *rp, *dp = head; // loop until the down pointer is not NULL while (dp) { rp = dp; // loop until the right pointer is not NULL while (rp) { cout << rp->data << " "; rp = rp->right; } cout << endl; dp = dp->down; }} // function which constructs the linked list// from the given matrix of size m * n// and returns the head pointer of the linked listnode* constructLinkedMatrix(int mat[][3], int m, int n){ // stores the head of the linked list node* mainhead = NULL; // stores the head of linked lists of each row node* head[m]; node *righttemp, *newptr; // Firstly, we create m linked lists // by setting all the right nodes of every row for (int i = 0; i < m; i++) { // initially set the head of ith row as NULL head[i] = NULL; for (int j = 0; j < n; j++) { newptr = newNode(mat[i][j]); // stores the mat[0][0] node as // the mainhead of the linked list if (!mainhead) mainhead = newptr; if (!head[i]) head[i] = newptr; else righttemp->right = newptr; righttemp = newptr; } } // Then, for every ith and (i+1)th list, // we set the down pointers of // every node of ith list // with its corresponding // node of (i+1)th list for (int i = 0; i < m - 1; i++) { node *temp1 = head[i], *temp2 = head[i + 1]; while (temp1 && temp2) { temp1->down = temp2; temp1 = temp1->right; temp2 = temp2->right; } } // return the mainhead pointer of the linked list return mainhead;} // Driver program to test the above functionint main(){ int m, n; // m = rows and n = columns m = 3, n = 3; // 2D matrix int mat[][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; node* head = constructLinkedMatrix(mat, m, n); display(head); return 0;} // Java implementation for above approach // Construct a Linked List from 2-D Matrixclass LinkedMatrix{ class Node { int data; Node right, down; // Default Constructor Node() { this.right = null; this.down = null; } Node(int d) { this.data = d; this.right = null; this.down = null; } } /* A function to construct a Linked List from the given matrix of size m * n and returns the head pointer of the linked list */ Node constructLinkedMatrix(int[][] arr, int m, int n) { // stores the head of the linked list Node mainHead = null; // stores the head of linked lists // of each row Node[] head = new Node[m]; Node rightTemp = new Node(), newptr; // Firstly, we create m linked lists // by setting all the right nodes of every row for(int i = 0; i < m; i++) { // initially set the head of // ith row as NULL head[i] = null; for(int j = 0; j < n; j++) { newptr = new Node(arr[i][j]); // stores the mat[0][0] node as // the mainhead of the linked list if(mainHead == null) mainHead = newptr; if(head[i] == null) head[i] = newptr; else rightTemp.right = newptr; rightTemp = newptr; } } // Then, for every ith and (i+1)th list, // we set the down pointers of // every node of ith list // with its corresponding // node of (i+1)th list for(int i = 0; i < m - 1; i++) { Node temp1 = head[i], temp2 = head[i + 1]; while(temp1 != null && temp2 != null) { temp1.down = temp2; temp1 = temp1.right; temp2 = temp2.right; } } // return the mainhead pointer // of the linked list return mainHead; } // utility function to print the // linked list pointed to by head pointer void display(Node head) { Node rp, dp = head; // loop until the down pointer // is not NULL while(dp != null) { rp = dp; // loop until the right pointer // is not NULL while(rp != null) { System.out.print(rp.data + " "); rp = rp.right; } System.out.println(); dp = dp.down; } } // Driver Code public static void main(String[] args) { LinkedMatrix Obj = new LinkedMatrix(); int m = 3, n = 3; // m = rows and n = columns // 2-D Matrix int[][] arr = {{ 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }}; Node head = Obj.constructLinkedMatrix(arr, m, n); Obj.display(head); }} // This code is contributed by Rhythem # Python3 program to construct a linked# list from 2D matrix | Iterative Approach # struct node of linked listclass node: def __init__(self, data): self.data = data self.right = None self.down = None # utility function to create a new node with given datadef newNode(d): temp = node(d) return temp; # utility function to print the linked list pointed to by head pointerdef display(head): rp = None dp = head; # loop until the down pointer is not None while (dp != None): rp = dp; # loop until the right pointer is not None while rp != None: print(rp.data, end = ' ') rp = rp.right; print() dp = dp.down; # function which constructs the linked list# from the given matrix of size m * n# and returns the head pointer of the linked listdef constructLinkedMatrix(mat, m, n): # stores the head of the linked list mainhead = None; # stores the head of linked lists of each row head = [0 for i in range(m)]; righttemp = None newptr = None # Firstly, we create m linked lists # by setting all the right nodes of every row for i in range(m): # initially set the head of ith row as None head[i] = None; for j in range(n): newptr = newNode(mat[i][j]); # stores the mat[0][0] node as # the mainhead of the linked list if (not mainhead): mainhead = newptr; if (not head[i]): head[i] = newptr; else: righttemp.right = newptr; righttemp = newptr; # Then, for every ith and (i+1)th list, # we set the down pointers of # every node of ith list # with its corresponding # node of (i+1)th list for i in range(m - 1): temp1 = head[i] temp2 = head[i + 1]; while (temp1 and temp2): temp1.down = temp2; temp1 = temp1.right; temp2 = temp2.right; # return the mainhead pointer of the linked list return mainhead; # Driver codeif __name__ == '__main__': m = 3 n = 3; # 2D matrix mat= [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]; head = constructLinkedMatrix(mat, m, n); display(head); # This code is contributed by rutvik_56 // C# implementation for above approachusing System; // Construct a Linked List from 2-D Matrixclass GFG{ class Node { public int data; public Node right, down; // Default Constructor public Node() { this.right = null; this.down = null; } public Node(int d) { this.data = d; this.right = null; this.down = null; } } /* A function to construct a Linked List from the given matrix of size m * n and returns the head pointer of the linked list */ Node constructLinkedMatrix(int[,] arr, int m, int n) { // stores the head of the linked list Node mainHead = null; // stores the head of linked lists // of each row Node[] head = new Node[m]; Node rightTemp = new Node(), newptr; // Firstly, we create m linked lists // by setting all the right nodes of every row for(int i = 0; i < m; i++) { // initially set the head of // ith row as NULL head[i] = null; for(int j = 0; j < n; j++) { newptr = new Node(arr[i, j]); // stores the mat[0][0] node as // the mainhead of the linked list if(mainHead == null) mainHead = newptr; if(head[i] == null) head[i] = newptr; else rightTemp.right = newptr; rightTemp = newptr; } } // Then, for every ith and (i+1)th list, // we set the down pointers of // every node of ith list // with its corresponding // node of (i+1)th list for(int i = 0; i < m - 1; i++) { Node temp1 = head[i], temp2 = head[i + 1]; while(temp1 != null && temp2 != null) { temp1.down = temp2; temp1 = temp1.right; temp2 = temp2.right; } } // return the mainhead pointer // of the linked list return mainHead; } // utility function to print the // linked list pointed to by head pointer void display(Node head) { Node rp, dp = head; // loop until the down pointer // is not NULL while(dp != null) { rp = dp; // loop until the right pointer // is not NULL while(rp != null) { Console.Write(rp.data + " "); rp = rp.right; } Console.WriteLine(); dp = dp.down; } } // Driver Code public static void Main(String[] args) { GFG Obj = new GFG(); int m = 3, n = 3; // m = rows and n = columns // 2-D Matrix int[,] arr = {{ 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }}; Node head = Obj.constructLinkedMatrix(arr, m, n); Obj.display(head); }} // This code is contributed by PrinciRaj1992 1 2 3 4 5 6 7 8 9 Time complexity: O(M * N) souravdutta123 RhythemParashar16BEE0150 princiraj1992 rutvik_56 FactSet Linked Lists pointer Linked List Matrix FactSet Linked List Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Delete a Linked List node at a given position Implementing a Linked List in Java using Class Queue - Linked List Implementation Merge two sorted linked lists Implement a stack using singly linked list Matrix Chain Multiplication | DP-8 Program to find largest element in an array Print a given matrix in spiral form Sudoku | Backtracking-7 Rat in a Maze | Backtracking-2
[ { "code": null, "e": 25016, "s": 24988, "text": "\n30 Dec, 2020" }, { "code": null, "e": 25148, "s": 25016, "text": "Given a matrix, the task is to construct a linked list matrix in which each node is connected to its right and down node.Example: " }, { "code": null, "e": 25349, "s": 25148, "text": "Input: [1 2 3\n 4 5 6\n 7 8 9]\n\nOutput:\n1 -> 2 -> 3 -> NULL\n| | |\nv v v\n4 -> 5 -> 6 -> NULL\n| | |\nv v v\n7 -> 8 -> 9 -> NULL\n| | |\nv v v\nNULL NULL NULL" }, { "code": null, "e": 25480, "s": 25351, "text": "A recursive solution for this problem has been already discussed in this post. Below is an iterative approach for the problem: " }, { "code": null, "e": 25651, "s": 25480, "text": "The idea is to create m linked lists (m = number of rows) whose each node stores its right node. The head pointers of each m linked lists are stored in an array of nodes." }, { "code": null, "e": 25797, "s": 25651, "text": "Then, traverse m lists, for every ith and (i+1)th list, set the down pointers of each node of ith list to its corresponding node of (i+1)th list." }, { "code": null, "e": 25852, "s": 25799, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 25856, "s": 25852, "text": "C++" }, { "code": null, "e": 25861, "s": 25856, "text": "Java" }, { "code": null, "e": 25869, "s": 25861, "text": "Python3" }, { "code": null, "e": 25872, "s": 25869, "text": "C#" }, { "code": "// C++ program to construct a linked// list from 2D matrix | Iterative Approach#include <bits/stdc++.h>using namespace std; // struct node of linked liststruct node { int data; node *right, *down;}; // utility function to create a new node with given datanode* newNode(int d){ node* temp = new node; temp->data = d; temp->right = temp->down = NULL; return temp;} // utility function to print the linked list pointed to by head pointervoid display(node* head){ node *rp, *dp = head; // loop until the down pointer is not NULL while (dp) { rp = dp; // loop until the right pointer is not NULL while (rp) { cout << rp->data << \" \"; rp = rp->right; } cout << endl; dp = dp->down; }} // function which constructs the linked list// from the given matrix of size m * n// and returns the head pointer of the linked listnode* constructLinkedMatrix(int mat[][3], int m, int n){ // stores the head of the linked list node* mainhead = NULL; // stores the head of linked lists of each row node* head[m]; node *righttemp, *newptr; // Firstly, we create m linked lists // by setting all the right nodes of every row for (int i = 0; i < m; i++) { // initially set the head of ith row as NULL head[i] = NULL; for (int j = 0; j < n; j++) { newptr = newNode(mat[i][j]); // stores the mat[0][0] node as // the mainhead of the linked list if (!mainhead) mainhead = newptr; if (!head[i]) head[i] = newptr; else righttemp->right = newptr; righttemp = newptr; } } // Then, for every ith and (i+1)th list, // we set the down pointers of // every node of ith list // with its corresponding // node of (i+1)th list for (int i = 0; i < m - 1; i++) { node *temp1 = head[i], *temp2 = head[i + 1]; while (temp1 && temp2) { temp1->down = temp2; temp1 = temp1->right; temp2 = temp2->right; } } // return the mainhead pointer of the linked list return mainhead;} // Driver program to test the above functionint main(){ int m, n; // m = rows and n = columns m = 3, n = 3; // 2D matrix int mat[][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; node* head = constructLinkedMatrix(mat, m, n); display(head); return 0;}", "e": 28381, "s": 25872, "text": null }, { "code": "// Java implementation for above approach // Construct a Linked List from 2-D Matrixclass LinkedMatrix{ class Node { int data; Node right, down; // Default Constructor Node() { this.right = null; this.down = null; } Node(int d) { this.data = d; this.right = null; this.down = null; } } /* A function to construct a Linked List from the given matrix of size m * n and returns the head pointer of the linked list */ Node constructLinkedMatrix(int[][] arr, int m, int n) { // stores the head of the linked list Node mainHead = null; // stores the head of linked lists // of each row Node[] head = new Node[m]; Node rightTemp = new Node(), newptr; // Firstly, we create m linked lists // by setting all the right nodes of every row for(int i = 0; i < m; i++) { // initially set the head of // ith row as NULL head[i] = null; for(int j = 0; j < n; j++) { newptr = new Node(arr[i][j]); // stores the mat[0][0] node as // the mainhead of the linked list if(mainHead == null) mainHead = newptr; if(head[i] == null) head[i] = newptr; else rightTemp.right = newptr; rightTemp = newptr; } } // Then, for every ith and (i+1)th list, // we set the down pointers of // every node of ith list // with its corresponding // node of (i+1)th list for(int i = 0; i < m - 1; i++) { Node temp1 = head[i], temp2 = head[i + 1]; while(temp1 != null && temp2 != null) { temp1.down = temp2; temp1 = temp1.right; temp2 = temp2.right; } } // return the mainhead pointer // of the linked list return mainHead; } // utility function to print the // linked list pointed to by head pointer void display(Node head) { Node rp, dp = head; // loop until the down pointer // is not NULL while(dp != null) { rp = dp; // loop until the right pointer // is not NULL while(rp != null) { System.out.print(rp.data + \" \"); rp = rp.right; } System.out.println(); dp = dp.down; } } // Driver Code public static void main(String[] args) { LinkedMatrix Obj = new LinkedMatrix(); int m = 3, n = 3; // m = rows and n = columns // 2-D Matrix int[][] arr = {{ 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }}; Node head = Obj.constructLinkedMatrix(arr, m, n); Obj.display(head); }} // This code is contributed by Rhythem", "e": 31481, "s": 28381, "text": null }, { "code": "# Python3 program to construct a linked# list from 2D matrix | Iterative Approach # struct node of linked listclass node: def __init__(self, data): self.data = data self.right = None self.down = None # utility function to create a new node with given datadef newNode(d): temp = node(d) return temp; # utility function to print the linked list pointed to by head pointerdef display(head): rp = None dp = head; # loop until the down pointer is not None while (dp != None): rp = dp; # loop until the right pointer is not None while rp != None: print(rp.data, end = ' ') rp = rp.right; print() dp = dp.down; # function which constructs the linked list# from the given matrix of size m * n# and returns the head pointer of the linked listdef constructLinkedMatrix(mat, m, n): # stores the head of the linked list mainhead = None; # stores the head of linked lists of each row head = [0 for i in range(m)]; righttemp = None newptr = None # Firstly, we create m linked lists # by setting all the right nodes of every row for i in range(m): # initially set the head of ith row as None head[i] = None; for j in range(n): newptr = newNode(mat[i][j]); # stores the mat[0][0] node as # the mainhead of the linked list if (not mainhead): mainhead = newptr; if (not head[i]): head[i] = newptr; else: righttemp.right = newptr; righttemp = newptr; # Then, for every ith and (i+1)th list, # we set the down pointers of # every node of ith list # with its corresponding # node of (i+1)th list for i in range(m - 1): temp1 = head[i] temp2 = head[i + 1]; while (temp1 and temp2): temp1.down = temp2; temp1 = temp1.right; temp2 = temp2.right; # return the mainhead pointer of the linked list return mainhead; # Driver codeif __name__ == '__main__': m = 3 n = 3; # 2D matrix mat= [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]; head = constructLinkedMatrix(mat, m, n); display(head); # This code is contributed by rutvik_56", "e": 33854, "s": 31481, "text": null }, { "code": "// C# implementation for above approachusing System; // Construct a Linked List from 2-D Matrixclass GFG{ class Node { public int data; public Node right, down; // Default Constructor public Node() { this.right = null; this.down = null; } public Node(int d) { this.data = d; this.right = null; this.down = null; } } /* A function to construct a Linked List from the given matrix of size m * n and returns the head pointer of the linked list */ Node constructLinkedMatrix(int[,] arr, int m, int n) { // stores the head of the linked list Node mainHead = null; // stores the head of linked lists // of each row Node[] head = new Node[m]; Node rightTemp = new Node(), newptr; // Firstly, we create m linked lists // by setting all the right nodes of every row for(int i = 0; i < m; i++) { // initially set the head of // ith row as NULL head[i] = null; for(int j = 0; j < n; j++) { newptr = new Node(arr[i, j]); // stores the mat[0][0] node as // the mainhead of the linked list if(mainHead == null) mainHead = newptr; if(head[i] == null) head[i] = newptr; else rightTemp.right = newptr; rightTemp = newptr; } } // Then, for every ith and (i+1)th list, // we set the down pointers of // every node of ith list // with its corresponding // node of (i+1)th list for(int i = 0; i < m - 1; i++) { Node temp1 = head[i], temp2 = head[i + 1]; while(temp1 != null && temp2 != null) { temp1.down = temp2; temp1 = temp1.right; temp2 = temp2.right; } } // return the mainhead pointer // of the linked list return mainHead; } // utility function to print the // linked list pointed to by head pointer void display(Node head) { Node rp, dp = head; // loop until the down pointer // is not NULL while(dp != null) { rp = dp; // loop until the right pointer // is not NULL while(rp != null) { Console.Write(rp.data + \" \"); rp = rp.right; } Console.WriteLine(); dp = dp.down; } } // Driver Code public static void Main(String[] args) { GFG Obj = new GFG(); int m = 3, n = 3; // m = rows and n = columns // 2-D Matrix int[,] arr = {{ 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }}; Node head = Obj.constructLinkedMatrix(arr, m, n); Obj.display(head); }} // This code is contributed by PrinciRaj1992", "e": 36980, "s": 33854, "text": null }, { "code": null, "e": 37000, "s": 36980, "text": "1 2 3 \n4 5 6 \n7 8 9" }, { "code": null, "e": 37029, "s": 37002, "text": "Time complexity: O(M * N) " }, { "code": null, "e": 37044, "s": 37029, "text": "souravdutta123" }, { "code": null, "e": 37069, "s": 37044, "text": "RhythemParashar16BEE0150" }, { "code": null, "e": 37083, "s": 37069, "text": "princiraj1992" }, { "code": null, "e": 37093, "s": 37083, "text": "rutvik_56" }, { "code": null, "e": 37101, "s": 37093, "text": "FactSet" }, { "code": null, "e": 37114, "s": 37101, "text": "Linked Lists" }, { "code": null, "e": 37122, "s": 37114, "text": "pointer" }, { "code": null, "e": 37134, "s": 37122, "text": "Linked List" }, { "code": null, "e": 37141, "s": 37134, "text": "Matrix" }, { "code": null, "e": 37149, "s": 37141, "text": "FactSet" }, { "code": null, "e": 37161, "s": 37149, "text": "Linked List" }, { "code": null, "e": 37168, "s": 37161, "text": "Matrix" }, { "code": null, "e": 37266, "s": 37168, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37275, "s": 37266, "text": "Comments" }, { "code": null, "e": 37288, "s": 37275, "text": "Old Comments" }, { "code": null, "e": 37334, "s": 37288, "text": "Delete a Linked List node at a given position" }, { "code": null, "e": 37381, "s": 37334, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 37416, "s": 37381, "text": "Queue - Linked List Implementation" }, { "code": null, "e": 37446, "s": 37416, "text": "Merge two sorted linked lists" }, { "code": null, "e": 37489, "s": 37446, "text": "Implement a stack using singly linked list" }, { "code": null, "e": 37524, "s": 37489, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 37568, "s": 37524, "text": "Program to find largest element in an array" }, { "code": null, "e": 37604, "s": 37568, "text": "Print a given matrix in spiral form" }, { "code": null, "e": 37628, "s": 37604, "text": "Sudoku | Backtracking-7" } ]
WebGL - Translation
So far, we discussed how to draw various shapes and apply colors in them using WebGL. Here, in this chapter, we will take an example to show how to translate a triangle. Translation is one of the affine transformations provided by WebGL. Using translation, we can move a triangle (any object) on the xyz plane. Suppose we have a triangle [a, b, c] and we want to move the triangle to a position which is 5 units towards the positive X-axis and 3 units towards the positive Y-axis. Then the new vertices would be [a+5, b+3, c+0]. That means, to translate the triangle, we need to add the translation distances, say, tx, ty, tz to each vertex. Since it is a per-vertex operation, we can carry it in the vertex shader program. In the vertex shader, along with the attribute, coordinates (that hold the vertex positions), we define a uniform variable that holds the translation distances (x,y,z). Later, we add this uniform variable to the coordinates variable and assign the result to the gl_Position variable. Note βˆ’ Since vertex shader will be run on each vertex, all the vertices of the triangle will be translated. The following steps are required to create a WebGL application to draw a triangle and then translate it to a new position. Step 1 βˆ’ Prepare the Canvas and Get the WebGL Rendering Context In this step, we obtain the WebGL Rendering context object using getContext(). Step 2 βˆ’ Define the Geometry and Store it in the Buffer Objects Since we are drawing a triangle, we have to pass three vertices of the triangle, and store them in buffers. var vertices = [ -0.5,0.5,0.0, -0.5,-0.5,0.0, 0.5,-0.5,0.0, ]; Step 3 βˆ’ Create and Compile the Shader Programs In this step, you need to write the vertex shader and fragment shader programs, compile them, and create a combined program by linking these two programs. Vertex Shader βˆ’ In the vertex shader of the program, we define a vector attribute to store 3D coordinates. Along with it, we define a uniform variable to store the translation distances, and finally, we add these two values and assign it to gl_position which holds the final position of the vertices. Vertex Shader βˆ’ In the vertex shader of the program, we define a vector attribute to store 3D coordinates. Along with it, we define a uniform variable to store the translation distances, and finally, we add these two values and assign it to gl_position which holds the final position of the vertices. var vertCode = 'attribute vec4 coordinates;' + 'uniform vec4 translation;'+ 'void main(void) {' + ' gl_Position = coordinates + translation;' + '}'; Fragment Shader βˆ’ In the fragment shader, we simply assign the fragment color to the variable gl_FragColor. Fragment Shader βˆ’ In the fragment shader, we simply assign the fragment color to the variable gl_FragColor. var fragCode = 'void main(void) {' +' gl_FragColor = vec4(1, 0.5, 0.0, 1);' +'}'; Step 4 βˆ’ Associate the Shader Programs to the Buffer Objects In this step, we associate the buffer objects with the shader program. Step 5 βˆ’ Drawing the Required Object Since we are drawing the triangle using indices, we will use the method drawArrays(). To this method, we have to pass the number of vertices /elements to be considered. Since we are drawing a triangle, we will pass 3 as a parameter. gl.drawArrays(gl.TRIANGLES, 0, 3); The following example show how to translate a triangle on xyz plane. <!doctype html> <html> <body> <canvas width = "300" height = "300" id = "my_Canvas"></canvas> <script> /*=================Creating a canvas=========================*/ var canvas = document.getElementById('my_Canvas'); gl = canvas.getContext('experimental-webgl'); /*===========Defining and storing the geometry==============*/ var vertices = [ -0.5,0.5,0.0, -0.5,-0.5,0.0, 0.5,-0.5,0.0, ]; //Create an empty buffer object and store vertex data var vertex_buffer = gl.createBuffer(); //Create a new buffer gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer); //bind it to the current buffer gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW); // Pass the buffer data gl.bindBuffer(gl.ARRAY_BUFFER, null); /*========================Shaders============================*/ //vertex shader source code var vertCode = 'attribute vec4 coordinates;' + 'uniform vec4 translation;'+ 'void main(void) {' + ' gl_Position = coordinates + translation;' + '}'; //Create a vertex shader program object and compile it var vertShader = gl.createShader(gl.VERTEX_SHADER); gl.shaderSource(vertShader, vertCode); gl.compileShader(vertShader); //fragment shader source code var fragCode = 'void main(void) {' + ' gl_FragColor = vec4(0.0, 0.0, 0.0, 0.1);' + '}'; //Create a fragment shader program object and compile it var fragShader = gl.createShader(gl.FRAGMENT_SHADER); gl.shaderSource(fragShader, fragCode); gl.compileShader(fragShader); //Create and use combiened shader program var shaderProgram = gl.createProgram(); gl.attachShader(shaderProgram, vertShader); gl.attachShader(shaderProgram, fragShader); gl.linkProgram(shaderProgram); gl.useProgram(shaderProgram); /* ===========Associating shaders to buffer objects============*/ gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer); var coordinatesVar = gl.getAttribLocation(shaderProgram, "coordinates"); gl.vertexAttribPointer(coordinatesVar, 3, gl.FLOAT, false, 0, 0); gl.enableVertexAttribArray(coordinatesVar); /* ==========translation======================================*/ var Tx = 0.5, Ty = 0.5, Tz = 0.0; var translation = gl.getUniformLocation(shaderProgram, 'translation'); gl.uniform4f(translation, Tx, Ty, Tz, 0.0); /*=================Drawing the riangle and transforming it========================*/ gl.clearColor(0.5, 0.5, 0.5, 0.9); gl.enable(gl.DEPTH_TEST); gl.clear(gl.COLOR_BUFFER_BIT); gl.viewport(0,0,canvas.width,canvas.height); gl.drawArrays(gl.TRIANGLES, 0, 3); </script> </body> </html> If you run this example, it will produce the following output βˆ’ 10 Lectures 1 hours Frahaan Hussain 28 Lectures 4 hours Frahaan Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 2217, "s": 2047, "text": "So far, we discussed how to draw various shapes and apply colors in them using WebGL. Here, in this chapter, we will take an example to show how to translate a triangle." }, { "code": null, "e": 2689, "s": 2217, "text": "Translation is one of the affine transformations provided by WebGL. Using translation, we can move a triangle (any object) on the xyz plane. Suppose we have a triangle [a, b, c] and we want to move the triangle to a position which is 5 units towards the positive X-axis and 3 units towards the positive Y-axis. Then the new vertices would be [a+5, b+3, c+0]. That means, to translate the triangle, we need to add the translation distances, say, tx, ty, tz to each vertex." }, { "code": null, "e": 2771, "s": 2689, "text": "Since it is a per-vertex operation, we can carry it in the vertex shader program." }, { "code": null, "e": 3055, "s": 2771, "text": "In the vertex shader, along with the attribute, coordinates (that hold the vertex positions), we define a uniform variable that holds the translation distances (x,y,z). Later, we add this uniform variable to the coordinates variable and assign the result to the gl_Position variable." }, { "code": null, "e": 3163, "s": 3055, "text": "Note βˆ’ Since vertex shader will be run on each vertex, all the vertices of the triangle will be translated." }, { "code": null, "e": 3286, "s": 3163, "text": "The following steps are required to create a WebGL application to draw a triangle and then translate it to a new position." }, { "code": null, "e": 3350, "s": 3286, "text": "Step 1 βˆ’ Prepare the Canvas and Get the WebGL Rendering Context" }, { "code": null, "e": 3429, "s": 3350, "text": "In this step, we obtain the WebGL Rendering context object using getContext()." }, { "code": null, "e": 3493, "s": 3429, "text": "Step 2 βˆ’ Define the Geometry and Store it in the Buffer Objects" }, { "code": null, "e": 3601, "s": 3493, "text": "Since we are drawing a triangle, we have to pass three vertices of the triangle, and store them in buffers." }, { "code": null, "e": 3665, "s": 3601, "text": "var vertices = [ -0.5,0.5,0.0, -0.5,-0.5,0.0, 0.5,-0.5,0.0, ];\n" }, { "code": null, "e": 3713, "s": 3665, "text": "Step 3 βˆ’ Create and Compile the Shader Programs" }, { "code": null, "e": 3868, "s": 3713, "text": "In this step, you need to write the vertex shader and fragment shader programs, compile them, and create a combined program by linking these two programs." }, { "code": null, "e": 4169, "s": 3868, "text": "Vertex Shader βˆ’ In the vertex shader of the program, we define a vector attribute to store 3D coordinates. Along with it, we define a uniform variable to store the translation distances, and finally, we add these two values and assign it to gl_position which holds the final position of the vertices." }, { "code": null, "e": 4470, "s": 4169, "text": "Vertex Shader βˆ’ In the vertex shader of the program, we define a vector attribute to store 3D coordinates. Along with it, we define a uniform variable to store the translation distances, and finally, we add these two values and assign it to gl_position which holds the final position of the vertices." }, { "code": null, "e": 4638, "s": 4470, "text": "var vertCode =\n 'attribute vec4 coordinates;' +\n 'uniform vec4 translation;'+\n 'void main(void) {' +\n ' gl_Position = coordinates + translation;' +\n '}';\n" }, { "code": null, "e": 4746, "s": 4638, "text": "Fragment Shader βˆ’ In the fragment shader, we simply assign the fragment color to the variable gl_FragColor." }, { "code": null, "e": 4854, "s": 4746, "text": "Fragment Shader βˆ’ In the fragment shader, we simply assign the fragment color to the variable gl_FragColor." }, { "code": null, "e": 4937, "s": 4854, "text": "var fragCode = 'void main(void) {' +' gl_FragColor = vec4(1, 0.5, 0.0, 1);' +'}';\n" }, { "code": null, "e": 4998, "s": 4937, "text": "Step 4 βˆ’ Associate the Shader Programs to the Buffer Objects" }, { "code": null, "e": 5069, "s": 4998, "text": "In this step, we associate the buffer objects with the shader program." }, { "code": null, "e": 5106, "s": 5069, "text": "Step 5 βˆ’ Drawing the Required Object" }, { "code": null, "e": 5339, "s": 5106, "text": "Since we are drawing the triangle using indices, we will use the method drawArrays(). To this method, we have to pass the number of vertices /elements to be considered. Since we are drawing a triangle, we will pass 3 as a parameter." }, { "code": null, "e": 5375, "s": 5339, "text": "gl.drawArrays(gl.TRIANGLES, 0, 3);\n" }, { "code": null, "e": 5444, "s": 5375, "text": "The following example show how to translate a triangle on xyz plane." }, { "code": null, "e": 8704, "s": 5444, "text": "<!doctype html>\n<html>\n <body>\n <canvas width = \"300\" height = \"300\" id = \"my_Canvas\"></canvas>\n \n <script>\n /*=================Creating a canvas=========================*/\n var canvas = document.getElementById('my_Canvas');\n gl = canvas.getContext('experimental-webgl'); \n \n /*===========Defining and storing the geometry==============*/\n var vertices = [\n -0.5,0.5,0.0, \t\n -0.5,-0.5,0.0, \t\n 0.5,-0.5,0.0, \n ];\n \n //Create an empty buffer object and store vertex data \n var vertex_buffer = gl.createBuffer(); \n\t\t\t\n //Create a new buffer\n gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer); \n\t\t\t\n //bind it to the current buffer\t\t\t\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW); \n\t\t\t\n // Pass the buffer data\n gl.bindBuffer(gl.ARRAY_BUFFER, null); \n \n /*========================Shaders============================*/\n \n //vertex shader source code \n var vertCode =\n 'attribute vec4 coordinates;' + \n 'uniform vec4 translation;'+\n 'void main(void) {' +\n ' gl_Position = coordinates + translation;' +\n '}';\n \n //Create a vertex shader program object and compile it \n var vertShader = gl.createShader(gl.VERTEX_SHADER);\n gl.shaderSource(vertShader, vertCode);\n gl.compileShader(vertShader);\n \n \n //fragment shader source code\n var fragCode =\n 'void main(void) {' +\n ' gl_FragColor = vec4(0.0, 0.0, 0.0, 0.1);' +\n '}';\n\n //Create a fragment shader program object and compile it \n var fragShader = gl.createShader(gl.FRAGMENT_SHADER);\n gl.shaderSource(fragShader, fragCode);\n gl.compileShader(fragShader);\n \n //Create and use combiened shader program\n var shaderProgram = gl.createProgram();\n gl.attachShader(shaderProgram, vertShader);\n gl.attachShader(shaderProgram, fragShader);\n gl.linkProgram(shaderProgram);\n \n gl.useProgram(shaderProgram);\n \n /* ===========Associating shaders to buffer objects============*/\n \n gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer); \n var coordinatesVar = gl.getAttribLocation(shaderProgram, \"coordinates\");\n gl.vertexAttribPointer(coordinatesVar, 3, gl.FLOAT, false, 0, 0); \n gl.enableVertexAttribArray(coordinatesVar); \n \n /* ==========translation======================================*/\n var Tx = 0.5, Ty = 0.5, Tz = 0.0;\n var translation = gl.getUniformLocation(shaderProgram, 'translation');\n gl.uniform4f(translation, Tx, Ty, Tz, 0.0);\n \n /*=================Drawing the riangle and transforming it========================*/ \n\n gl.clearColor(0.5, 0.5, 0.5, 0.9);\n gl.enable(gl.DEPTH_TEST);\n \n gl.clear(gl.COLOR_BUFFER_BIT);\n gl.viewport(0,0,canvas.width,canvas.height);\n gl.drawArrays(gl.TRIANGLES, 0, 3);\n </script>\n </body>\n </html>" }, { "code": null, "e": 8768, "s": 8704, "text": "If you run this example, it will produce the following output βˆ’" }, { "code": null, "e": 8801, "s": 8768, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 8818, "s": 8801, "text": " Frahaan Hussain" }, { "code": null, "e": 8851, "s": 8818, "text": "\n 28 Lectures \n 4 hours \n" }, { "code": null, "e": 8868, "s": 8851, "text": " Frahaan Hussain" }, { "code": null, "e": 8875, "s": 8868, "text": " Print" }, { "code": null, "e": 8886, "s": 8875, "text": " Add Notes" } ]
File.Exists() Method in C# with Examples
11 Oct, 2021 File.Exists(String) is an inbuilt File class method that is used to determine whether the specified file exists or not. This method returns true if the caller has the required permissions and path contains the name of an existing file; otherwise, false. Also, if the path is null, then this method returns false. Syntax: public static bool Exists (string path); Here, path is the specified path that is to be checked. Program 1: Before running the below code, a file file.txt is created with some contents shown below: CSharp // C# program to illustrate the usage// of File.Exists(String) method // Using System and System.IO namespacesusing System;using System.IO; class GFG { static void Main() { // Checking the existence of the specified if (File.Exists("file.txt")) { Console.WriteLine("Specified file exists."); } else { Console.WriteLine("Specified file does not "+ "exist in the current directory."); } }} Output: Specified file exists. Program 2: Before running the below code, no file is created. CSharp // C# program to illustrate the usage// of File.Exists(String) method // Using System and System.IO namespacesusing System;using System.IO; class GFG { static void Main() { // Checking the existence of the specified if (File.Exists("file.txt")) { Console.WriteLine("Specified file exists."); } else { Console.WriteLine("Specified file does not"+ " exist in the current directory."); } }} Output: Specified file does not exist in the current directory. khushboogoyal499 CSharp-File-Handling C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Oct, 2021" }, { "code": null, "e": 342, "s": 28, "text": "File.Exists(String) is an inbuilt File class method that is used to determine whether the specified file exists or not. This method returns true if the caller has the required permissions and path contains the name of an existing file; otherwise, false. Also, if the path is null, then this method returns false. " }, { "code": null, "e": 352, "s": 342, "text": "Syntax: " }, { "code": null, "e": 393, "s": 352, "text": "public static bool Exists (string path);" }, { "code": null, "e": 451, "s": 393, "text": "Here, path is the specified path that is to be checked. " }, { "code": null, "e": 553, "s": 451, "text": "Program 1: Before running the below code, a file file.txt is created with some contents shown below: " }, { "code": null, "e": 562, "s": 555, "text": "CSharp" }, { "code": "// C# program to illustrate the usage// of File.Exists(String) method // Using System and System.IO namespacesusing System;using System.IO; class GFG { static void Main() { // Checking the existence of the specified if (File.Exists(\"file.txt\")) { Console.WriteLine(\"Specified file exists.\"); } else { Console.WriteLine(\"Specified file does not \"+ \"exist in the current directory.\"); } }}", "e": 1037, "s": 562, "text": null }, { "code": null, "e": 1047, "s": 1037, "text": "Output: " }, { "code": null, "e": 1070, "s": 1047, "text": "Specified file exists." }, { "code": null, "e": 1133, "s": 1070, "text": "Program 2: Before running the below code, no file is created. " }, { "code": null, "e": 1140, "s": 1133, "text": "CSharp" }, { "code": "// C# program to illustrate the usage// of File.Exists(String) method // Using System and System.IO namespacesusing System;using System.IO; class GFG { static void Main() { // Checking the existence of the specified if (File.Exists(\"file.txt\")) { Console.WriteLine(\"Specified file exists.\"); } else { Console.WriteLine(\"Specified file does not\"+ \" exist in the current directory.\"); } }}", "e": 1613, "s": 1140, "text": null }, { "code": null, "e": 1623, "s": 1613, "text": "Output: " }, { "code": null, "e": 1679, "s": 1623, "text": "Specified file does not exist in the current directory." }, { "code": null, "e": 1698, "s": 1681, "text": "khushboogoyal499" }, { "code": null, "e": 1719, "s": 1698, "text": "CSharp-File-Handling" }, { "code": null, "e": 1722, "s": 1719, "text": "C#" } ]
Python MongoDB – find_one Query
04 Jul, 2022 This article focus on the find_one() method of the PyMongo library. find_one() is used to find the data from MongoDB. Prerequisites: MongoDB Python Basics Let’s begin with the find_one() method: Importing PyMongo Module: Import the PyMongo module using the command: from pymongo import MongoClient If MongoDB is already not installed on your machine, one can refer to the guide og how to Install MongoDB with Python.Creating a Connection: Now we had already imported the module, it’s time to establish a connection to the MongoDB server, presumably which is running on localhost (host name) at port 27017 (port number). If MongoDB is already not installed on your machine, one can refer to the guide og how to Install MongoDB with Python. Creating a Connection: Now we had already imported the module, it’s time to establish a connection to the MongoDB server, presumably which is running on localhost (host name) at port 27017 (port number). client = MongoClient(β€˜localhost’, 27017) Accessing the Database: Since the connection to the MongoDB server is established. We can now create or use the existing database. mydatabase = client.name_of_the_database Accessing the Collection: We now select the collection from the database using the following syntax: collection_name = mydatabase.name_of_collection Finding in the collection: Now we will find in the collection using find_one() function. This function return only one document if the data is found in the collection else it returns None. It is ideal for those situations where we need to search for only one document. Syntax: find_one(filter=None, *args, **kwargs) Example 1: Sample Database: Python3 # Python program to demonstrate# find_one() method # Importing Libraryfrom pymongo import MongoClient # Connecting to MongoDB server# client = MongoClient('host_name','port_number')client = MongoClient('localhost', 27017) # Connecting to the database named# GFGmydatabase = client.GFG # Accessing the collection named# gfg_collectionmycollection = mydatabase.Student # Searching through the database# using find_one method.result = mycollection.find_one({'Branch': 'CSE'})print(result) Output: {'_id': 1, 'name': 'Vishwash', 'Roll No': '1001', 'Branch': 'CSE'} Example 2: Python3 # Python program to demonstrate# find_one() method # Importing Libraryfrom pymongo import MongoClient # Connecting to MongoDB server# client = MongoClient('host_name','port_number')client = MongoClient('localhost', 27017) # Connecting to the database named# GFGmydatabase = client.GFG # Accessing the collection named# gfg_collectionmycollection = mydatabase.Student # Searching through the database# using find_one method.result = mycollection.find_one({'Branch': 'CSE'}, {'_id': 0, 'name': 1, 'Roll No': 1})print(result) Output: {'name': 'Vishwash', 'Roll No': '1001'} khushb99 Python-mongoDB Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Jul, 2022" }, { "code": null, "e": 147, "s": 28, "text": "This article focus on the find_one() method of the PyMongo library. find_one() is used to find the data from MongoDB. " }, { "code": null, "e": 185, "s": 147, "text": "Prerequisites: MongoDB Python Basics " }, { "code": null, "e": 225, "s": 185, "text": "Let’s begin with the find_one() method:" }, { "code": null, "e": 296, "s": 225, "text": "Importing PyMongo Module: Import the PyMongo module using the command:" }, { "code": null, "e": 328, "s": 296, "text": "from pymongo import MongoClient" }, { "code": null, "e": 650, "s": 328, "text": "If MongoDB is already not installed on your machine, one can refer to the guide og how to Install MongoDB with Python.Creating a Connection: Now we had already imported the module, it’s time to establish a connection to the MongoDB server, presumably which is running on localhost (host name) at port 27017 (port number)." }, { "code": null, "e": 769, "s": 650, "text": "If MongoDB is already not installed on your machine, one can refer to the guide og how to Install MongoDB with Python." }, { "code": null, "e": 973, "s": 769, "text": "Creating a Connection: Now we had already imported the module, it’s time to establish a connection to the MongoDB server, presumably which is running on localhost (host name) at port 27017 (port number)." }, { "code": null, "e": 1014, "s": 973, "text": "client = MongoClient(β€˜localhost’, 27017)" }, { "code": null, "e": 1145, "s": 1014, "text": "Accessing the Database: Since the connection to the MongoDB server is established. We can now create or use the existing database." }, { "code": null, "e": 1186, "s": 1145, "text": "mydatabase = client.name_of_the_database" }, { "code": null, "e": 1287, "s": 1186, "text": "Accessing the Collection: We now select the collection from the database using the following syntax:" }, { "code": null, "e": 1335, "s": 1287, "text": "collection_name = mydatabase.name_of_collection" }, { "code": null, "e": 1612, "s": 1335, "text": "Finding in the collection: Now we will find in the collection using find_one() function. This function return only one document if the data is found in the collection else it returns None. It is ideal for those situations where we need to search for only one document. Syntax:" }, { "code": null, "e": 1651, "s": 1612, "text": "find_one(filter=None, *args, **kwargs)" }, { "code": null, "e": 1681, "s": 1651, "text": "Example 1: Sample Database: " }, { "code": null, "e": 1689, "s": 1681, "text": "Python3" }, { "code": "# Python program to demonstrate# find_one() method # Importing Libraryfrom pymongo import MongoClient # Connecting to MongoDB server# client = MongoClient('host_name','port_number')client = MongoClient('localhost', 27017) # Connecting to the database named# GFGmydatabase = client.GFG # Accessing the collection named# gfg_collectionmycollection = mydatabase.Student # Searching through the database# using find_one method.result = mycollection.find_one({'Branch': 'CSE'})print(result)", "e": 2179, "s": 1689, "text": null }, { "code": null, "e": 2187, "s": 2179, "text": "Output:" }, { "code": null, "e": 2254, "s": 2187, "text": "{'_id': 1, 'name': 'Vishwash', 'Roll No': '1001', 'Branch': 'CSE'}" }, { "code": null, "e": 2266, "s": 2254, "text": "Example 2: " }, { "code": null, "e": 2274, "s": 2266, "text": "Python3" }, { "code": "# Python program to demonstrate# find_one() method # Importing Libraryfrom pymongo import MongoClient # Connecting to MongoDB server# client = MongoClient('host_name','port_number')client = MongoClient('localhost', 27017) # Connecting to the database named# GFGmydatabase = client.GFG # Accessing the collection named# gfg_collectionmycollection = mydatabase.Student # Searching through the database# using find_one method.result = mycollection.find_one({'Branch': 'CSE'}, {'_id': 0, 'name': 1, 'Roll No': 1})print(result)", "e": 2831, "s": 2274, "text": null }, { "code": null, "e": 2839, "s": 2831, "text": "Output:" }, { "code": null, "e": 2879, "s": 2839, "text": "{'name': 'Vishwash', 'Roll No': '1001'}" }, { "code": null, "e": 2888, "s": 2879, "text": "khushb99" }, { "code": null, "e": 2903, "s": 2888, "text": "Python-mongoDB" }, { "code": null, "e": 2910, "s": 2903, "text": "Python" } ]
Count Strictly Increasing Subarrays
04 Jun, 2022 Given an array of integers, count number of subarrays (of size more than one) that are strictly increasing. Expected Time Complexity : O(n) Expected Extra Space: O(1) Examples: 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. Input: arr[] = {1, 4, 3} Output: 1 There is only one subarray {1, 4} Input: arr[] = {1, 2, 3, 4} Output: 6 There are 6 subarrays {1, 2}, {1, 2, 3}, {1, 2, 3, 4} {2, 3}, {2, 3, 4} and {3, 4} Input: arr[] = {1, 2, 2, 4} Output: 2 There are 2 subarrays {1, 2} and {2, 4} A Simple Solution is to generate all possible subarrays, and for every subarray check if subarray is strictly increasing or not. Worst case time complexity of this solution would be O(n3). A Better Solution is to use the fact that if subarray arr[i:j] is not strictly increasing, then subarrays arr[i:j+1], arr[i:j+2], .. arr[i:n-1] cannot be strictly increasing. Below is the program based on above idea. C++ Java Python3 C# PHP Javascript // C++ program to count number of strictly// increasing subarrays#include<bits/stdc++.h>using namespace std; int countIncreasing(int arr[], int n){ // Initialize count of subarrays as 0 int cnt = 0; // Pick starting point for (int i=0; i<n; i++) { // Pick ending point for (int j=i+1; j<n; j++) { if (arr[j] > arr[j-1]) cnt++; // If subarray arr[i..j] is not strictly // increasing, then subarrays after it , i.e., // arr[i..j+1], arr[i..j+2], .... cannot // be strictly increasing else break; } } return cnt;} // Driver programint main(){ int arr[] = {1, 2, 2, 4}; int n = sizeof(arr)/sizeof(arr[0]); cout << "Count of strictly increasing subarrays is " << countIncreasing(arr, n); return 0;} // Java program to count number of strictly// increasing subarrays class Test{ static int arr[] = new int[]{1, 2, 2, 4}; static int countIncreasing(int n) { // Initialize count of subarrays as 0 int cnt = 0; // Pick starting point for (int i=0; i<n; i++) { // Pick ending point for (int j=i+1; j<n; j++) { if (arr[j] > arr[j-1]) cnt++; // If subarray arr[i..j] is not strictly // increasing, then subarrays after it , i.e., // arr[i..j+1], arr[i..j+2], .... cannot // be strictly increasing else break; } } return cnt; } // Driver method to test the above function public static void main(String[] args) { System.out.println("Count of strictly increasing subarrays is " + countIncreasing(arr.length)); }} # Python3 program to count number# of strictly increasing subarrays def countIncreasing(arr, n): # Initialize count of subarrays as 0 cnt = 0 # Pick starting point for i in range(0, n) : # Pick ending point for j in range(i + 1, n) : if arr[j] > arr[j - 1] : cnt += 1 # If subarray arr[i..j] is not strictly # increasing, then subarrays after it , i.e., # arr[i..j+1], arr[i..j+2], .... cannot # be strictly increasing else: break return cnt # Driver codearr = [1, 2, 2, 4]n = len(arr)print ("Count of strictly increasing subarrays is", countIncreasing(arr, n)) # This code is contributed by Shreyanshi Arun. // C# program to count number of// strictly increasing subarraysusing System; class Test{ static int []arr = new int[]{1, 2, 2, 4}; static int countIncreasing(int n) { // Initialize count of subarrays as 0 int cnt = 0; // Pick starting point for (int i = 0; i < n; i++) { // Pick ending point for (int j = i + 1; j < n; j++) { if (arr[j] > arr[j - 1]) cnt++; // If subarray arr[i..j] is not strictly // increasing, then subarrays after it , // i.e., arr[i..j+1], arr[i..j+2], .... // cannot be strictly increasing else break; } } return cnt; } // Driver Code public static void Main(String[] args) { Console.Write("Count of strictly increasing" + "subarrays is " + countIncreasing(arr.Length)); }} // This code is contributed by parashar. <?php// PHP program to count number of// strictly increasing subarrays function countIncreasing( $arr, $n){ // Initialize count of subarrays // as 0 $cnt = 0; // Pick starting point for ( $i = 0; $i < $n; $i++) { // Pick ending point for ( $j = $i+1; $j < $n; $j++) { if ($arr[$j] > $arr[$j-1]) $cnt++; // If subarray arr[i..j] is // not strictly increasing, // then subarrays after it, // i.e., arr[i..j+1], // arr[i..j+2], .... cannot // be strictly increasing else break; } } return $cnt;} // Driver program $arr = array(1, 2, 2, 4);$n = count($arr);echo "Count of strictly increasing ", "subarrays is ", countIncreasing($arr, $n); // This code is contributed by anuj_67.?> <script> // Javascript program to count number of strictly// increasing subarraysfunction countIncreasing(arr, n){ // Initialize count of subarrays as 0 let cnt = 0; // Pick starting point for(let i = 0; i < n; i++) { // Pick ending point for (let j = i + 1; j < n; j++) { if (arr[j] > arr[j - 1]) cnt++; // If subarray arr[i..j] is not strictly // increasing, then subarrays after it , i.e., // arr[i..j+1], arr[i..j+2], .... cannot // be strictly increasing else break; } } return cnt;} // Driver codelet arr = [ 1, 2, 2, 4 ];let n = arr.length;document.write("Count of strictly " + "increasing subarrays is " + countIncreasing(arr, n)); // This code is contributed by divyesh072019 </script> Output : Count of strictly increasing subarrays is 2 Time Complexity: O(n2) Auxiliary Space: O(1) Time complexity of the above solution is O(m) where m is number of subarrays in outputThis problem and solution are contributed by Rahul Agrawal. An Efficient Solution can count subarrays in O(n) time. The idea is based on fact that a sorted subarray of length β€˜len’ adds len*(len-1)/2 to result. For example, {10, 20, 30, 40} adds 6 to the result. C++ Java Python3 C# PHP Javascript // C++ program to count number of strictly// increasing subarrays in O(n) time.#include<bits/stdc++.h>using namespace std; int countIncreasing(int arr[], int n){ int cnt = 0; // Initialize result // Initialize length of current increasing // subarray int len = 1; // Traverse through the array for (int i=0; i < n-1; ++i) { // If arr[i+1] is greater than arr[i], // then increment length if (arr[i + 1] > arr[i]) len++; // Else Update count and reset length else { cnt += (((len - 1) * len) / 2); len = 1; } } // If last length is more than 1 if (len > 1) cnt += (((len - 1) * len) / 2); return cnt;} // Driver programint main(){ int arr[] = {1, 2, 2, 4}; int n = sizeof(arr)/sizeof(arr[0]); cout << "Count of strictly increasing subarrays is " << countIncreasing(arr, n); return 0;} // Java program to count number of strictly// increasing subarrays class Test{ static int arr[] = new int[]{1, 2, 2, 4}; static int countIncreasing(int n) { int cnt = 0; // Initialize result // Initialize length of current increasing // subarray int len = 1; // Traverse through the array for (int i=0; i < n-1; ++i) { // If arr[i+1] is greater than arr[i], // then increment length if (arr[i + 1] > arr[i]) len++; // Else Update count and reset length else { cnt += (((len - 1) * len) / 2); len = 1; } } // If last length is more than 1 if (len > 1) cnt += (((len - 1) * len) / 2); return cnt; } // Driver method to test the above function public static void main(String[] args) { System.out.println("Count of strictly increasing subarrays is " + countIncreasing(arr.length)); }} # Python3 program to count number of# strictlyincreasing subarrays in O(n) time. def countIncreasing(arr, n): cnt = 0 # Initialize result # Initialize length of current # increasing subarray len = 1 # Traverse through the array for i in range(0, n - 1) : # If arr[i+1] is greater than arr[i], # then increment length if arr[i + 1] > arr[i] : len += 1 # Else Update count and reset length else: cnt += (((len - 1) * len) / 2) len = 1 # If last length is more than 1 if len > 1: cnt += (((len - 1) * len) / 2) return cnt # Driver programarr = [1, 2, 2, 4]n = len(arr) print ("Count of strictly increasing subarrays is", int(countIncreasing(arr, n))) # This code is contributed by Shreyanshi Arun. // C# program to count number of strictly// increasing subarraysusing System; class GFG { static int []arr = new int[]{1, 2, 2, 4}; static int countIncreasing(int n) { int cnt = 0; // Initialize result // Initialize length of current // increasing subarray int len = 1; // Traverse through the array for (int i = 0; i < n-1; ++i) { // If arr[i+1] is greater than // arr[i], then increment length if (arr[i + 1] > arr[i]) len++; // Else Update count and reset // length else { cnt += (((len - 1) * len) / 2); len = 1; } } // If last length is more than 1 if (len > 1) cnt += (((len - 1) * len) / 2); return cnt; } // Driver method to test the // above function public static void Main() { Console.WriteLine("Count of strictly " + "increasing subarrays is " + countIncreasing(arr.Length)); }} // This code is contribute by anuj_67. <?php// PHP program to count number of strictly// increasing subarrays in O(n) time. function countIncreasing( $arr, $n){ // Initialize result $cnt = 0; // Initialize length of // current increasing // subarray $len = 1; // Traverse through the array for($i = 0; $i < $n - 1; ++$i) { // If arr[i+1] is greater than arr[i], // then increment length if ($arr[$i + 1] > $arr[$i]) $len++; // Else Update count and // reset length else { $cnt += ((($len - 1) * $len) / 2); $len = 1; } } // If last length is // more than 1 if ($len > 1) $cnt += ((($len - 1) * $len) / 2); return $cnt;} // Driver Code$arr = array(1, 2, 2, 4);$n = count($arr);echo "Count of strictly increasing subarrays is " , countIncreasing($arr, $n); // This code is contribute by anuj_67?> <script> // Javascript program to count number of strictly // increasing subarrays let arr = [1, 2, 2, 4]; function countIncreasing(n) { let cnt = 0; // Initialize result // Initialize length of current // increasing subarray let len = 1; // Traverse through the array for (let i = 0; i < n-1; ++i) { // If arr[i+1] is greater than // arr[i], then increment length if (arr[i + 1] > arr[i]) len++; // Else Update count and reset // length else { cnt += (((len - 1) * len) / 2); len = 1; } } // If last length is more than 1 if (len > 1) cnt += (((len - 1) * len) / 2); return cnt; } document.write("Count of strictly " + "increasing subarrays is " + countIncreasing(arr.length)); </script> Output : Count of strictly increasing subarrays is 2 Time Complexity: O(n) Auxiliary Space: O(1) Count Strictly Increasing Subarrays | GeeksforGeeks - YouTubeGeeksforGeeks532K subscribersCount Strictly Increasing Subarrays | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 10:00β€’Liveβ€’<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=eMuC2LCoMvU" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above parashar vt_m divyesh072019 mukesh07 surinderdawra388 _shinchancode Arrays Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n04 Jun, 2022" }, { "code": null, "e": 221, "s": 54, "text": "Given an array of integers, count number of subarrays (of size more than one) that are strictly increasing. Expected Time Complexity : O(n) Expected Extra Space: O(1)" }, { "code": null, "e": 231, "s": 221, "text": "Examples:" }, { "code": null, "e": 240, "s": 231, "text": "Chapters" }, { "code": null, "e": 267, "s": 240, "text": "descriptions off, selected" }, { "code": null, "e": 317, "s": 267, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 340, "s": 317, "text": "captions off, selected" }, { "code": null, "e": 348, "s": 340, "text": "English" }, { "code": null, "e": 372, "s": 348, "text": "This is a modal window." }, { "code": null, "e": 441, "s": 372, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 463, "s": 441, "text": "End of dialog window." }, { "code": null, "e": 755, "s": 463, "text": "Input: arr[] = {1, 4, 3}\nOutput: 1\nThere is only one subarray {1, 4}\n\nInput: arr[] = {1, 2, 3, 4}\nOutput: 6\nThere are 6 subarrays {1, 2}, {1, 2, 3}, {1, 2, 3, 4}\n {2, 3}, {2, 3, 4} and {3, 4}\n\nInput: arr[] = {1, 2, 2, 4}\nOutput: 2\nThere are 2 subarrays {1, 2} and {2, 4}" }, { "code": null, "e": 944, "s": 755, "text": "A Simple Solution is to generate all possible subarrays, and for every subarray check if subarray is strictly increasing or not. Worst case time complexity of this solution would be O(n3)." }, { "code": null, "e": 1163, "s": 944, "text": "A Better Solution is to use the fact that if subarray arr[i:j] is not strictly increasing, then subarrays arr[i:j+1], arr[i:j+2], .. arr[i:n-1] cannot be strictly increasing. Below is the program based on above idea. " }, { "code": null, "e": 1167, "s": 1163, "text": "C++" }, { "code": null, "e": 1172, "s": 1167, "text": "Java" }, { "code": null, "e": 1180, "s": 1172, "text": "Python3" }, { "code": null, "e": 1183, "s": 1180, "text": "C#" }, { "code": null, "e": 1187, "s": 1183, "text": "PHP" }, { "code": null, "e": 1198, "s": 1187, "text": "Javascript" }, { "code": "// C++ program to count number of strictly// increasing subarrays#include<bits/stdc++.h>using namespace std; int countIncreasing(int arr[], int n){ // Initialize count of subarrays as 0 int cnt = 0; // Pick starting point for (int i=0; i<n; i++) { // Pick ending point for (int j=i+1; j<n; j++) { if (arr[j] > arr[j-1]) cnt++; // If subarray arr[i..j] is not strictly // increasing, then subarrays after it , i.e., // arr[i..j+1], arr[i..j+2], .... cannot // be strictly increasing else break; } } return cnt;} // Driver programint main(){ int arr[] = {1, 2, 2, 4}; int n = sizeof(arr)/sizeof(arr[0]); cout << \"Count of strictly increasing subarrays is \" << countIncreasing(arr, n); return 0;}", "e": 2049, "s": 1198, "text": null }, { "code": "// Java program to count number of strictly// increasing subarrays class Test{ static int arr[] = new int[]{1, 2, 2, 4}; static int countIncreasing(int n) { // Initialize count of subarrays as 0 int cnt = 0; // Pick starting point for (int i=0; i<n; i++) { // Pick ending point for (int j=i+1; j<n; j++) { if (arr[j] > arr[j-1]) cnt++; // If subarray arr[i..j] is not strictly // increasing, then subarrays after it , i.e., // arr[i..j+1], arr[i..j+2], .... cannot // be strictly increasing else break; } } return cnt; } // Driver method to test the above function public static void main(String[] args) { System.out.println(\"Count of strictly increasing subarrays is \" + countIncreasing(arr.length)); }}", "e": 3070, "s": 2049, "text": null }, { "code": "# Python3 program to count number# of strictly increasing subarrays def countIncreasing(arr, n): # Initialize count of subarrays as 0 cnt = 0 # Pick starting point for i in range(0, n) : # Pick ending point for j in range(i + 1, n) : if arr[j] > arr[j - 1] : cnt += 1 # If subarray arr[i..j] is not strictly # increasing, then subarrays after it , i.e., # arr[i..j+1], arr[i..j+2], .... cannot # be strictly increasing else: break return cnt # Driver codearr = [1, 2, 2, 4]n = len(arr)print (\"Count of strictly increasing subarrays is\", countIncreasing(arr, n)) # This code is contributed by Shreyanshi Arun.", "e": 3848, "s": 3070, "text": null }, { "code": "// C# program to count number of// strictly increasing subarraysusing System; class Test{ static int []arr = new int[]{1, 2, 2, 4}; static int countIncreasing(int n) { // Initialize count of subarrays as 0 int cnt = 0; // Pick starting point for (int i = 0; i < n; i++) { // Pick ending point for (int j = i + 1; j < n; j++) { if (arr[j] > arr[j - 1]) cnt++; // If subarray arr[i..j] is not strictly // increasing, then subarrays after it , // i.e., arr[i..j+1], arr[i..j+2], .... // cannot be strictly increasing else break; } } return cnt; } // Driver Code public static void Main(String[] args) { Console.Write(\"Count of strictly increasing\" + \"subarrays is \" + countIncreasing(arr.Length)); }} // This code is contributed by parashar.", "e": 4871, "s": 3848, "text": null }, { "code": "<?php// PHP program to count number of// strictly increasing subarrays function countIncreasing( $arr, $n){ // Initialize count of subarrays // as 0 $cnt = 0; // Pick starting point for ( $i = 0; $i < $n; $i++) { // Pick ending point for ( $j = $i+1; $j < $n; $j++) { if ($arr[$j] > $arr[$j-1]) $cnt++; // If subarray arr[i..j] is // not strictly increasing, // then subarrays after it, // i.e., arr[i..j+1], // arr[i..j+2], .... cannot // be strictly increasing else break; } } return $cnt;} // Driver program $arr = array(1, 2, 2, 4);$n = count($arr);echo \"Count of strictly increasing \", \"subarrays is \", countIncreasing($arr, $n); // This code is contributed by anuj_67.?>", "e": 5756, "s": 4871, "text": null }, { "code": "<script> // Javascript program to count number of strictly// increasing subarraysfunction countIncreasing(arr, n){ // Initialize count of subarrays as 0 let cnt = 0; // Pick starting point for(let i = 0; i < n; i++) { // Pick ending point for (let j = i + 1; j < n; j++) { if (arr[j] > arr[j - 1]) cnt++; // If subarray arr[i..j] is not strictly // increasing, then subarrays after it , i.e., // arr[i..j+1], arr[i..j+2], .... cannot // be strictly increasing else break; } } return cnt;} // Driver codelet arr = [ 1, 2, 2, 4 ];let n = arr.length;document.write(\"Count of strictly \" + \"increasing subarrays is \" + countIncreasing(arr, n)); // This code is contributed by divyesh072019 </script>", "e": 6655, "s": 5756, "text": null }, { "code": null, "e": 6665, "s": 6655, "text": "Output : " }, { "code": null, "e": 6709, "s": 6665, "text": "Count of strictly increasing subarrays is 2" }, { "code": null, "e": 6754, "s": 6709, "text": "Time Complexity: O(n2) Auxiliary Space: O(1)" }, { "code": null, "e": 6900, "s": 6754, "text": "Time complexity of the above solution is O(m) where m is number of subarrays in outputThis problem and solution are contributed by Rahul Agrawal." }, { "code": null, "e": 7105, "s": 6900, "text": "An Efficient Solution can count subarrays in O(n) time. The idea is based on fact that a sorted subarray of length β€˜len’ adds len*(len-1)/2 to result. For example, {10, 20, 30, 40} adds 6 to the result. " }, { "code": null, "e": 7109, "s": 7105, "text": "C++" }, { "code": null, "e": 7114, "s": 7109, "text": "Java" }, { "code": null, "e": 7122, "s": 7114, "text": "Python3" }, { "code": null, "e": 7125, "s": 7122, "text": "C#" }, { "code": null, "e": 7129, "s": 7125, "text": "PHP" }, { "code": null, "e": 7140, "s": 7129, "text": "Javascript" }, { "code": "// C++ program to count number of strictly// increasing subarrays in O(n) time.#include<bits/stdc++.h>using namespace std; int countIncreasing(int arr[], int n){ int cnt = 0; // Initialize result // Initialize length of current increasing // subarray int len = 1; // Traverse through the array for (int i=0; i < n-1; ++i) { // If arr[i+1] is greater than arr[i], // then increment length if (arr[i + 1] > arr[i]) len++; // Else Update count and reset length else { cnt += (((len - 1) * len) / 2); len = 1; } } // If last length is more than 1 if (len > 1) cnt += (((len - 1) * len) / 2); return cnt;} // Driver programint main(){ int arr[] = {1, 2, 2, 4}; int n = sizeof(arr)/sizeof(arr[0]); cout << \"Count of strictly increasing subarrays is \" << countIncreasing(arr, n); return 0;}", "e": 8078, "s": 7140, "text": null }, { "code": "// Java program to count number of strictly// increasing subarrays class Test{ static int arr[] = new int[]{1, 2, 2, 4}; static int countIncreasing(int n) { int cnt = 0; // Initialize result // Initialize length of current increasing // subarray int len = 1; // Traverse through the array for (int i=0; i < n-1; ++i) { // If arr[i+1] is greater than arr[i], // then increment length if (arr[i + 1] > arr[i]) len++; // Else Update count and reset length else { cnt += (((len - 1) * len) / 2); len = 1; } } // If last length is more than 1 if (len > 1) cnt += (((len - 1) * len) / 2); return cnt; } // Driver method to test the above function public static void main(String[] args) { System.out.println(\"Count of strictly increasing subarrays is \" + countIncreasing(arr.length)); }}", "e": 9203, "s": 8078, "text": null }, { "code": "# Python3 program to count number of# strictlyincreasing subarrays in O(n) time. def countIncreasing(arr, n): cnt = 0 # Initialize result # Initialize length of current # increasing subarray len = 1 # Traverse through the array for i in range(0, n - 1) : # If arr[i+1] is greater than arr[i], # then increment length if arr[i + 1] > arr[i] : len += 1 # Else Update count and reset length else: cnt += (((len - 1) * len) / 2) len = 1 # If last length is more than 1 if len > 1: cnt += (((len - 1) * len) / 2) return cnt # Driver programarr = [1, 2, 2, 4]n = len(arr) print (\"Count of strictly increasing subarrays is\", int(countIncreasing(arr, n))) # This code is contributed by Shreyanshi Arun.", "e": 10055, "s": 9203, "text": null }, { "code": "// C# program to count number of strictly// increasing subarraysusing System; class GFG { static int []arr = new int[]{1, 2, 2, 4}; static int countIncreasing(int n) { int cnt = 0; // Initialize result // Initialize length of current // increasing subarray int len = 1; // Traverse through the array for (int i = 0; i < n-1; ++i) { // If arr[i+1] is greater than // arr[i], then increment length if (arr[i + 1] > arr[i]) len++; // Else Update count and reset // length else { cnt += (((len - 1) * len) / 2); len = 1; } } // If last length is more than 1 if (len > 1) cnt += (((len - 1) * len) / 2); return cnt; } // Driver method to test the // above function public static void Main() { Console.WriteLine(\"Count of strictly \" + \"increasing subarrays is \" + countIncreasing(arr.Length)); }} // This code is contribute by anuj_67.", "e": 11244, "s": 10055, "text": null }, { "code": "<?php// PHP program to count number of strictly// increasing subarrays in O(n) time. function countIncreasing( $arr, $n){ // Initialize result $cnt = 0; // Initialize length of // current increasing // subarray $len = 1; // Traverse through the array for($i = 0; $i < $n - 1; ++$i) { // If arr[i+1] is greater than arr[i], // then increment length if ($arr[$i + 1] > $arr[$i]) $len++; // Else Update count and // reset length else { $cnt += ((($len - 1) * $len) / 2); $len = 1; } } // If last length is // more than 1 if ($len > 1) $cnt += ((($len - 1) * $len) / 2); return $cnt;} // Driver Code$arr = array(1, 2, 2, 4);$n = count($arr);echo \"Count of strictly increasing subarrays is \" , countIncreasing($arr, $n); // This code is contribute by anuj_67?>", "e": 12193, "s": 11244, "text": null }, { "code": "<script> // Javascript program to count number of strictly // increasing subarrays let arr = [1, 2, 2, 4]; function countIncreasing(n) { let cnt = 0; // Initialize result // Initialize length of current // increasing subarray let len = 1; // Traverse through the array for (let i = 0; i < n-1; ++i) { // If arr[i+1] is greater than // arr[i], then increment length if (arr[i + 1] > arr[i]) len++; // Else Update count and reset // length else { cnt += (((len - 1) * len) / 2); len = 1; } } // If last length is more than 1 if (len > 1) cnt += (((len - 1) * len) / 2); return cnt; } document.write(\"Count of strictly \" + \"increasing subarrays is \" + countIncreasing(arr.length)); </script>", "e": 13251, "s": 12193, "text": null }, { "code": null, "e": 13261, "s": 13251, "text": "Output : " }, { "code": null, "e": 13305, "s": 13261, "text": "Count of strictly increasing subarrays is 2" }, { "code": null, "e": 13350, "s": 13305, "text": "Time Complexity: O(n) Auxiliary Space: O(1) " }, { "code": null, "e": 14239, "s": 13350, "text": "Count Strictly Increasing Subarrays | GeeksforGeeks - YouTubeGeeksforGeeks532K subscribersCount Strictly Increasing Subarrays | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 10:00β€’Liveβ€’<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=eMuC2LCoMvU\" 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": 14364, "s": 14239, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 14373, "s": 14364, "text": "parashar" }, { "code": null, "e": 14378, "s": 14373, "text": "vt_m" }, { "code": null, "e": 14392, "s": 14378, "text": "divyesh072019" }, { "code": null, "e": 14401, "s": 14392, "text": "mukesh07" }, { "code": null, "e": 14418, "s": 14401, "text": "surinderdawra388" }, { "code": null, "e": 14432, "s": 14418, "text": "_shinchancode" }, { "code": null, "e": 14439, "s": 14432, "text": "Arrays" }, { "code": null, "e": 14446, "s": 14439, "text": "Arrays" } ]
PHP | pathinfo( ) Function
25 Nov, 2021 The pathinfo() is an inbuilt function which is used to return information about a path using an associative array or a string. The returned array or string contains the following information: Directory name Basename Extension The path and options are sent as a parameters to the pathinfo() function and it returns an associative array containing the following elements directory name, basename, extension if the options parameter is not passed.Syntax: pathinfo(path, options) Parameters Used: The pathinfo() function in PHP accepts two parameters. path : It is a mandatory parameter which specifies the path of the file.options : It is an optional parameter which can used to restrict the elements returned by the pathinfo() function. By default it returns all the possible values which are directory name, basename, extension. Possible values can be restricted using : PATHINFO_DIRNAME – return only dirnamePATHINFO_BASENAME – return only basenamePATHINFO_EXTENSION – return only extension path : It is a mandatory parameter which specifies the path of the file. options : It is an optional parameter which can used to restrict the elements returned by the pathinfo() function. By default it returns all the possible values which are directory name, basename, extension. Possible values can be restricted using : PATHINFO_DIRNAME – return only dirnamePATHINFO_BASENAME – return only basenamePATHINFO_EXTENSION – return only extension PATHINFO_DIRNAME – return only dirname PATHINFO_BASENAME – return only basename PATHINFO_EXTENSION – return only extension Return Value: It returns an associative array containing the following elements directory name, basename, extension if the options parameter is not passed.Errors And Exceptions: PATHINFO_EXTENSION returns only the last extension, if the path has more than one extension.No extension element is returned, if the path does not have an extension.If the basename of the path starts with a dot, the following characters are interpreted as extension, and the filename is empty. PATHINFO_EXTENSION returns only the last extension, if the path has more than one extension. No extension element is returned, if the path does not have an extension. If the basename of the path starts with a dot, the following characters are interpreted as extension, and the filename is empty. Examples: Input : print_r(pathinfo("/documents/gfg.txt")); Output : Array ( [dirname] => /documents [basename] => gfg.txt [extension] => txt ) Input : print_r(pathinfo("/documents/gfg.txt", PATHINFO_DIRNAME)); Output : /documents Input : print_r(pathinfo("/documents/gfg.txt", PATHINFO_EXTENSION)); Output : txt Input : print_r(pathinfo("/documents/gfg.txt", PATHINFO_BASENAME)); Output : gfg.txt Below programs illustrate the pathinfo() function.Suppose there is a file named β€œgfg.txt”Program 1 php <?php// returning information about// the path using pathinfo() functionprint_r(pathinfo("/documents/gfg.txt"));?> Output: Array ( [dirname] => /documents [basename] => gfg.txt [extension] => txt ) Program 2 php <?php // returning information about // the directoryname path using pathinfo() function print_r(pathinfo("/documents/gfg.txt", PATHINFO_DIRNAME));?> Output: /documents Program 3 php <?php // returning information about // the extension of path using pathinfo() function print_r(pathinfo("/documents/gfg.txt", PATHINFO_EXTENSION));?> Output: txt Program 4 php <?php // returning information about // the basename of path using pathinfo() function print_r(pathinfo("/documents/gfg.txt", PATHINFO_BASENAME));?> Output: gfg.txt Reference: http://php.net/manual/en/function.pathinfo.php rajeev0719singh PHP-array PHP-function PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Nov, 2021" }, { "code": null, "e": 222, "s": 28, "text": "The pathinfo() is an inbuilt function which is used to return information about a path using an associative array or a string. The returned array or string contains the following information: " }, { "code": null, "e": 237, "s": 222, "text": "Directory name" }, { "code": null, "e": 246, "s": 237, "text": "Basename" }, { "code": null, "e": 256, "s": 246, "text": "Extension" }, { "code": null, "e": 484, "s": 256, "text": "The path and options are sent as a parameters to the pathinfo() function and it returns an associative array containing the following elements directory name, basename, extension if the options parameter is not passed.Syntax: " }, { "code": null, "e": 508, "s": 484, "text": "pathinfo(path, options)" }, { "code": null, "e": 582, "s": 508, "text": "Parameters Used: The pathinfo() function in PHP accepts two parameters. " }, { "code": null, "e": 1025, "s": 582, "text": "path : It is a mandatory parameter which specifies the path of the file.options : It is an optional parameter which can used to restrict the elements returned by the pathinfo() function. By default it returns all the possible values which are directory name, basename, extension. Possible values can be restricted using : PATHINFO_DIRNAME – return only dirnamePATHINFO_BASENAME – return only basenamePATHINFO_EXTENSION – return only extension" }, { "code": null, "e": 1098, "s": 1025, "text": "path : It is a mandatory parameter which specifies the path of the file." }, { "code": null, "e": 1469, "s": 1098, "text": "options : It is an optional parameter which can used to restrict the elements returned by the pathinfo() function. By default it returns all the possible values which are directory name, basename, extension. Possible values can be restricted using : PATHINFO_DIRNAME – return only dirnamePATHINFO_BASENAME – return only basenamePATHINFO_EXTENSION – return only extension" }, { "code": null, "e": 1508, "s": 1469, "text": "PATHINFO_DIRNAME – return only dirname" }, { "code": null, "e": 1549, "s": 1508, "text": "PATHINFO_BASENAME – return only basename" }, { "code": null, "e": 1592, "s": 1549, "text": "PATHINFO_EXTENSION – return only extension" }, { "code": null, "e": 1772, "s": 1592, "text": "Return Value: It returns an associative array containing the following elements directory name, basename, extension if the options parameter is not passed.Errors And Exceptions: " }, { "code": null, "e": 2066, "s": 1772, "text": "PATHINFO_EXTENSION returns only the last extension, if the path has more than one extension.No extension element is returned, if the path does not have an extension.If the basename of the path starts with a dot, the following characters are interpreted as extension, and the filename is empty." }, { "code": null, "e": 2159, "s": 2066, "text": "PATHINFO_EXTENSION returns only the last extension, if the path has more than one extension." }, { "code": null, "e": 2233, "s": 2159, "text": "No extension element is returned, if the path does not have an extension." }, { "code": null, "e": 2362, "s": 2233, "text": "If the basename of the path starts with a dot, the following characters are interpreted as extension, and the filename is empty." }, { "code": null, "e": 2373, "s": 2362, "text": "Examples: " }, { "code": null, "e": 2811, "s": 2373, "text": "Input : print_r(pathinfo(\"/documents/gfg.txt\"));\nOutput : Array\n (\n [dirname] => /documents\n [basename] => gfg.txt\n [extension] => txt\n )\n\nInput : print_r(pathinfo(\"/documents/gfg.txt\", PATHINFO_DIRNAME));\nOutput : /documents\n\nInput : print_r(pathinfo(\"/documents/gfg.txt\", PATHINFO_EXTENSION));\nOutput : txt\n\nInput : print_r(pathinfo(\"/documents/gfg.txt\", PATHINFO_BASENAME));\nOutput : gfg.txt" }, { "code": null, "e": 2910, "s": 2811, "text": "Below programs illustrate the pathinfo() function.Suppose there is a file named β€œgfg.txt”Program 1" }, { "code": null, "e": 2914, "s": 2910, "text": "php" }, { "code": "<?php// returning information about// the path using pathinfo() functionprint_r(pathinfo(\"/documents/gfg.txt\"));?>", "e": 3029, "s": 2914, "text": null }, { "code": null, "e": 3039, "s": 3029, "text": "Output: " }, { "code": null, "e": 3163, "s": 3039, "text": " Array\n (\n [dirname] => /documents\n [basename] => gfg.txt\n [extension] => txt\n )" }, { "code": null, "e": 3173, "s": 3163, "text": "Program 2" }, { "code": null, "e": 3177, "s": 3173, "text": "php" }, { "code": "<?php // returning information about // the directoryname path using pathinfo() function print_r(pathinfo(\"/documents/gfg.txt\", PATHINFO_DIRNAME));?>", "e": 3330, "s": 3177, "text": null }, { "code": null, "e": 3340, "s": 3330, "text": "Output: " }, { "code": null, "e": 3353, "s": 3340, "text": " /documents " }, { "code": null, "e": 3363, "s": 3353, "text": "Program 3" }, { "code": null, "e": 3367, "s": 3363, "text": "php" }, { "code": "<?php // returning information about // the extension of path using pathinfo() function print_r(pathinfo(\"/documents/gfg.txt\", PATHINFO_EXTENSION));?>", "e": 3522, "s": 3367, "text": null }, { "code": null, "e": 3532, "s": 3522, "text": "Output: " }, { "code": null, "e": 3538, "s": 3532, "text": " txt " }, { "code": null, "e": 3548, "s": 3538, "text": "Program 4" }, { "code": null, "e": 3552, "s": 3548, "text": "php" }, { "code": "<?php // returning information about // the basename of path using pathinfo() function print_r(pathinfo(\"/documents/gfg.txt\", PATHINFO_BASENAME));?>", "e": 3704, "s": 3552, "text": null }, { "code": null, "e": 3714, "s": 3704, "text": "Output: " }, { "code": null, "e": 3724, "s": 3714, "text": " gfg.txt " }, { "code": null, "e": 3783, "s": 3724, "text": "Reference: http://php.net/manual/en/function.pathinfo.php " }, { "code": null, "e": 3799, "s": 3783, "text": "rajeev0719singh" }, { "code": null, "e": 3809, "s": 3799, "text": "PHP-array" }, { "code": null, "e": 3822, "s": 3809, "text": "PHP-function" }, { "code": null, "e": 3826, "s": 3822, "text": "PHP" }, { "code": null, "e": 3843, "s": 3826, "text": "Web Technologies" }, { "code": null, "e": 3847, "s": 3843, "text": "PHP" } ]
Java Program to Make a File Read-Only
21 Jul, 2021 Read-Only is the file attribute that the operating system assigns to the file. When the file is flagged as read-only, it means that it can only be opened or read, one cannot change the name of the file, can not rewrite or append the content of the file, and also cannot delete the file. Method 1: Using setLastModified Method To make the file read-only, setReadOnly() method of File Class is used. This method returns the boolean value, which is used to check whether the task(to make the file read-only) got successful or not. If the value returned by the method is true, it means that the task was successful and vice versa. Parameters: The function doesn’t require any parameters. Return Value: The function returns boolean data type. The function returns true if the File object could be set as Read-Only else false. Exception: This method throws SecurityException if the method does not allow to write access to the file Java // Java program to make the file as read only import java.io.File; public class GFG { public static void main(String[] args) { // flag variable which contains the boolean // value returned by setReadOnly() function boolean flag; try { File file = new File("/home/mayur/GFG.java"); // creates a new file file.createNewFile(); // flag the file to be read-only flag = file.setReadOnly(); System.out.println("Is File is read-only ? : " + flag); // checking whether Is file writable flag = file.canWrite(); System.out.println("Is File is writable ? : " + flag); } catch (Exception e) { e.printStackTrace(); } }} Output: Method 2: Using setWritable() method Here by passing β€œfalse” as an argument to the setWritable() method, we can make a file read only. The following code will help you understand how to make a file read only using setWritable(). Java import java.io.File; public class ChangetoReadOnly { public static void main(String[] args) { try { File file = new File( "C://Users//sai mohan pulamolu//Desktop//test.txt"); // making the file to read only mode file.setWritable(false); // check if the file is writable or not // if not writable then it is readonly file. if (!file.canWrite()) { System.out.println( "This File is read only."); } else { System.out.println( "This File is writable."); } } catch (Exception e) { System.out.println( "Sorry unable to change to readonly mode."); } }} Output: pulamolusaimohan manikarora059 Java-Files Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class Factory method design pattern in Java Java Program to Remove Duplicate Elements From the Array
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Jul, 2021" }, { "code": null, "e": 315, "s": 28, "text": "Read-Only is the file attribute that the operating system assigns to the file. When the file is flagged as read-only, it means that it can only be opened or read, one cannot change the name of the file, can not rewrite or append the content of the file, and also cannot delete the file." }, { "code": null, "e": 325, "s": 315, "text": "Method 1:" }, { "code": null, "e": 354, "s": 325, "text": "Using setLastModified Method" }, { "code": null, "e": 655, "s": 354, "text": "To make the file read-only, setReadOnly() method of File Class is used. This method returns the boolean value, which is used to check whether the task(to make the file read-only) got successful or not. If the value returned by the method is true, it means that the task was successful and vice versa." }, { "code": null, "e": 712, "s": 655, "text": "Parameters: The function doesn’t require any parameters." }, { "code": null, "e": 849, "s": 712, "text": "Return Value: The function returns boolean data type. The function returns true if the File object could be set as Read-Only else false." }, { "code": null, "e": 954, "s": 849, "text": "Exception: This method throws SecurityException if the method does not allow to write access to the file" }, { "code": null, "e": 959, "s": 954, "text": "Java" }, { "code": "// Java program to make the file as read only import java.io.File; public class GFG { public static void main(String[] args) { // flag variable which contains the boolean // value returned by setReadOnly() function boolean flag; try { File file = new File(\"/home/mayur/GFG.java\"); // creates a new file file.createNewFile(); // flag the file to be read-only flag = file.setReadOnly(); System.out.println(\"Is File is read-only ? : \" + flag); // checking whether Is file writable flag = file.canWrite(); System.out.println(\"Is File is writable ? : \" + flag); } catch (Exception e) { e.printStackTrace(); } }}", "e": 1867, "s": 959, "text": null }, { "code": null, "e": 1876, "s": 1867, "text": "Output: " }, { "code": null, "e": 1913, "s": 1876, "text": "Method 2: Using setWritable() method" }, { "code": null, "e": 2011, "s": 1913, "text": "Here by passing β€œfalse” as an argument to the setWritable() method, we can make a file read only." }, { "code": null, "e": 2105, "s": 2011, "text": "The following code will help you understand how to make a file read only using setWritable()." }, { "code": null, "e": 2110, "s": 2105, "text": "Java" }, { "code": "import java.io.File; public class ChangetoReadOnly { public static void main(String[] args) { try { File file = new File( \"C://Users//sai mohan pulamolu//Desktop//test.txt\"); // making the file to read only mode file.setWritable(false); // check if the file is writable or not // if not writable then it is readonly file. if (!file.canWrite()) { System.out.println( \"This File is read only.\"); } else { System.out.println( \"This File is writable.\"); } } catch (Exception e) { System.out.println( \"Sorry unable to change to readonly mode.\"); } }}", "e": 2925, "s": 2110, "text": null }, { "code": null, "e": 2933, "s": 2925, "text": "Output:" }, { "code": null, "e": 2950, "s": 2933, "text": "pulamolusaimohan" }, { "code": null, "e": 2964, "s": 2950, "text": "manikarora059" }, { "code": null, "e": 2975, "s": 2964, "text": "Java-Files" }, { "code": null, "e": 2982, "s": 2975, "text": "Picked" }, { "code": null, "e": 2987, "s": 2982, "text": "Java" }, { "code": null, "e": 3001, "s": 2987, "text": "Java Programs" }, { "code": null, "e": 3006, "s": 3001, "text": "Java" }, { "code": null, "e": 3104, "s": 3006, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3119, "s": 3104, "text": "Stream In Java" }, { "code": null, "e": 3140, "s": 3119, "text": "Introduction to Java" }, { "code": null, "e": 3161, "s": 3140, "text": "Constructors in Java" }, { "code": null, "e": 3180, "s": 3161, "text": "Exceptions in Java" }, { "code": null, "e": 3197, "s": 3180, "text": "Generics in Java" }, { "code": null, "e": 3223, "s": 3197, "text": "Java Programming Examples" }, { "code": null, "e": 3257, "s": 3223, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 3304, "s": 3257, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 3342, "s": 3304, "text": "Factory method design pattern in Java" } ]
Python | Append multiple lists at once
16 Aug, 2021 There can be an application requirement to append elements of 2-3 lists to one list. This kind of application has the potential to come into the domain of Machine Learning or sometimes in web development as well. Let’s discuss certain ways in which this particular task can be performed. Method #1 : Using + operator This can be easily done using the plus operator as it does the element addition at the back of the list. Similar logic is extended in the case of multiple lists. Python3 # Python3 code to demonstrate# adding multiple list at once# using + operator # initializing liststest_list1 = [1, 3, 5, 5, 4]test_list2 = [4, 6, 2, 8, 10]test_list3 = [7, 5, 2, 9, 11] # printing original listsprint ("The original list 1 is : " + str(test_list1))print ("The original list 2 is : " + str(test_list2))print ("The original list 3 is : " + str(test_list3)) # using + operator# adding multiple list at oncetest_list1 = test_list1 + test_list2 + test_list3 # printing resultprint ("The extended and modified list is : " + str(test_list1)) Output: The original list 1 is : [1, 3, 5, 5, 4] The original list 2 is : [4, 6, 2, 8, 10] The original list 3 is : [7, 5, 2, 9, 11] The extended and modified list is : [1, 3, 5, 5, 4, 4, 6, 2, 8, 10, 7, 5, 2, 9, 11] Method #2 : Using itertools.chain() The chain function can also be employed to perform this particular tasks as it uses the iterator to perform this and hence offers better performance over the above method. Python3 # Python3 code to demonstrate# adding multiple list at once# using itertools.chain()from itertools import chain # initializing liststest_list1 = [1, 3, 5, 5, 4]test_list2 = [4, 6, 2, 8, 10]test_list3 = [7, 5, 2, 9, 11] # printing original listsprint ("The original list 1 is : " + str(test_list1))print ("The original list 2 is : " + str(test_list2))print ("The original list 3 is : " + str(test_list3)) # using itertools.chain()# adding multiple list at oncetest_list1 = list(chain(test_list1, test_list2, test_list3)) # printing resultprint ("The extended and modified list is : " + str(test_list1)) Output: The original list 1 is : [1, 3, 5, 5, 4] The original list 2 is : [4, 6, 2, 8, 10] The original list 3 is : [7, 5, 2, 9, 11] The extended and modified list is : [1, 3, 5, 5, 4, 4, 6, 2, 8, 10, 7, 5, 2, 9, 11] jonnymonty gulshankumarar231 Python list-programs python-list Python Python Programs python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Aug, 2021" }, { "code": null, "e": 316, "s": 28, "text": "There can be an application requirement to append elements of 2-3 lists to one list. This kind of application has the potential to come into the domain of Machine Learning or sometimes in web development as well. Let’s discuss certain ways in which this particular task can be performed." }, { "code": null, "e": 507, "s": 316, "text": "Method #1 : Using + operator This can be easily done using the plus operator as it does the element addition at the back of the list. Similar logic is extended in the case of multiple lists." }, { "code": null, "e": 515, "s": 507, "text": "Python3" }, { "code": "# Python3 code to demonstrate# adding multiple list at once# using + operator # initializing liststest_list1 = [1, 3, 5, 5, 4]test_list2 = [4, 6, 2, 8, 10]test_list3 = [7, 5, 2, 9, 11] # printing original listsprint (\"The original list 1 is : \" + str(test_list1))print (\"The original list 2 is : \" + str(test_list2))print (\"The original list 3 is : \" + str(test_list3)) # using + operator# adding multiple list at oncetest_list1 = test_list1 + test_list2 + test_list3 # printing resultprint (\"The extended and modified list is : \" + str(test_list1))", "e": 1070, "s": 515, "text": null }, { "code": null, "e": 1078, "s": 1070, "text": "Output:" }, { "code": null, "e": 1287, "s": 1078, "text": "The original list 1 is : [1, 3, 5, 5, 4]\nThe original list 2 is : [4, 6, 2, 8, 10]\nThe original list 3 is : [7, 5, 2, 9, 11]\nThe extended and modified list is : [1, 3, 5, 5, 4, 4, 6, 2, 8, 10, 7, 5, 2, 9, 11]" }, { "code": null, "e": 1497, "s": 1287, "text": " Method #2 : Using itertools.chain() The chain function can also be employed to perform this particular tasks as it uses the iterator to perform this and hence offers better performance over the above method." }, { "code": null, "e": 1505, "s": 1497, "text": "Python3" }, { "code": "# Python3 code to demonstrate# adding multiple list at once# using itertools.chain()from itertools import chain # initializing liststest_list1 = [1, 3, 5, 5, 4]test_list2 = [4, 6, 2, 8, 10]test_list3 = [7, 5, 2, 9, 11] # printing original listsprint (\"The original list 1 is : \" + str(test_list1))print (\"The original list 2 is : \" + str(test_list2))print (\"The original list 3 is : \" + str(test_list3)) # using itertools.chain()# adding multiple list at oncetest_list1 = list(chain(test_list1, test_list2, test_list3)) # printing resultprint (\"The extended and modified list is : \" + str(test_list1))", "e": 2112, "s": 1505, "text": null }, { "code": null, "e": 2120, "s": 2112, "text": "Output:" }, { "code": null, "e": 2329, "s": 2120, "text": "The original list 1 is : [1, 3, 5, 5, 4]\nThe original list 2 is : [4, 6, 2, 8, 10]\nThe original list 3 is : [7, 5, 2, 9, 11]\nThe extended and modified list is : [1, 3, 5, 5, 4, 4, 6, 2, 8, 10, 7, 5, 2, 9, 11]" }, { "code": null, "e": 2340, "s": 2329, "text": "jonnymonty" }, { "code": null, "e": 2358, "s": 2340, "text": "gulshankumarar231" }, { "code": null, "e": 2379, "s": 2358, "text": "Python list-programs" }, { "code": null, "e": 2391, "s": 2379, "text": "python-list" }, { "code": null, "e": 2398, "s": 2391, "text": "Python" }, { "code": null, "e": 2414, "s": 2398, "text": "Python Programs" }, { "code": null, "e": 2426, "s": 2414, "text": "python-list" } ]
Java Program to Display the ATM Transaction
09 Nov, 2020 Lets Build a Java Program, to represent ATM Transaction, where a User has to choose input from the options displayed on the Screen. The available options on the Screen include operations such as Withdraw, deposit, balance. Following are the basic operations available in the ATM WithdrawDepositCheck BalanceExit Withdraw Deposit Check Balance Exit Approach to each Option A. Withdraw: Take the amount user desires to withdraw as input.If the balance amount greater than or equal to the withdrawal amount then Perform the transaction and give the user the desired amount.Else print Insufficient Funds message. Take the amount user desires to withdraw as input. If the balance amount greater than or equal to the withdrawal amount then Perform the transaction and give the user the desired amount. Else print Insufficient Funds message. B. Deposit: Take the amount user desires to deposit as input.Add the received input from the user to balance and update its value.balance = balance + deposit.Print a message on screen stating deposit transaction has been successful. Take the amount user desires to deposit as input. Add the received input from the user to balance and update its value. balance = balance + deposit. Print a message on screen stating deposit transaction has been successful. C. Check Balance: Print a message on screen showing the value of balance amount. D. Exit: Exit the current Transaction mode and return the user to the home page or initial screen. Below is the implementation of the above approach. Java // Java Program to Display the ATM Transactionimport java.io.*;public class GFG { // Display current balance in account public static void displayBalance(int balance) { System.out.println("Current Balance : " + balance); System.out.println(); } // Withdraw amount and update the balance public static int amountWithdrawing(int balance, int withdrawAmount) { System.out.println("Withdrawn Operation:"); System.out.println("Withdrawing Amount : " + withdrawAmount); if (balance >= withdrawAmount) { balance = balance - withdrawAmount; System.out.println( "Please collect your money and collect the card"); displayBalance(balance); } else { System.out.println("Sorry! Insufficient Funds"); System.out.println(); } return balance; } // Deposit amount and update the balance public static int amountDepositing(int balance, int depositAmount) { System.out.println("Deposit Operation:"); System.out.println("Depositing Amount : " + depositAmount); balance = balance + depositAmount; System.out.println( "Your Money has been successfully deposited"); displayBalance(balance); return balance; } public static void main(String args[]) { int balance = 10000; int withdrawAmount = 5000; int depositAmount = 2000; // calling display balance displayBalance(balance); // withdrawing amount balance = amountWithdrawing(balance, withdrawAmount); // depositing amount balance = amountDepositing(balance, depositAmount); }} Current Balance : 10000 Withdrawn Operation: Withdrawing Amount : 5000 Please collect your money and collect the card Current Balance : 5000 Deposit Operation: Depositing Amount : 2000 Your Money has been successfully deposited Balance : 7000 Time Complexity: O(1) Technical Scripter 2020 Java Java Programs Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Nov, 2020" }, { "code": null, "e": 251, "s": 28, "text": "Lets Build a Java Program, to represent ATM Transaction, where a User has to choose input from the options displayed on the Screen. The available options on the Screen include operations such as Withdraw, deposit, balance." }, { "code": null, "e": 307, "s": 251, "text": "Following are the basic operations available in the ATM" }, { "code": null, "e": 340, "s": 307, "text": "WithdrawDepositCheck BalanceExit" }, { "code": null, "e": 349, "s": 340, "text": "Withdraw" }, { "code": null, "e": 357, "s": 349, "text": "Deposit" }, { "code": null, "e": 371, "s": 357, "text": "Check Balance" }, { "code": null, "e": 376, "s": 371, "text": "Exit" }, { "code": null, "e": 400, "s": 376, "text": "Approach to each Option" }, { "code": null, "e": 413, "s": 400, "text": "A. Withdraw:" }, { "code": null, "e": 637, "s": 413, "text": "Take the amount user desires to withdraw as input.If the balance amount greater than or equal to the withdrawal amount then Perform the transaction and give the user the desired amount.Else print Insufficient Funds message." }, { "code": null, "e": 688, "s": 637, "text": "Take the amount user desires to withdraw as input." }, { "code": null, "e": 824, "s": 688, "text": "If the balance amount greater than or equal to the withdrawal amount then Perform the transaction and give the user the desired amount." }, { "code": null, "e": 863, "s": 824, "text": "Else print Insufficient Funds message." }, { "code": null, "e": 875, "s": 863, "text": "B. Deposit:" }, { "code": null, "e": 1096, "s": 875, "text": "Take the amount user desires to deposit as input.Add the received input from the user to balance and update its value.balance = balance + deposit.Print a message on screen stating deposit transaction has been successful." }, { "code": null, "e": 1146, "s": 1096, "text": "Take the amount user desires to deposit as input." }, { "code": null, "e": 1216, "s": 1146, "text": "Add the received input from the user to balance and update its value." }, { "code": null, "e": 1245, "s": 1216, "text": "balance = balance + deposit." }, { "code": null, "e": 1320, "s": 1245, "text": "Print a message on screen stating deposit transaction has been successful." }, { "code": null, "e": 1338, "s": 1320, "text": "C. Check Balance:" }, { "code": null, "e": 1401, "s": 1338, "text": "Print a message on screen showing the value of balance amount." }, { "code": null, "e": 1410, "s": 1401, "text": "D. Exit:" }, { "code": null, "e": 1500, "s": 1410, "text": "Exit the current Transaction mode and return the user to the home page or initial screen." }, { "code": null, "e": 1551, "s": 1500, "text": "Below is the implementation of the above approach." }, { "code": null, "e": 1556, "s": 1551, "text": "Java" }, { "code": "// Java Program to Display the ATM Transactionimport java.io.*;public class GFG { // Display current balance in account public static void displayBalance(int balance) { System.out.println(\"Current Balance : \" + balance); System.out.println(); } // Withdraw amount and update the balance public static int amountWithdrawing(int balance, int withdrawAmount) { System.out.println(\"Withdrawn Operation:\"); System.out.println(\"Withdrawing Amount : \" + withdrawAmount); if (balance >= withdrawAmount) { balance = balance - withdrawAmount; System.out.println( \"Please collect your money and collect the card\"); displayBalance(balance); } else { System.out.println(\"Sorry! Insufficient Funds\"); System.out.println(); } return balance; } // Deposit amount and update the balance public static int amountDepositing(int balance, int depositAmount) { System.out.println(\"Deposit Operation:\"); System.out.println(\"Depositing Amount : \" + depositAmount); balance = balance + depositAmount; System.out.println( \"Your Money has been successfully deposited\"); displayBalance(balance); return balance; } public static void main(String args[]) { int balance = 10000; int withdrawAmount = 5000; int depositAmount = 2000; // calling display balance displayBalance(balance); // withdrawing amount balance = amountWithdrawing(balance, withdrawAmount); // depositing amount balance = amountDepositing(balance, depositAmount); }}", "e": 3405, "s": 1556, "text": null }, { "code": null, "e": 3650, "s": 3405, "text": "Current Balance : 10000\n\nWithdrawn Operation:\nWithdrawing Amount : 5000\nPlease collect your money and collect the card\nCurrent Balance : 5000\n\nDeposit Operation:\nDepositing Amount : 2000\nYour Money has been successfully deposited\nBalance : 7000" }, { "code": null, "e": 3672, "s": 3650, "text": "Time Complexity: O(1)" }, { "code": null, "e": 3696, "s": 3672, "text": "Technical Scripter 2020" }, { "code": null, "e": 3701, "s": 3696, "text": "Java" }, { "code": null, "e": 3715, "s": 3701, "text": "Java Programs" }, { "code": null, "e": 3734, "s": 3715, "text": "Technical Scripter" }, { "code": null, "e": 3739, "s": 3734, "text": "Java" } ]
How to use styles in ReactJS ?
18 Oct, 2021 React is a Javascript front-end library that is used to build single-page applications (SPA). React apps can easily be styled by assigning the styles to the className prop. There are various ways to style a react app. In this article, we are going to discuss the following four ways to style a react app. Using Inline stylesUsing CSS fileUsing CSS moduleUsing styled-components Using Inline styles Using CSS file Using CSS module Using styled-components Project Setup – We can create the React app by using the command mentioned below on the command line. npx create-react-app name_of_the_app Note: To follow along with the example please delete all the content of App.js and App.css files. Styling using Inline Styles – In order to apply the inline styles to the elements, we use the style prop. We pass an object with key as CSS properties in camelCase and value as the values that can be assigned to these CSS properties. Syntax: The syntax to assign inline styles to CSS elements is mentioned below. <div style={{backgroundColor: 'red'}}></div> Filename: App.js The content of the App.js file is mentioned in the code given below in which we have added inline styling to the React elements. App.js const App = () => { return ( <div style={{ display: "flex", alignItems: "center", justifyContent: "center", height: "100vh", backgroundImage: "linear-gradient(to right, #427ceb, #1dad6f)", }} > <h1 style={{ color: "white" }}>GeeksForGeeks</h1> </div> );}; export default App; Step to run the application: Use the following command to start the application. npm start Output: Open the browser and go to http://localhost:3000, you will see the following output. Note: For all below-given examples, the output will remain as above only. Though you can verify it at your end by pasting the content of App.js and App.css files and running the React app on your device. Styling using CSS file – To style the React elements using the CSS file, we first import the CSS file and then assign the classes contained in the CSS file to the className prop of React elements. Syntax: The syntax to assign the classes to the className prop is mentioned below. <div className="name_of_the_class"></div> Filename: App.js The content of App.js and App.css files demonstrating the use of CSS files to style React elements is mentioned below. App.js import './App.css'; const App = () => { return ( <div className='container-div'> <h1 className='heading'>GeeksForGeeks</h1> </div> );}; export default App; App.css .container-div { display: flex; align-items: center; justify-content: center; height: 100vh; background-image: linear-gradient( to right, #427ceb, #1dad6f);} .heading { color: white;} Styling using CSS module – CSS modules are a way to locally scope the content of your CSS file. We can create a CSS module file by naming our CSS file as App.modules.css and then it can be imported inside App.js file using the special syntax mentioned below. Syntax: import styles from './App.module.css'; Now we can easily assign the classes to the className properties mentioned below. <div className={styles['container-div']}> <h1 className={styles.heading}>GeeksForGeeks</h1> </div> The square bracket is used to access the class when it contains a hyphen or we can use it generally also. The dot can be used to access the class when it does not contain a hyphen. Filename: App.js The content of App.js and App.css files demonstrating the use of CSS modules to style the React element is mentioned below. App.js import styles from './App.module.css'; const App = () => { return ( <div className={styles['container-div']}> <h1 className={styles.heading}>GeeksForGeeks</h1> </div> );}; export default App; App.modules.css .container-div { display: flex; align-items: center; justify-content: center; height: 100vh; background-image: linear-gradient( to right, #427ceb, #1dad6f);} .heading { color: white;} Styling using styled-components – The styled-components is a third-party package that helps us create a new Styled component based on the React element and CSS styles provided to it. Module Installation: In order to use the styled-components you must first install it as a dependency using the following command from the command line. npm install styled-components Syntax: To create a styled component you can use the syntax mentioned below. import styled from 'styled-components'; const GeeksHeading = styled.h1` color: white; `; The code above will create a new component based on the h1 element and style it with the CSS properties passed to it. The content of the App.js file demonstrating the use of styled-components is mentioned below. App.js import styled from 'styled-components'; const PageDiv = styled.div` display: flex; align-items: center; justify-content: center; height: 100vh; background-image: linear-gradient( to right, #427ceb, #1dad6f);`; const GeeksHeading = styled.h1` color: white;`; const App = () => { return ( <PageDiv> <GeeksHeading>GeeksForGeeks</GeeksHeading> </PageDiv> );}; export default App; Picked React-Questions ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Axios in React: A Guide for Beginners ReactJS useNavigate() Hook How to do crud operations in ReactJS ? How to Use Bootstrap with React? How to install bootstrap in React.js ? Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? Remove elements from a JavaScript Array
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Oct, 2021" }, { "code": null, "e": 202, "s": 28, "text": "React is a Javascript front-end library that is used to build single-page applications (SPA). React apps can easily be styled by assigning the styles to the className prop. " }, { "code": null, "e": 335, "s": 202, "text": "There are various ways to style a react app. In this article, we are going to discuss the following four ways to style a react app. " }, { "code": null, "e": 408, "s": 335, "text": "Using Inline stylesUsing CSS fileUsing CSS moduleUsing styled-components" }, { "code": null, "e": 428, "s": 408, "text": "Using Inline styles" }, { "code": null, "e": 443, "s": 428, "text": "Using CSS file" }, { "code": null, "e": 460, "s": 443, "text": "Using CSS module" }, { "code": null, "e": 484, "s": 460, "text": "Using styled-components" }, { "code": null, "e": 586, "s": 484, "text": "Project Setup – We can create the React app by using the command mentioned below on the command line." }, { "code": null, "e": 623, "s": 586, "text": "npx create-react-app name_of_the_app" }, { "code": null, "e": 721, "s": 623, "text": "Note: To follow along with the example please delete all the content of App.js and App.css files." }, { "code": null, "e": 955, "s": 721, "text": "Styling using Inline Styles – In order to apply the inline styles to the elements, we use the style prop. We pass an object with key as CSS properties in camelCase and value as the values that can be assigned to these CSS properties." }, { "code": null, "e": 1034, "s": 955, "text": "Syntax: The syntax to assign inline styles to CSS elements is mentioned below." }, { "code": null, "e": 1079, "s": 1034, "text": "<div style={{backgroundColor: 'red'}}></div>" }, { "code": null, "e": 1226, "s": 1079, "text": "Filename: App.js The content of the App.js file is mentioned in the code given below in which we have added inline styling to the React elements. " }, { "code": null, "e": 1233, "s": 1226, "text": "App.js" }, { "code": "const App = () => { return ( <div style={{ display: \"flex\", alignItems: \"center\", justifyContent: \"center\", height: \"100vh\", backgroundImage: \"linear-gradient(to right, #427ceb, #1dad6f)\", }} > <h1 style={{ color: \"white\" }}>GeeksForGeeks</h1> </div> );}; export default App;", "e": 1581, "s": 1233, "text": null }, { "code": null, "e": 1662, "s": 1581, "text": "Step to run the application: Use the following command to start the application." }, { "code": null, "e": 1672, "s": 1662, "text": "npm start" }, { "code": null, "e": 1765, "s": 1672, "text": "Output: Open the browser and go to http://localhost:3000, you will see the following output." }, { "code": null, "e": 1969, "s": 1765, "text": "Note: For all below-given examples, the output will remain as above only. Though you can verify it at your end by pasting the content of App.js and App.css files and running the React app on your device." }, { "code": null, "e": 2167, "s": 1969, "text": "Styling using CSS file – To style the React elements using the CSS file, we first import the CSS file and then assign the classes contained in the CSS file to the className prop of React elements. " }, { "code": null, "e": 2251, "s": 2167, "text": "Syntax: The syntax to assign the classes to the className prop is mentioned below. " }, { "code": null, "e": 2293, "s": 2251, "text": "<div className=\"name_of_the_class\"></div>" }, { "code": null, "e": 2429, "s": 2293, "text": "Filename: App.js The content of App.js and App.css files demonstrating the use of CSS files to style React elements is mentioned below." }, { "code": null, "e": 2436, "s": 2429, "text": "App.js" }, { "code": "import './App.css'; const App = () => { return ( <div className='container-div'> <h1 className='heading'>GeeksForGeeks</h1> </div> );}; export default App;", "e": 2607, "s": 2436, "text": null }, { "code": null, "e": 2615, "s": 2607, "text": "App.css" }, { "code": ".container-div { display: flex; align-items: center; justify-content: center; height: 100vh; background-image: linear-gradient( to right, #427ceb, #1dad6f);} .heading { color: white;}", "e": 2827, "s": 2615, "text": null }, { "code": null, "e": 3086, "s": 2827, "text": "Styling using CSS module – CSS modules are a way to locally scope the content of your CSS file. We can create a CSS module file by naming our CSS file as App.modules.css and then it can be imported inside App.js file using the special syntax mentioned below." }, { "code": null, "e": 3094, "s": 3086, "text": "Syntax:" }, { "code": null, "e": 3133, "s": 3094, "text": "import styles from './App.module.css';" }, { "code": null, "e": 3215, "s": 3133, "text": "Now we can easily assign the classes to the className properties mentioned below." }, { "code": null, "e": 3319, "s": 3215, "text": "<div className={styles['container-div']}> \n <h1 className={styles.heading}>GeeksForGeeks</h1>\n</div>" }, { "code": null, "e": 3501, "s": 3319, "text": "The square bracket is used to access the class when it contains a hyphen or we can use it generally also. The dot can be used to access the class when it does not contain a hyphen. " }, { "code": null, "e": 3642, "s": 3501, "text": "Filename: App.js The content of App.js and App.css files demonstrating the use of CSS modules to style the React element is mentioned below." }, { "code": null, "e": 3649, "s": 3642, "text": "App.js" }, { "code": "import styles from './App.module.css'; const App = () => { return ( <div className={styles['container-div']}> <h1 className={styles.heading}>GeeksForGeeks</h1> </div> );}; export default App;", "e": 3857, "s": 3649, "text": null }, { "code": null, "e": 3873, "s": 3857, "text": "App.modules.css" }, { "code": ".container-div { display: flex; align-items: center; justify-content: center; height: 100vh; background-image: linear-gradient( to right, #427ceb, #1dad6f);} .heading { color: white;}", "e": 4085, "s": 3873, "text": null }, { "code": null, "e": 4269, "s": 4085, "text": "Styling using styled-components – The styled-components is a third-party package that helps us create a new Styled component based on the React element and CSS styles provided to it. " }, { "code": null, "e": 4421, "s": 4269, "text": "Module Installation: In order to use the styled-components you must first install it as a dependency using the following command from the command line." }, { "code": null, "e": 4451, "s": 4421, "text": "npm install styled-components" }, { "code": null, "e": 4528, "s": 4451, "text": "Syntax: To create a styled component you can use the syntax mentioned below." }, { "code": null, "e": 4619, "s": 4528, "text": "import styled from 'styled-components';\nconst GeeksHeading = styled.h1`\n color: white;\n`;" }, { "code": null, "e": 4831, "s": 4619, "text": "The code above will create a new component based on the h1 element and style it with the CSS properties passed to it. The content of the App.js file demonstrating the use of styled-components is mentioned below." }, { "code": null, "e": 4838, "s": 4831, "text": "App.js" }, { "code": "import styled from 'styled-components'; const PageDiv = styled.div` display: flex; align-items: center; justify-content: center; height: 100vh; background-image: linear-gradient( to right, #427ceb, #1dad6f);`; const GeeksHeading = styled.h1` color: white;`; const App = () => { return ( <PageDiv> <GeeksHeading>GeeksForGeeks</GeeksHeading> </PageDiv> );}; export default App;", "e": 5242, "s": 4838, "text": null }, { "code": null, "e": 5249, "s": 5242, "text": "Picked" }, { "code": null, "e": 5265, "s": 5249, "text": "React-Questions" }, { "code": null, "e": 5273, "s": 5265, "text": "ReactJS" }, { "code": null, "e": 5290, "s": 5273, "text": "Web Technologies" }, { "code": null, "e": 5388, "s": 5290, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5426, "s": 5388, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 5453, "s": 5426, "text": "ReactJS useNavigate() Hook" }, { "code": null, "e": 5492, "s": 5453, "text": "How to do crud operations in ReactJS ?" }, { "code": null, "e": 5525, "s": 5492, "text": "How to Use Bootstrap with React?" }, { "code": null, "e": 5564, "s": 5525, "text": "How to install bootstrap in React.js ?" }, { "code": null, "e": 5597, "s": 5564, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 5659, "s": 5597, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 5720, "s": 5659, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 5770, "s": 5720, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to render HTML to an image ?
21 Jun, 2020 HTML code can be converted into an image by different means such as html2canvas JavaScript library or sometimes by CSS as well it can be very helpful and useful for users who wish to share the image of the code but can’t share the exact code. The user will generate an image from the webpage and have an option to convert a particular part of the HTML page into the picture. Example 1: This is a relatively easy implementation which converts the code into an image using CSS. The below code does not involve any JavaScript in any manner. <!DOCTYPE html><html> <head> <title>HTML Code to Image</title> <style> .image { text-align: center; padding: 20px; color: white; font-size: 90px; width: 800px; height: 400px; font-family: 'Times New Roman'; background-image: linear-gradient( 140deg, #3a9c50 0%, #006b18 100%); } </style></head> <body> <div class="image"> <h4>GEEKS FOR GEEKS</h4> </div></body> </html> Output: Example 2: The example is implemented to convert the HTML code into an image, where the preview button shows the photo which is converted. The download option is given to save it on the local computer by using html2canvas JavaScript library. <!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"> </script> <script src="https://files.codepedia.info/files/uploads/iScripts/html2canvas.js"> </script> <title> How to render HTML to an image? </title></head> <body> <div id="html-content-holder" style="background-color: #F0F0F1;color: #00cc65; width: 500px; padding-left: 25px; padding-top: 10px;"> <strong>GEEKS FOR GEEKS</strong> <p style="color: #3e4b51;"> A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and ... </p> <p style="color: #3e4b51;"> A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and ... </p> </div> <input id="btn-Preview-Image" type="button" value="Preview" /> <a id="btn-Convert-Html2Image" href="#"> Download </a> <br /> <h3>Preview :</h3> <div id="previewImage"></div> <script> $(document).ready(function () { // Global variable var element = $("#html-content-holder"); var getCanvas; // Global variable $("#btn-Preview-Image").on('click', function () { html2canvas(element, { onrendered: function (canvas) { $("#previewImage").append(canvas); getCanvas = canvas; } }); }); $("#btn-Convert-Html2Image"). on('click', function () { var imgageData = getCanvas.toDataURL("image/png"); // Now browser starts downloading it // instead of just showing it var newData = imgageData.replace( /^data:image\/png/, "data:application/octet-stream"); $("#btn-Convert-Html2Image") .attr("download", "gfg.png") .attr("href", newData); }); }); </script></body> </html> Output: CSS-Misc HTML-Misc Picked CSS HTML JQuery Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a Tribute Page using HTML & CSS How to set space between the flexbox ? Build a Survey Form using HTML and CSS Design a web page using HTML and CSS Form validation using jQuery REST API (Introduction) Hide or show elements in HTML using display property How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Design a Tribute Page using HTML & CSS
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Jun, 2020" }, { "code": null, "e": 403, "s": 28, "text": "HTML code can be converted into an image by different means such as html2canvas JavaScript library or sometimes by CSS as well it can be very helpful and useful for users who wish to share the image of the code but can’t share the exact code. The user will generate an image from the webpage and have an option to convert a particular part of the HTML page into the picture." }, { "code": null, "e": 566, "s": 403, "text": "Example 1: This is a relatively easy implementation which converts the code into an image using CSS. The below code does not involve any JavaScript in any manner." }, { "code": "<!DOCTYPE html><html> <head> <title>HTML Code to Image</title> <style> .image { text-align: center; padding: 20px; color: white; font-size: 90px; width: 800px; height: 400px; font-family: 'Times New Roman'; background-image: linear-gradient( 140deg, #3a9c50 0%, #006b18 100%); } </style></head> <body> <div class=\"image\"> <h4>GEEKS FOR GEEKS</h4> </div></body> </html>", "e": 1079, "s": 566, "text": null }, { "code": null, "e": 1087, "s": 1079, "text": "Output:" }, { "code": null, "e": 1329, "s": 1087, "text": "Example 2: The example is implemented to convert the HTML code into an image, where the preview button shows the photo which is converted. The download option is given to save it on the local computer by using html2canvas JavaScript library." }, { "code": "<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js\"> </script> <script src=\"https://files.codepedia.info/files/uploads/iScripts/html2canvas.js\"> </script> <title> How to render HTML to an image? </title></head> <body> <div id=\"html-content-holder\" style=\"background-color: #F0F0F1;color: #00cc65; width: 500px; padding-left: 25px; padding-top: 10px;\"> <strong>GEEKS FOR GEEKS</strong> <p style=\"color: #3e4b51;\"> A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and ... </p> <p style=\"color: #3e4b51;\"> A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and ... </p> </div> <input id=\"btn-Preview-Image\" type=\"button\" value=\"Preview\" /> <a id=\"btn-Convert-Html2Image\" href=\"#\"> Download </a> <br /> <h3>Preview :</h3> <div id=\"previewImage\"></div> <script> $(document).ready(function () { // Global variable var element = $(\"#html-content-holder\"); var getCanvas; // Global variable $(\"#btn-Preview-Image\").on('click', function () { html2canvas(element, { onrendered: function (canvas) { $(\"#previewImage\").append(canvas); getCanvas = canvas; } }); }); $(\"#btn-Convert-Html2Image\"). on('click', function () { var imgageData = getCanvas.toDataURL(\"image/png\"); // Now browser starts downloading it // instead of just showing it var newData = imgageData.replace( /^data:image\\/png/, \"data:application/octet-stream\"); $(\"#btn-Convert-Html2Image\") .attr(\"download\", \"gfg.png\") .attr(\"href\", newData); }); }); </script></body> </html>", "e": 3680, "s": 1329, "text": null }, { "code": null, "e": 3688, "s": 3680, "text": "Output:" }, { "code": null, "e": 3697, "s": 3688, "text": "CSS-Misc" }, { "code": null, "e": 3707, "s": 3697, "text": "HTML-Misc" }, { "code": null, "e": 3714, "s": 3707, "text": "Picked" }, { "code": null, "e": 3718, "s": 3714, "text": "CSS" }, { "code": null, "e": 3723, "s": 3718, "text": "HTML" }, { "code": null, "e": 3730, "s": 3723, "text": "JQuery" }, { "code": null, "e": 3747, "s": 3730, "text": "Web Technologies" }, { "code": null, "e": 3774, "s": 3747, "text": "Web technologies Questions" }, { "code": null, "e": 3779, "s": 3774, "text": "HTML" }, { "code": null, "e": 3877, "s": 3779, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3916, "s": 3877, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 3955, "s": 3916, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 3994, "s": 3955, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 4031, "s": 3994, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 4060, "s": 4031, "text": "Form validation using jQuery" }, { "code": null, "e": 4084, "s": 4060, "text": "REST API (Introduction)" }, { "code": null, "e": 4137, "s": 4084, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 4197, "s": 4137, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 4258, "s": 4197, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Reverse a path in BST using queue
21 Jun, 2022 Given a binary search tree and a key, your task to reverse path of the binary tree.Prerequisite : Reverse path of Binary tree Examples : Input : 50 / \ 30 70 / \ / \ 20 40 60 80 k = 70 Output : Inorder before reversal : 20 30 40 50 60 70 80 Inorder after reversal : 20 30 40 70 60 50 80 Input : 8 / \ 3 10 / \ \ 1 6 14 / \ / 4 7 13 k = 13 Output : Inorder before reversal : 1 3 4 6 7 8 10 13 14 Inorder after reversal : 1 3 4 6 7 13 14 8 10 Approach : Take a queue and push all the element till that given key at the end replace node key with queue front element till root, then print inorder of the tree. Below is the implementation of above approach : C++ Java Python3 C# Javascript // C++ code to demonstrate insert// operation in binary search tree#include <bits/stdc++.h>using namespace std; struct node { int key; struct node *left, *right;}; // A utility function to// create a new BST nodestruct node* newNode(int item){ struct node* temp = new node; temp->key = item; temp->left = temp->right = NULL; return temp;} // A utility function to// do inorder traversal of BSTvoid inorder(struct node* root){ if (root != NULL) { inorder(root->left); cout << root->key << " "; inorder(root->right); }} // reverse tree path using queuevoid reversePath(struct node** node, int& key, queue<int>& q1){ /* If the tree is empty, return a new node */ if (node == NULL) return; // If the node key equal // to key then if ((*node)->key == key) { // push current node key q1.push((*node)->key); // replace first node // with last element (*node)->key = q1.front(); // remove first element q1.pop(); // return return; } // if key smaller than node key then else if (key < (*node)->key) { // push node key into queue q1.push((*node)->key); // recursive call itself reversePath(&(*node)->left, key, q1); // replace queue front to node key (*node)->key = q1.front(); // perform pop in queue q1.pop(); } // if key greater than node key then else if (key > (*node)->key) { // push node key into queue q1.push((*node)->key); // recursive call itself reversePath(&(*node)->right, key, q1); // replace queue front to node key (*node)->key = q1.front(); // perform pop in queue q1.pop(); } // return return;} /* A utility function to inserta new node with given key in BST */struct node* insert(struct node* node, int key){ /* If the tree is empty, return a new node */ if (node == NULL) return newNode(key); /* Otherwise, recur down the tree */ if (key < node->key) node->left = insert(node->left, key); else if (key > node->key) node->right = insert(node->right, key); /* return the (unchanged) node pointer */ return node;} // Driver Program to test above functionsint main(){ /* Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 */ struct node* root = NULL; queue<int> q1; // reverse path till k int k = 80; root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); cout << "Before Reverse :" << endl; // print inorder traversal of the BST inorder(root); cout << "\n"; // reverse path till k reversePath(&root, k, q1); cout << "After Reverse :" << endl; // print inorder of reverse path tree inorder(root); return 0;} // Java code to demonstrate insert// operation in binary search treeimport java.util.*;class GFG{ static class node { int key; node left, right; }; static node root = null; static Queue<Integer> q1; static int k; // A utility function to // create a new BST node static node newNode(int item) { node temp = new node(); temp.key = item; temp.left = temp.right = null; return temp; } // A utility function to // do inorder traversal of BST static void inorder(node root) { if (root != null) { inorder(root.left); System.out.print(root.key + " "); inorder(root.right); } } // reverse tree path using queue static void reversePath(node node) { /* If the tree is empty, return a new node */ if (node == null) return; // If the node key equal // to key then if ((node).key == k) { // push current node key q1.add((node).key); // replace first node // with last element (node).key = q1.peek(); // remove first element q1.remove(); // return return; } // if key smaller than node key then else if (k < (node).key) { // push node key into queue q1.add((node).key); // recursive call itself reversePath((node).left); // replace queue front to node key (node).key = q1.peek(); // perform pop in queue q1.remove(); } // if key greater than node key then else if (k > (node).key) { // push node key into queue q1.add((node).key); // recursive call itself reversePath((node).right); // replace queue front to node key (node).key = q1.peek(); // perform pop in queue q1.remove(); } // return return; } /* A utility function to insert a new node with given key in BST */ static node insert(node node, int key) { /* If the tree is empty, return a new node */ if (node == null) return newNode(key); /* Otherwise, recur down the tree */ if (key < node.key) node.left = insert(node.left, key); else if (key > node.key) node.right = insert(node.right, key); /* return the (unchanged) node pointer */ return node; } // Driver code public static void main(String[] args) { /* Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 */ q1 = new LinkedList<>(); // reverse path till k k = 80; root = insert(root, 50); root = insert(root, 30); root = insert(root, 20); root = insert(root, 40); root = insert(root, 70); root = insert(root, 60); root = insert(root, 80); System.out.print("Before Reverse :" + "\n"); // print inorder traversal of the BST inorder(root); System.out.print("\n"); // reverse path till k reversePath(root); System.out.print("After Reverse :" + "\n"); // print inorder of reverse path tree inorder(root); }} // This code is contributed by gauravrajput1 # Python3 code to demonstrate insert# operation in binary search treeclass Node: # Constructor to create a new node def __init__(self, data): self.key = data self.left = None self.right = None # A utility function to# do inorder traversal of BSTdef inorder(root): if root != None: inorder(root.left) print(root.key, end = " ") inorder(root.right) # reverse tree path using queuedef reversePath(node, key, q1): # If the tree is empty, # return a new node */ if node == None: return # If the node key equal # to key then if node.key == key: # push current node key q1.insert(0, node.key) # replace first node # with last element node.key = q1[-1] # remove first element q1.pop() # return return # if key smaller than node key then elif key < node.key: # push node key into queue q1.insert(0, node.key) # recursive call itself reversePath(node.left, key, q1) # replace queue front to node key node.key = q1[-1] # perform pop in queue q1.pop() # if key greater than node key then elif (key > node.key): # push node key into queue q1.insert(0, node.key) # recursive call itself reversePath(node.right, key, q1) # replace queue front to node key node.key = q1[-1] # perform pop in queue q1.pop() # return return # A utility function to insert#a new node with given key in BST */def insert(node, key): # If the tree is empty, # return a new node */ if node == None: return Node(key) # Otherwise, recur down the tree */ if key < node.key: node.left = insert(node.left, key) elif key > node.key: node.right = insert(node.right, key) # return the (unchanged) node pointer */ return node # Driver Codeif __name__ == '__main__': # Let us create following BST # 50 # / \ # 30 70 # / \ / \ # 20 40 60 80 */ root = None q1 = [] # reverse path till k k = 80; root = insert(root, 50) insert(root, 30) insert(root, 20) insert(root, 40) insert(root, 70) insert(root, 60) insert(root, 80) print("Before Reverse :") # print inorder traversal of the BST inorder(root) # reverse path till k reversePath(root, k, q1) print() print("After Reverse :") # print inorder of reverse path tree inorder(root) # This code is contributed by PranchalK // C# code to demonstrate insert// operation in binary search treeusing System;using System.Collections.Generic; class GFG{ public class node{ public int key; public node left, right;}; static node root = null;static Queue<int> q1;static int k; // A utility function to// create a new BST nodestatic node newNode(int item){ node temp = new node(); temp.key = item; temp.left = temp.right = null; return temp;} // A utility function to// do inorder traversal of BSTstatic void inorder(node root){ if (root != null) { inorder(root.left); Console.Write(root.key + " "); inorder(root.right); }} // Reverse tree path using queuestatic void reversePath(node node){ // If the tree is empty, // return a new node if (node == null) return; // If the node key equal // to key then if ((node).key == k) { // push current node key q1.Enqueue((node).key); // replace first node // with last element (node).key = q1.Peek(); // Remove first element q1.Dequeue(); // Return return; } // If key smaller than node key then else if (k < (node).key) { // push node key into queue q1.Enqueue((node).key); // Recursive call itself reversePath((node).left); // Replace queue front to node key (node).key = q1.Peek(); // Perform pop in queue q1.Dequeue(); } // If key greater than node key then else if (k > (node).key) { // push node key into queue q1.Enqueue((node).key); // Recursive call itself reversePath((node).right); // Replace queue front to node key (node).key = q1.Peek(); // Perform pop in queue q1.Dequeue(); } // Return return;} // A utility function to insert// a new node with given key in BSTstatic node insert(node node, int key){ // If the tree is empty, // return a new node if (node == null) return newNode(key); // Otherwise, recur down the tree if (key < node.key) node.left = insert(node.left, key); else if (key > node.key) node.right = insert(node.right, key); // Return the (unchanged) node pointer return node;} // Driver codepublic static void Main(String[] args){ /* Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 */ q1 = new Queue<int>(); // Reverse path till k k = 80; root = insert(root, 50); root = insert(root, 30); root = insert(root, 20); root = insert(root, 40); root = insert(root, 70); root = insert(root, 60); root = insert(root, 80); Console.Write("Before Reverse :" + "\n"); // Print inorder traversal of the BST inorder(root); Console.Write("\n"); // Reverse path till k reversePath(root); Console.Write("After Reverse :" + "\n"); // Print inorder of reverse path tree inorder(root);}} // This code is contributed by gauravrajput1 <script> // javascript code to demonstrate insert// operation in binary search tree class node{ constructor() { this.key = 0; this.left = null; this.right = null; }}; var root = null;var q1 = [];var k = 0; // A utility function to// create a new BST nodefunction newNode(item){ var temp = new node(); temp.key = item; temp.left = temp.right = null; return temp;} // A utility function to// do inorder traversal of BSTfunction inorder(root){ if (root != null) { inorder(root.left); document.write(root.key + " "); inorder(root.right); }} // Reverse tree path using queuefunction reversePath(node){ // If the tree is empty, // return a new node if (node == null) return; // If the node key equal // to key then if ((node).key == k) { // push current node key q1.push((node).key); // replace first node // with last element (node).key = q1[0]; // Remove first element q1.shift(); // Return return; } // If key smaller than node key then else if (k < (node).key) { // push node key into queue q1.push((node).key); // Recursive call itself reversePath((node).left); // Replace queue front to node key (node).key = q1[0]; // Perform pop in queue q1.shift(); } // If key greater than node key then else if (k > (node).key) { // push node key into queue q1.push((node).key); // Recursive call itself reversePath((node).right); // Replace queue front to node key (node).key = q1[0]; // Perform pop in queue q1.shift(); } // Return return;} // A utility function to insert// a new node with given key in BSTfunction insert(node, key){ // If the tree is empty, // return a new node if (node == null) return newNode(key); // Otherwise, recur down the tree if (key < node.key) node.left = insert(node.left, key); else if (key > node.key) node.right = insert(node.right, key); // Return the (unchanged) node pointer return node;} // Driver code /* Let us create following BST 50 / \ 30 70 / \ / \20 40 60 80 */q1 = []; // Reverse path till kk = 80;root = insert(root, 50);root = insert(root, 30);root = insert(root, 20);root = insert(root, 40);root = insert(root, 70);root = insert(root, 60);root = insert(root, 80);document.write("Before Reverse :" + "<br>"); // Print inorder traversal of the BSTinorder(root);document.write("<br>"); // Reverse path till kreversePath(root);document.write("After Reverse :" + "<br>"); // Print inorder of reverse path treeinorder(root); // This code is contributed by itsok.</script> Before Reverse : 20 30 40 50 60 70 80 After Reverse : 20 30 40 80 60 70 50 Time Complexity: O(n) Auxiliary Space: O(n) PranchalKatiyar rns111 GauravRajput1 gabaa406 itsok surinderdawra388 geekygirl2001 cpp-queue Binary Search Tree Queue Queue Binary Search Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Binary Search Tree | Set 1 (Search and Insertion) AVL Tree | Set 1 (Insertion) Binary Search Tree | Set 2 (Delete) A program to check if a binary tree is BST or not Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash) Breadth First Search or BFS for a Graph Level Order Binary Tree Traversal Queue in Python Queue Interface In Java Introduction to Data Structures
[ { "code": null, "e": 54, "s": 26, "text": "\n21 Jun, 2022" }, { "code": null, "e": 180, "s": 54, "text": "Given a binary search tree and a key, your task to reverse path of the binary tree.Prerequisite : Reverse path of Binary tree" }, { "code": null, "e": 192, "s": 180, "text": "Examples : " }, { "code": null, "e": 666, "s": 192, "text": "Input : 50\n / \\\n 30 70\n / \\ / \\\n 20 40 60 80 \nk = 70\nOutput :\nInorder before reversal :\n20 30 40 50 60 70 80 \nInorder after reversal :\n20 30 40 70 60 50 80 \n\nInput : 8\n / \\\n 3 10\n / \\ \\\n 1 6 14\n / \\ /\n 4 7 13\nk = 13\nOutput :\nInorder before reversal :\n1 3 4 6 7 8 10 13 14\nInorder after reversal :\n1 3 4 6 7 13 14 8 10" }, { "code": null, "e": 831, "s": 666, "text": "Approach : Take a queue and push all the element till that given key at the end replace node key with queue front element till root, then print inorder of the tree." }, { "code": null, "e": 881, "s": 831, "text": "Below is the implementation of above approach : " }, { "code": null, "e": 885, "s": 881, "text": "C++" }, { "code": null, "e": 890, "s": 885, "text": "Java" }, { "code": null, "e": 898, "s": 890, "text": "Python3" }, { "code": null, "e": 901, "s": 898, "text": "C#" }, { "code": null, "e": 912, "s": 901, "text": "Javascript" }, { "code": "// C++ code to demonstrate insert// operation in binary search tree#include <bits/stdc++.h>using namespace std; struct node { int key; struct node *left, *right;}; // A utility function to// create a new BST nodestruct node* newNode(int item){ struct node* temp = new node; temp->key = item; temp->left = temp->right = NULL; return temp;} // A utility function to// do inorder traversal of BSTvoid inorder(struct node* root){ if (root != NULL) { inorder(root->left); cout << root->key << \" \"; inorder(root->right); }} // reverse tree path using queuevoid reversePath(struct node** node, int& key, queue<int>& q1){ /* If the tree is empty, return a new node */ if (node == NULL) return; // If the node key equal // to key then if ((*node)->key == key) { // push current node key q1.push((*node)->key); // replace first node // with last element (*node)->key = q1.front(); // remove first element q1.pop(); // return return; } // if key smaller than node key then else if (key < (*node)->key) { // push node key into queue q1.push((*node)->key); // recursive call itself reversePath(&(*node)->left, key, q1); // replace queue front to node key (*node)->key = q1.front(); // perform pop in queue q1.pop(); } // if key greater than node key then else if (key > (*node)->key) { // push node key into queue q1.push((*node)->key); // recursive call itself reversePath(&(*node)->right, key, q1); // replace queue front to node key (*node)->key = q1.front(); // perform pop in queue q1.pop(); } // return return;} /* A utility function to inserta new node with given key in BST */struct node* insert(struct node* node, int key){ /* If the tree is empty, return a new node */ if (node == NULL) return newNode(key); /* Otherwise, recur down the tree */ if (key < node->key) node->left = insert(node->left, key); else if (key > node->key) node->right = insert(node->right, key); /* return the (unchanged) node pointer */ return node;} // Driver Program to test above functionsint main(){ /* Let us create following BST 50 / \\ 30 70 / \\ / \\ 20 40 60 80 */ struct node* root = NULL; queue<int> q1; // reverse path till k int k = 80; root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); cout << \"Before Reverse :\" << endl; // print inorder traversal of the BST inorder(root); cout << \"\\n\"; // reverse path till k reversePath(&root, k, q1); cout << \"After Reverse :\" << endl; // print inorder of reverse path tree inorder(root); return 0;}", "e": 3947, "s": 912, "text": null }, { "code": "// Java code to demonstrate insert// operation in binary search treeimport java.util.*;class GFG{ static class node { int key; node left, right; }; static node root = null; static Queue<Integer> q1; static int k; // A utility function to // create a new BST node static node newNode(int item) { node temp = new node(); temp.key = item; temp.left = temp.right = null; return temp; } // A utility function to // do inorder traversal of BST static void inorder(node root) { if (root != null) { inorder(root.left); System.out.print(root.key + \" \"); inorder(root.right); } } // reverse tree path using queue static void reversePath(node node) { /* If the tree is empty, return a new node */ if (node == null) return; // If the node key equal // to key then if ((node).key == k) { // push current node key q1.add((node).key); // replace first node // with last element (node).key = q1.peek(); // remove first element q1.remove(); // return return; } // if key smaller than node key then else if (k < (node).key) { // push node key into queue q1.add((node).key); // recursive call itself reversePath((node).left); // replace queue front to node key (node).key = q1.peek(); // perform pop in queue q1.remove(); } // if key greater than node key then else if (k > (node).key) { // push node key into queue q1.add((node).key); // recursive call itself reversePath((node).right); // replace queue front to node key (node).key = q1.peek(); // perform pop in queue q1.remove(); } // return return; } /* A utility function to insert a new node with given key in BST */ static node insert(node node, int key) { /* If the tree is empty, return a new node */ if (node == null) return newNode(key); /* Otherwise, recur down the tree */ if (key < node.key) node.left = insert(node.left, key); else if (key > node.key) node.right = insert(node.right, key); /* return the (unchanged) node pointer */ return node; } // Driver code public static void main(String[] args) { /* Let us create following BST 50 / \\ 30 70 / \\ / \\ 20 40 60 80 */ q1 = new LinkedList<>(); // reverse path till k k = 80; root = insert(root, 50); root = insert(root, 30); root = insert(root, 20); root = insert(root, 40); root = insert(root, 70); root = insert(root, 60); root = insert(root, 80); System.out.print(\"Before Reverse :\" + \"\\n\"); // print inorder traversal of the BST inorder(root); System.out.print(\"\\n\"); // reverse path till k reversePath(root); System.out.print(\"After Reverse :\" + \"\\n\"); // print inorder of reverse path tree inorder(root); }} // This code is contributed by gauravrajput1", "e": 7022, "s": 3947, "text": null }, { "code": "# Python3 code to demonstrate insert# operation in binary search treeclass Node: # Constructor to create a new node def __init__(self, data): self.key = data self.left = None self.right = None # A utility function to# do inorder traversal of BSTdef inorder(root): if root != None: inorder(root.left) print(root.key, end = \" \") inorder(root.right) # reverse tree path using queuedef reversePath(node, key, q1): # If the tree is empty, # return a new node */ if node == None: return # If the node key equal # to key then if node.key == key: # push current node key q1.insert(0, node.key) # replace first node # with last element node.key = q1[-1] # remove first element q1.pop() # return return # if key smaller than node key then elif key < node.key: # push node key into queue q1.insert(0, node.key) # recursive call itself reversePath(node.left, key, q1) # replace queue front to node key node.key = q1[-1] # perform pop in queue q1.pop() # if key greater than node key then elif (key > node.key): # push node key into queue q1.insert(0, node.key) # recursive call itself reversePath(node.right, key, q1) # replace queue front to node key node.key = q1[-1] # perform pop in queue q1.pop() # return return # A utility function to insert#a new node with given key in BST */def insert(node, key): # If the tree is empty, # return a new node */ if node == None: return Node(key) # Otherwise, recur down the tree */ if key < node.key: node.left = insert(node.left, key) elif key > node.key: node.right = insert(node.right, key) # return the (unchanged) node pointer */ return node # Driver Codeif __name__ == '__main__': # Let us create following BST # 50 # / \\ # 30 70 # / \\ / \\ # 20 40 60 80 */ root = None q1 = [] # reverse path till k k = 80; root = insert(root, 50) insert(root, 30) insert(root, 20) insert(root, 40) insert(root, 70) insert(root, 60) insert(root, 80) print(\"Before Reverse :\") # print inorder traversal of the BST inorder(root) # reverse path till k reversePath(root, k, q1) print() print(\"After Reverse :\") # print inorder of reverse path tree inorder(root) # This code is contributed by PranchalK", "e": 9678, "s": 7022, "text": null }, { "code": "// C# code to demonstrate insert// operation in binary search treeusing System;using System.Collections.Generic; class GFG{ public class node{ public int key; public node left, right;}; static node root = null;static Queue<int> q1;static int k; // A utility function to// create a new BST nodestatic node newNode(int item){ node temp = new node(); temp.key = item; temp.left = temp.right = null; return temp;} // A utility function to// do inorder traversal of BSTstatic void inorder(node root){ if (root != null) { inorder(root.left); Console.Write(root.key + \" \"); inorder(root.right); }} // Reverse tree path using queuestatic void reversePath(node node){ // If the tree is empty, // return a new node if (node == null) return; // If the node key equal // to key then if ((node).key == k) { // push current node key q1.Enqueue((node).key); // replace first node // with last element (node).key = q1.Peek(); // Remove first element q1.Dequeue(); // Return return; } // If key smaller than node key then else if (k < (node).key) { // push node key into queue q1.Enqueue((node).key); // Recursive call itself reversePath((node).left); // Replace queue front to node key (node).key = q1.Peek(); // Perform pop in queue q1.Dequeue(); } // If key greater than node key then else if (k > (node).key) { // push node key into queue q1.Enqueue((node).key); // Recursive call itself reversePath((node).right); // Replace queue front to node key (node).key = q1.Peek(); // Perform pop in queue q1.Dequeue(); } // Return return;} // A utility function to insert// a new node with given key in BSTstatic node insert(node node, int key){ // If the tree is empty, // return a new node if (node == null) return newNode(key); // Otherwise, recur down the tree if (key < node.key) node.left = insert(node.left, key); else if (key > node.key) node.right = insert(node.right, key); // Return the (unchanged) node pointer return node;} // Driver codepublic static void Main(String[] args){ /* Let us create following BST 50 / \\ 30 70 / \\ / \\ 20 40 60 80 */ q1 = new Queue<int>(); // Reverse path till k k = 80; root = insert(root, 50); root = insert(root, 30); root = insert(root, 20); root = insert(root, 40); root = insert(root, 70); root = insert(root, 60); root = insert(root, 80); Console.Write(\"Before Reverse :\" + \"\\n\"); // Print inorder traversal of the BST inorder(root); Console.Write(\"\\n\"); // Reverse path till k reversePath(root); Console.Write(\"After Reverse :\" + \"\\n\"); // Print inorder of reverse path tree inorder(root);}} // This code is contributed by gauravrajput1", "e": 12852, "s": 9678, "text": null }, { "code": "<script> // javascript code to demonstrate insert// operation in binary search tree class node{ constructor() { this.key = 0; this.left = null; this.right = null; }}; var root = null;var q1 = [];var k = 0; // A utility function to// create a new BST nodefunction newNode(item){ var temp = new node(); temp.key = item; temp.left = temp.right = null; return temp;} // A utility function to// do inorder traversal of BSTfunction inorder(root){ if (root != null) { inorder(root.left); document.write(root.key + \" \"); inorder(root.right); }} // Reverse tree path using queuefunction reversePath(node){ // If the tree is empty, // return a new node if (node == null) return; // If the node key equal // to key then if ((node).key == k) { // push current node key q1.push((node).key); // replace first node // with last element (node).key = q1[0]; // Remove first element q1.shift(); // Return return; } // If key smaller than node key then else if (k < (node).key) { // push node key into queue q1.push((node).key); // Recursive call itself reversePath((node).left); // Replace queue front to node key (node).key = q1[0]; // Perform pop in queue q1.shift(); } // If key greater than node key then else if (k > (node).key) { // push node key into queue q1.push((node).key); // Recursive call itself reversePath((node).right); // Replace queue front to node key (node).key = q1[0]; // Perform pop in queue q1.shift(); } // Return return;} // A utility function to insert// a new node with given key in BSTfunction insert(node, key){ // If the tree is empty, // return a new node if (node == null) return newNode(key); // Otherwise, recur down the tree if (key < node.key) node.left = insert(node.left, key); else if (key > node.key) node.right = insert(node.right, key); // Return the (unchanged) node pointer return node;} // Driver code /* Let us create following BST 50 / \\ 30 70 / \\ / \\20 40 60 80 */q1 = []; // Reverse path till kk = 80;root = insert(root, 50);root = insert(root, 30);root = insert(root, 20);root = insert(root, 40);root = insert(root, 70);root = insert(root, 60);root = insert(root, 80);document.write(\"Before Reverse :\" + \"<br>\"); // Print inorder traversal of the BSTinorder(root);document.write(\"<br>\"); // Reverse path till kreversePath(root);document.write(\"After Reverse :\" + \"<br>\"); // Print inorder of reverse path treeinorder(root); // This code is contributed by itsok.</script>", "e": 15785, "s": 12852, "text": null }, { "code": null, "e": 15861, "s": 15785, "text": "Before Reverse :\n20 30 40 50 60 70 80 \nAfter Reverse :\n20 30 40 80 60 70 50" }, { "code": null, "e": 15885, "s": 15863, "text": "Time Complexity: O(n)" }, { "code": null, "e": 15907, "s": 15885, "text": "Auxiliary Space: O(n)" }, { "code": null, "e": 15923, "s": 15907, "text": "PranchalKatiyar" }, { "code": null, "e": 15930, "s": 15923, "text": "rns111" }, { "code": null, "e": 15944, "s": 15930, "text": "GauravRajput1" }, { "code": null, "e": 15953, "s": 15944, "text": "gabaa406" }, { "code": null, "e": 15959, "s": 15953, "text": "itsok" }, { "code": null, "e": 15976, "s": 15959, "text": "surinderdawra388" }, { "code": null, "e": 15990, "s": 15976, "text": "geekygirl2001" }, { "code": null, "e": 16000, "s": 15990, "text": "cpp-queue" }, { "code": null, "e": 16019, "s": 16000, "text": "Binary Search Tree" }, { "code": null, "e": 16025, "s": 16019, "text": "Queue" }, { "code": null, "e": 16031, "s": 16025, "text": "Queue" }, { "code": null, "e": 16050, "s": 16031, "text": "Binary Search Tree" }, { "code": null, "e": 16148, "s": 16050, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 16198, "s": 16148, "text": "Binary Search Tree | Set 1 (Search and Insertion)" }, { "code": null, "e": 16227, "s": 16198, "text": "AVL Tree | Set 1 (Insertion)" }, { "code": null, "e": 16263, "s": 16227, "text": "Binary Search Tree | Set 2 (Delete)" }, { "code": null, "e": 16313, "s": 16263, "text": "A program to check if a binary tree is BST or not" }, { "code": null, "e": 16383, "s": 16313, "text": "Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)" }, { "code": null, "e": 16423, "s": 16383, "text": "Breadth First Search or BFS for a Graph" }, { "code": null, "e": 16457, "s": 16423, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 16473, "s": 16457, "text": "Queue in Python" }, { "code": null, "e": 16497, "s": 16473, "text": "Queue Interface In Java" } ]
HTML | <button> formmethod Attribute
14 Feb, 2022 The HTML button formmethod Attribute is used to specify the HTTP method used to send data while submitting the form. There are two kinds of HTTP methods, which are GET and POST. this Attribute is only used with the Button type=”submit” Syntax: <button type="submit" formmethod="get|post"> Attribute values: GET: In the GET method, after the submission of the form, the form values will be visible in the address bar of the new browser tab. It has a limited size of about 3000 characters. It is only useful for non-secure data not for sensitive information. It has a default value. POST: In the post method, after the submission of the form, the form values will not be visible in the address bar of the new browser tab as it was visible in the GET method. It appends form data inside the body of the HTTP request. It has no size limitation. This method does not support bookmark the result. Example: This Example illustrate the use of formmethod Attribute in Button Element. <!DOCTYPE html><html> <head> <title> Button Formmethod attribute </title></head> <body style="text-align: center"> <h1 style="color: green"> GeeksforGeeks </h1> <h4> HTML Button Formmethod Attribute </h4> <form action="#" method="post" enctype="multipart/form-data"> First name: <input type="text" name="fname"> <br><br> Last name: <input type="text" name="lname"> <br><br> Address: <input type="text" name="Address"> <br><br> <button type="submit" formmethod="GET"> submit using GET </button> <br> <br> <button type="submit" formenctype="text/plan" formmethod="POST"> submit using POST </button> </form></body> </html> Output:Supported Browsers: The browsers supported by HTML <button> Formmethod attribute are listed below: Google Chrome 9.0 Internet Explorer 10.0 Firefox 4.0 Opera 10.6 Safari 5.1 hritikbhatnagar2182 HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) Design a Tribute Page using HTML & CSS Build a Survey Form using HTML and CSS Angular File Upload Design a web page using HTML and CSS Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Feb, 2022" }, { "code": null, "e": 264, "s": 28, "text": "The HTML button formmethod Attribute is used to specify the HTTP method used to send data while submitting the form. There are two kinds of HTTP methods, which are GET and POST. this Attribute is only used with the Button type=”submit”" }, { "code": null, "e": 272, "s": 264, "text": "Syntax:" }, { "code": null, "e": 317, "s": 272, "text": "<button type=\"submit\" formmethod=\"get|post\">" }, { "code": null, "e": 335, "s": 317, "text": "Attribute values:" }, { "code": null, "e": 609, "s": 335, "text": "GET: In the GET method, after the submission of the form, the form values will be visible in the address bar of the new browser tab. It has a limited size of about 3000 characters. It is only useful for non-secure data not for sensitive information. It has a default value." }, { "code": null, "e": 919, "s": 609, "text": "POST: In the post method, after the submission of the form, the form values will not be visible in the address bar of the new browser tab as it was visible in the GET method. It appends form data inside the body of the HTTP request. It has no size limitation. This method does not support bookmark the result." }, { "code": null, "e": 1003, "s": 919, "text": "Example: This Example illustrate the use of formmethod Attribute in Button Element." }, { "code": "<!DOCTYPE html><html> <head> <title> Button Formmethod attribute </title></head> <body style=\"text-align: center\"> <h1 style=\"color: green\"> GeeksforGeeks </h1> <h4> HTML Button Formmethod Attribute </h4> <form action=\"#\" method=\"post\" enctype=\"multipart/form-data\"> First name: <input type=\"text\" name=\"fname\"> <br><br> Last name: <input type=\"text\" name=\"lname\"> <br><br> Address: <input type=\"text\" name=\"Address\"> <br><br> <button type=\"submit\" formmethod=\"GET\"> submit using GET </button> <br> <br> <button type=\"submit\" formenctype=\"text/plan\" formmethod=\"POST\"> submit using POST </button> </form></body> </html>", "e": 1816, "s": 1003, "text": null }, { "code": null, "e": 1922, "s": 1816, "text": "Output:Supported Browsers: The browsers supported by HTML <button> Formmethod attribute are listed below:" }, { "code": null, "e": 1940, "s": 1922, "text": "Google Chrome 9.0" }, { "code": null, "e": 1963, "s": 1940, "text": "Internet Explorer 10.0" }, { "code": null, "e": 1975, "s": 1963, "text": "Firefox 4.0" }, { "code": null, "e": 1986, "s": 1975, "text": "Opera 10.6" }, { "code": null, "e": 1997, "s": 1986, "text": "Safari 5.1" }, { "code": null, "e": 2017, "s": 1997, "text": "hritikbhatnagar2182" }, { "code": null, "e": 2033, "s": 2017, "text": "HTML-Attributes" }, { "code": null, "e": 2038, "s": 2033, "text": "HTML" }, { "code": null, "e": 2055, "s": 2038, "text": "Web Technologies" }, { "code": null, "e": 2060, "s": 2055, "text": "HTML" }, { "code": null, "e": 2158, "s": 2060, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2182, "s": 2158, "text": "REST API (Introduction)" }, { "code": null, "e": 2221, "s": 2182, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 2260, "s": 2221, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 2280, "s": 2260, "text": "Angular File Upload" }, { "code": null, "e": 2317, "s": 2280, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 2350, "s": 2317, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2411, "s": 2350, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2454, "s": 2411, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 2526, "s": 2454, "text": "Differences between Functional Components and Class Components in React" } ]
Regression using k-Nearest Neighbors in R Programming
28 Jul, 2020 Machine learning is a subset of Artificial Intelligence that provides a machine with the ability to learn automatically without being explicitly programmed. The machine in such cases improves from the experience without human intervention and adjusts actions accordingly. It is primarily of 3 types: Supervised machine learning Unsupervised machine learning Reinforcement Learning The K-nearest neighbor algorithm creates an imaginary boundary to classify the data. When new data points are added for prediction, the algorithm adds that point to the nearest of the boundary line. It follows the principle of β€œBirds of a feather flock together.” This algorithm can easily be implemented in the R language. Select K, the number of neighbors.Calculate the Euclidean distance of the K number of neighbors.Take the K nearest neighbors as per the calculated Euclidean distance.Count the number of data points in each category among these K neighbors.The new data point is assigned to the category for which the number of the neighbor is maximum. Select K, the number of neighbors. Calculate the Euclidean distance of the K number of neighbors. Take the K nearest neighbors as per the calculated Euclidean distance. Count the number of data points in each category among these K neighbors. The new data point is assigned to the category for which the number of the neighbor is maximum. The Dataset: A sample population of 400 people shared their age, gender, and salary with a product company, and if they bought the product or not(0 means no, 1 means yes). Download the dataset Advertisement.csv R # Importing the datasetdataset = read.csv('Advertisement.csv')head(dataset, 10) Output: R # Encoding the target# feature as factordataset$Purchased = factor(dataset$Purchased, levels = c(0, 1)) # Splitting the dataset into # the Training set and Test set# install.packages('caTools')library(caTools)set.seed(123)split = sample.split(dataset$Purchased, SplitRatio = 0.75)training_set = subset(dataset, split == TRUE)test_set = subset(dataset, split == FALSE) # Feature Scalingtraining_set[-3] = scale(training_set[-3])test_set[-3] = scale(test_set[-3]) # Fitting K-NN to the Training set # and Predicting the Test set resultslibrary(class)y_pred = knn(train = training_set[, -3], test = test_set[, -3], cl = training_set[, 3], k = 5, prob = TRUE) # Making the Confusion Matrixcm = table(test_set[, 3], y_pred) The training set contains 300 entries. The test set contains 100 entries. Confusion matrix result: [[64][4] [3][29]] Visualizing the Training Data: R # Visualising the Training set results# Install ElemStatLearn if not present # in the packages using(without hashtag)# install.packages('ElemStatLearn')library(ElemStatLearn)set = training_set #Building a grid of Age Column(X1)# and Estimated Salary(X2) ColumnX1 = seq(min(set[, 1]) - 1, max(set[, 1]) + 1, by = 0.01)X2 = seq(min(set[, 2]) - 1, max(set[, 2]) + 1, by = 0.01)grid_set = expand.grid(X1, X2) # Give name to the columns of matrixcolnames(grid_set) = c('Age', 'EstimatedSalary') # Predicting the values and plotting# them to grid and labelling the axesy_grid = knn(train = training_set[, -3], test = grid_set, cl = training_set[, 3], k = 5)plot(set[, -3], main = 'K-NN (Training set)', xlab = 'Age', ylab = 'Estimated Salary', xlim = range(X1), ylim = range(X2))contour(X1, X2, matrix(as.numeric(y_grid), length(X1), length(X2)), add = TRUE)points(grid_set, pch = '.', col = ifelse(y_grid == 1, 'springgreen3', 'tomato'))points(set, pch = 21, bg = ifelse(set[, 3] == 1, 'green4', 'red3')) Output: Visualizing the Test Data: R # Visualising the Test set resultslibrary(ElemStatLearn)set = test_set # Building a grid of Age Column(X1)# and Estimated Salary(X2) ColumnX1 = seq(min(set[, 1]) - 1, max(set[, 1]) + 1, by = 0.01)X2 = seq(min(set[, 2]) - 1, max(set[, 2]) + 1, by = 0.01)grid_set = expand.grid(X1, X2) # Give name to the columns of matrixcolnames(grid_set) = c('Age', 'EstimatedSalary') # Predicting the values and plotting # them to grid and labelling the axesy_grid = knn(train = training_set[, -3], test = grid_set, cl = training_set[, 3], k = 5)plot(set[, -3], main = 'K-NN (Test set)', xlab = 'Age', ylab = 'Estimated Salary', xlim = range(X1), ylim = range(X2))contour(X1, X2, matrix(as.numeric(y_grid), length(X1), length(X2)), add = TRUE)points(grid_set, pch = '.', col = ifelse(y_grid == 1, 'springgreen3', 'tomato'))points(set, pch = 21, bg = ifelse(set[, 3] == 1, 'green4', 'red3')) Output: There is no training period.KNN is an instance-based learning algorithm, hence a lazy learner.KNN does not derive any discriminative function from the training table, also there is no training period.KNN stores the training dataset and uses it to make real-time predictions.New data can be added seamlessly and it will not impact the accuracy of the algorithm as there is no training needed for the newly added data.There are only two parameters required to implement the KNN algorithm i.e. the value of K and the Euclidean distance function. There is no training period.KNN is an instance-based learning algorithm, hence a lazy learner.KNN does not derive any discriminative function from the training table, also there is no training period.KNN stores the training dataset and uses it to make real-time predictions. KNN is an instance-based learning algorithm, hence a lazy learner. KNN does not derive any discriminative function from the training table, also there is no training period. KNN stores the training dataset and uses it to make real-time predictions. New data can be added seamlessly and it will not impact the accuracy of the algorithm as there is no training needed for the newly added data. There are only two parameters required to implement the KNN algorithm i.e. the value of K and the Euclidean distance function. The cost of calculating the distance between each existing point and the new point is huge in the new data set which reduces the performance of the algorithm.It becomes difficult for the algorithm to calculate the distance in each dimension because the algorithm does not work well with high dimensional data i.e. a data with a large number of features,There is a need for feature scaling (standardization and normalization) before applying the KNN algorithm to any dataset else KNN may generate wrong predictions.KNN is sensitive to noise in the data. The cost of calculating the distance between each existing point and the new point is huge in the new data set which reduces the performance of the algorithm. It becomes difficult for the algorithm to calculate the distance in each dimension because the algorithm does not work well with high dimensional data i.e. a data with a large number of features, There is a need for feature scaling (standardization and normalization) before applying the KNN algorithm to any dataset else KNN may generate wrong predictions. KNN is sensitive to noise in the data. Picked R Data-science R Machine-Learning R regression 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 How to Split Column Into Multiple Columns in R DataFrame? Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to filter R DataFrame by values in a column? Logistic Regression in R Programming R - if statement Replace Specific Characters in String in R How to import an Excel File into R ? Joining of Dataframes in R Programming
[ { "code": null, "e": 54, "s": 26, "text": "\n28 Jul, 2020" }, { "code": null, "e": 354, "s": 54, "text": "Machine learning is a subset of Artificial Intelligence that provides a machine with the ability to learn automatically without being explicitly programmed. The machine in such cases improves from the experience without human intervention and adjusts actions accordingly. It is primarily of 3 types:" }, { "code": null, "e": 382, "s": 354, "text": "Supervised machine learning" }, { "code": null, "e": 412, "s": 382, "text": "Unsupervised machine learning" }, { "code": null, "e": 435, "s": 412, "text": "Reinforcement Learning" }, { "code": null, "e": 759, "s": 435, "text": "The K-nearest neighbor algorithm creates an imaginary boundary to classify the data. When new data points are added for prediction, the algorithm adds that point to the nearest of the boundary line. It follows the principle of β€œBirds of a feather flock together.” This algorithm can easily be implemented in the R language." }, { "code": null, "e": 1094, "s": 759, "text": "Select K, the number of neighbors.Calculate the Euclidean distance of the K number of neighbors.Take the K nearest neighbors as per the calculated Euclidean distance.Count the number of data points in each category among these K neighbors.The new data point is assigned to the category for which the number of the neighbor is maximum." }, { "code": null, "e": 1129, "s": 1094, "text": "Select K, the number of neighbors." }, { "code": null, "e": 1192, "s": 1129, "text": "Calculate the Euclidean distance of the K number of neighbors." }, { "code": null, "e": 1263, "s": 1192, "text": "Take the K nearest neighbors as per the calculated Euclidean distance." }, { "code": null, "e": 1337, "s": 1263, "text": "Count the number of data points in each category among these K neighbors." }, { "code": null, "e": 1433, "s": 1337, "text": "The new data point is assigned to the category for which the number of the neighbor is maximum." }, { "code": null, "e": 1644, "s": 1433, "text": "The Dataset: A sample population of 400 people shared their age, gender, and salary with a product company, and if they bought the product or not(0 means no, 1 means yes). Download the dataset Advertisement.csv" }, { "code": null, "e": 1646, "s": 1644, "text": "R" }, { "code": "# Importing the datasetdataset = read.csv('Advertisement.csv')head(dataset, 10)", "e": 1726, "s": 1646, "text": null }, { "code": null, "e": 1734, "s": 1726, "text": "Output:" }, { "code": null, "e": 1736, "s": 1734, "text": "R" }, { "code": "# Encoding the target# feature as factordataset$Purchased = factor(dataset$Purchased, levels = c(0, 1)) # Splitting the dataset into # the Training set and Test set# install.packages('caTools')library(caTools)set.seed(123)split = sample.split(dataset$Purchased, SplitRatio = 0.75)training_set = subset(dataset, split == TRUE)test_set = subset(dataset, split == FALSE) # Feature Scalingtraining_set[-3] = scale(training_set[-3])test_set[-3] = scale(test_set[-3]) # Fitting K-NN to the Training set # and Predicting the Test set resultslibrary(class)y_pred = knn(train = training_set[, -3], test = test_set[, -3], cl = training_set[, 3], k = 5, prob = TRUE) # Making the Confusion Matrixcm = table(test_set[, 3], y_pred)", "e": 2594, "s": 1736, "text": null }, { "code": null, "e": 2633, "s": 2594, "text": "The training set contains 300 entries." }, { "code": null, "e": 2668, "s": 2633, "text": "The test set contains 100 entries." }, { "code": null, "e": 2715, "s": 2668, "text": "Confusion matrix result:\n[[64][4]\n [3][29]]\n\n" }, { "code": null, "e": 2747, "s": 2715, "text": "Visualizing the Training Data: " }, { "code": null, "e": 2749, "s": 2747, "text": "R" }, { "code": "# Visualising the Training set results# Install ElemStatLearn if not present # in the packages using(without hashtag)# install.packages('ElemStatLearn')library(ElemStatLearn)set = training_set #Building a grid of Age Column(X1)# and Estimated Salary(X2) ColumnX1 = seq(min(set[, 1]) - 1, max(set[, 1]) + 1, by = 0.01)X2 = seq(min(set[, 2]) - 1, max(set[, 2]) + 1, by = 0.01)grid_set = expand.grid(X1, X2) # Give name to the columns of matrixcolnames(grid_set) = c('Age', 'EstimatedSalary') # Predicting the values and plotting# them to grid and labelling the axesy_grid = knn(train = training_set[, -3], test = grid_set, cl = training_set[, 3], k = 5)plot(set[, -3], main = 'K-NN (Training set)', xlab = 'Age', ylab = 'Estimated Salary', xlim = range(X1), ylim = range(X2))contour(X1, X2, matrix(as.numeric(y_grid), length(X1), length(X2)), add = TRUE)points(grid_set, pch = '.', col = ifelse(y_grid == 1, 'springgreen3', 'tomato'))points(set, pch = 21, bg = ifelse(set[, 3] == 1, 'green4', 'red3'))", "e": 3961, "s": 2749, "text": null }, { "code": null, "e": 3969, "s": 3961, "text": "Output:" }, { "code": null, "e": 3996, "s": 3969, "text": "Visualizing the Test Data:" }, { "code": null, "e": 3998, "s": 3996, "text": "R" }, { "code": "# Visualising the Test set resultslibrary(ElemStatLearn)set = test_set # Building a grid of Age Column(X1)# and Estimated Salary(X2) ColumnX1 = seq(min(set[, 1]) - 1, max(set[, 1]) + 1, by = 0.01)X2 = seq(min(set[, 2]) - 1, max(set[, 2]) + 1, by = 0.01)grid_set = expand.grid(X1, X2) # Give name to the columns of matrixcolnames(grid_set) = c('Age', 'EstimatedSalary') # Predicting the values and plotting # them to grid and labelling the axesy_grid = knn(train = training_set[, -3], test = grid_set, cl = training_set[, 3], k = 5)plot(set[, -3], main = 'K-NN (Test set)', xlab = 'Age', ylab = 'Estimated Salary', xlim = range(X1), ylim = range(X2))contour(X1, X2, matrix(as.numeric(y_grid), length(X1), length(X2)), add = TRUE)points(grid_set, pch = '.', col = ifelse(y_grid == 1, 'springgreen3', 'tomato'))points(set, pch = 21, bg = ifelse(set[, 3] == 1, 'green4', 'red3'))", "e": 5056, "s": 3998, "text": null }, { "code": null, "e": 5064, "s": 5056, "text": "Output:" }, { "code": null, "e": 5607, "s": 5064, "text": "There is no training period.KNN is an instance-based learning algorithm, hence a lazy learner.KNN does not derive any discriminative function from the training table, also there is no training period.KNN stores the training dataset and uses it to make real-time predictions.New data can be added seamlessly and it will not impact the accuracy of the algorithm as there is no training needed for the newly added data.There are only two parameters required to implement the KNN algorithm i.e. the value of K and the Euclidean distance function." }, { "code": null, "e": 5882, "s": 5607, "text": "There is no training period.KNN is an instance-based learning algorithm, hence a lazy learner.KNN does not derive any discriminative function from the training table, also there is no training period.KNN stores the training dataset and uses it to make real-time predictions." }, { "code": null, "e": 5949, "s": 5882, "text": "KNN is an instance-based learning algorithm, hence a lazy learner." }, { "code": null, "e": 6056, "s": 5949, "text": "KNN does not derive any discriminative function from the training table, also there is no training period." }, { "code": null, "e": 6131, "s": 6056, "text": "KNN stores the training dataset and uses it to make real-time predictions." }, { "code": null, "e": 6274, "s": 6131, "text": "New data can be added seamlessly and it will not impact the accuracy of the algorithm as there is no training needed for the newly added data." }, { "code": null, "e": 6401, "s": 6274, "text": "There are only two parameters required to implement the KNN algorithm i.e. the value of K and the Euclidean distance function." }, { "code": null, "e": 6954, "s": 6401, "text": "The cost of calculating the distance between each existing point and the new point is huge in the new data set which reduces the performance of the algorithm.It becomes difficult for the algorithm to calculate the distance in each dimension because the algorithm does not work well with high dimensional data i.e. a data with a large number of features,There is a need for feature scaling (standardization and normalization) before applying the KNN algorithm to any dataset else KNN may generate wrong predictions.KNN is sensitive to noise in the data." }, { "code": null, "e": 7113, "s": 6954, "text": "The cost of calculating the distance between each existing point and the new point is huge in the new data set which reduces the performance of the algorithm." }, { "code": null, "e": 7309, "s": 7113, "text": "It becomes difficult for the algorithm to calculate the distance in each dimension because the algorithm does not work well with high dimensional data i.e. a data with a large number of features," }, { "code": null, "e": 7471, "s": 7309, "text": "There is a need for feature scaling (standardization and normalization) before applying the KNN algorithm to any dataset else KNN may generate wrong predictions." }, { "code": null, "e": 7510, "s": 7471, "text": "KNN is sensitive to noise in the data." }, { "code": null, "e": 7517, "s": 7510, "text": "Picked" }, { "code": null, "e": 7532, "s": 7517, "text": "R Data-science" }, { "code": null, "e": 7551, "s": 7532, "text": "R Machine-Learning" }, { "code": null, "e": 7564, "s": 7551, "text": "R regression" }, { "code": null, "e": 7575, "s": 7564, "text": "R Language" }, { "code": null, "e": 7673, "s": 7575, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7725, "s": 7673, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 7783, "s": 7725, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 7818, "s": 7783, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 7856, "s": 7818, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 7905, "s": 7856, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 7942, "s": 7905, "text": "Logistic Regression in R Programming" }, { "code": null, "e": 7959, "s": 7942, "text": "R - if statement" }, { "code": null, "e": 8002, "s": 7959, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 8039, "s": 8002, "text": "How to import an Excel File into R ?" } ]
Heap’s Algorithm for generating permutations
15 Jun, 2021 Heap’s algorithm is used to generate all permutations of n objects. The idea is to generate each permutation from the previous permutation by choosing a pair of elements to interchange, without disturbing the other n-2 elements. Following is the illustration of generating all the permutations of n given numbers.Example: Input: 1 2 3 Output: 1 2 3 2 1 3 3 1 2 1 3 2 2 3 1 3 2 1 Algorithm: The algorithm generates (n-1)! permutations of the first n-1 elements, adjoining the last element to each of these. This will generate all of the permutations that end with the last element.If n is odd, swap the first and last element and if n is even, then swap the ith element (i is the counter starting from 0) and the last element and repeat the above algorithm till i is less than n.In each iteration, the algorithm will produce all the permutations that end with the current last element. The algorithm generates (n-1)! permutations of the first n-1 elements, adjoining the last element to each of these. This will generate all of the permutations that end with the last element. If n is odd, swap the first and last element and if n is even, then swap the ith element (i is the counter starting from 0) and the last element and repeat the above algorithm till i is less than n. In each iteration, the algorithm will produce all the permutations that end with the current last element. Implementation: C++ Java Python3 C# Javascript // C++ program to print all permutations using// Heap's algorithm#include <bits/stdc++.h>using namespace std; // Prints the arrayvoid printArr(int a[], int n){ for (int i = 0; i < n; i++) cout << a[i] << " "; printf("\n");} // Generating permutation using Heap Algorithmvoid heapPermutation(int a[], int size, int n){ // if size becomes 1 then prints the obtained // permutation if (size == 1) { printArr(a, n); return; } for (int i = 0; i < size; i++) { heapPermutation(a, size - 1, n); // if size is odd, swap 0th i.e (first) and // (size-1)th i.e (last) element if (size % 2 == 1) swap(a[0], a[size - 1]); // If size is even, swap ith and // (size-1)th i.e (last) element else swap(a[i], a[size - 1]); }} // Driver codeint main(){ int a[] = { 1, 2, 3 }; int n = sizeof a / sizeof a[0]; heapPermutation(a, n, n); return 0;} // Java program to print all permutations using// Heap's algorithmclass HeapAlgo { // Prints the array void printArr(int a[], int n) { for (int i = 0; i < n; i++) System.out.print(a[i] + " "); System.out.println(); } // Generating permutation using Heap Algorithm void heapPermutation(int a[], int size, int n) { // if size becomes 1 then prints the obtained // permutation if (size == 1) printArr(a, n); for (int i = 0; i < size; i++) { heapPermutation(a, size - 1, n); // if size is odd, swap 0th i.e (first) and // (size-1)th i.e (last) element if (size % 2 == 1) { int temp = a[0]; a[0] = a[size - 1]; a[size - 1] = temp; } // If size is even, swap ith // and (size-1)th i.e last element else { int temp = a[i]; a[i] = a[size - 1]; a[size - 1] = temp; } } } // Driver code public static void main(String args[]) { HeapAlgo obj = new HeapAlgo(); int a[] = { 1, 2, 3 }; obj.heapPermutation(a, a.length, a.length); }} // This code has been contributed by Amit Khandelwal. # Python program to print all permutations using# Heap's algorithm # Generating permutation using Heap Algorithmdef heapPermutation(a, size): # if size becomes 1 then prints the obtained # permutation if size == 1: print(a) return for i in range(size): heapPermutation(a, size-1) # if size is odd, swap 0th i.e (first) # and (size-1)th i.e (last) element # else If size is even, swap ith # and (size-1)th i.e (last) element if size & 1: a[0], a[size-1] = a[size-1], a[0] else: a[i], a[size-1] = a[size-1], a[i] # Driver codea = [1, 2, 3]n = len(a)heapPermutation(a, n) # This code is contributed by ankush_953# This code was cleaned up to by more pythonic by glubs9 // C# program to print all permutations using// Heap's algorithmusing System; public class GFG { // Prints the array static void printArr(int[] a, int n) { for (int i = 0; i < n; i++) Console.Write(a[i] + " "); Console.WriteLine(); } // Generating permutation using Heap Algorithm static void heapPermutation(int[] a, int size, int n) { // if size becomes 1 then prints the obtained // permutation if (size == 1) printArr(a, n); for (int i = 0; i < size; i++) { heapPermutation(a, size - 1, n); // if size is odd, swap 0th i.e (first) and // (size-1)th i.e (last) element if (size % 2 == 1) { int temp = a[0]; a[0] = a[size - 1]; a[size - 1] = temp; } // If size is even, swap ith and // (size-1)th i.e (last) element else { int temp = a[i]; a[i] = a[size - 1]; a[size - 1] = temp; } } } // Driver code public static void Main() { int[] a = { 1, 2, 3 }; heapPermutation(a, a.Length, a.Length); }} /* This Java code is contributed by 29AjayKumar*/ <script> // JavaScript program to print all permutations using// Heap's algorithm // Prints the arrayfunction printArr(a,n){ document.write(a.join(" ")+"<br>"); } // Generating permutation using Heap Algorithmfunction heapPermutation(a,size,n){ // if size becomes 1 then prints the obtained // permutation if (size == 1) printArr(a, n); for (let i = 0; i < size; i++) { heapPermutation(a, size - 1, n); // if size is odd, swap 0th i.e (first) and // (size-1)th i.e (last) element if (size % 2 == 1) { let temp = a[0]; a[0] = a[size - 1]; a[size - 1] = temp; } // If size is even, swap ith // and (size-1)th i.e last element else { let temp = a[i]; a[i] = a[size - 1]; a[size - 1] = temp; } }} // Driver codelet a=[1, 2, 3];heapPermutation(a, a.length, a.length); // This code is contributed by rag2127 </script> Output: 1 2 3 2 1 3 3 1 2 1 3 2 2 3 1 3 2 1 References: 1. β€œhttps://en.wikipedia.org/wiki/Heap%27s_algorithm#cite_note-3This article is contributed by Rahul Agrawal .If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. 29AjayKumar sanskar27jain ankush_953 bhargavbhatiya jontefry rag2127 permutation Combinatorial permutation Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count of subsets with sum equal to X Find the K-th Permutation Sequence of first N natural numbers Count Derangements (Permutation such that no element appears in its original position) Find the Number of Permutations that satisfy the given condition in an array Stack Permutations (Check if an array is stack permutation of other) Lexicographic rank of a string Python program to get all subsets of given size of a set Number of unique pairs in an array Find all distinct subsets of a given set using BitMasking Approach Probability of getting K heads in N coin tosses
[ { "code": null, "e": 52, "s": 24, "text": "\n15 Jun, 2021" }, { "code": null, "e": 375, "s": 52, "text": "Heap’s algorithm is used to generate all permutations of n objects. The idea is to generate each permutation from the previous permutation by choosing a pair of elements to interchange, without disturbing the other n-2 elements. Following is the illustration of generating all the permutations of n given numbers.Example: " }, { "code": null, "e": 472, "s": 375, "text": "Input: 1 2 3\nOutput: 1 2 3\n 2 1 3\n 3 1 2\n 1 3 2\n 2 3 1\n 3 2 1" }, { "code": null, "e": 484, "s": 472, "text": "Algorithm: " }, { "code": null, "e": 979, "s": 484, "text": "The algorithm generates (n-1)! permutations of the first n-1 elements, adjoining the last element to each of these. This will generate all of the permutations that end with the last element.If n is odd, swap the first and last element and if n is even, then swap the ith element (i is the counter starting from 0) and the last element and repeat the above algorithm till i is less than n.In each iteration, the algorithm will produce all the permutations that end with the current last element." }, { "code": null, "e": 1170, "s": 979, "text": "The algorithm generates (n-1)! permutations of the first n-1 elements, adjoining the last element to each of these. This will generate all of the permutations that end with the last element." }, { "code": null, "e": 1369, "s": 1170, "text": "If n is odd, swap the first and last element and if n is even, then swap the ith element (i is the counter starting from 0) and the last element and repeat the above algorithm till i is less than n." }, { "code": null, "e": 1476, "s": 1369, "text": "In each iteration, the algorithm will produce all the permutations that end with the current last element." }, { "code": null, "e": 1494, "s": 1476, "text": "Implementation: " }, { "code": null, "e": 1498, "s": 1494, "text": "C++" }, { "code": null, "e": 1503, "s": 1498, "text": "Java" }, { "code": null, "e": 1511, "s": 1503, "text": "Python3" }, { "code": null, "e": 1514, "s": 1511, "text": "C#" }, { "code": null, "e": 1525, "s": 1514, "text": "Javascript" }, { "code": "// C++ program to print all permutations using// Heap's algorithm#include <bits/stdc++.h>using namespace std; // Prints the arrayvoid printArr(int a[], int n){ for (int i = 0; i < n; i++) cout << a[i] << \" \"; printf(\"\\n\");} // Generating permutation using Heap Algorithmvoid heapPermutation(int a[], int size, int n){ // if size becomes 1 then prints the obtained // permutation if (size == 1) { printArr(a, n); return; } for (int i = 0; i < size; i++) { heapPermutation(a, size - 1, n); // if size is odd, swap 0th i.e (first) and // (size-1)th i.e (last) element if (size % 2 == 1) swap(a[0], a[size - 1]); // If size is even, swap ith and // (size-1)th i.e (last) element else swap(a[i], a[size - 1]); }} // Driver codeint main(){ int a[] = { 1, 2, 3 }; int n = sizeof a / sizeof a[0]; heapPermutation(a, n, n); return 0;}", "e": 2482, "s": 1525, "text": null }, { "code": "// Java program to print all permutations using// Heap's algorithmclass HeapAlgo { // Prints the array void printArr(int a[], int n) { for (int i = 0; i < n; i++) System.out.print(a[i] + \" \"); System.out.println(); } // Generating permutation using Heap Algorithm void heapPermutation(int a[], int size, int n) { // if size becomes 1 then prints the obtained // permutation if (size == 1) printArr(a, n); for (int i = 0; i < size; i++) { heapPermutation(a, size - 1, n); // if size is odd, swap 0th i.e (first) and // (size-1)th i.e (last) element if (size % 2 == 1) { int temp = a[0]; a[0] = a[size - 1]; a[size - 1] = temp; } // If size is even, swap ith // and (size-1)th i.e last element else { int temp = a[i]; a[i] = a[size - 1]; a[size - 1] = temp; } } } // Driver code public static void main(String args[]) { HeapAlgo obj = new HeapAlgo(); int a[] = { 1, 2, 3 }; obj.heapPermutation(a, a.length, a.length); }} // This code has been contributed by Amit Khandelwal.", "e": 3777, "s": 2482, "text": null }, { "code": "# Python program to print all permutations using# Heap's algorithm # Generating permutation using Heap Algorithmdef heapPermutation(a, size): # if size becomes 1 then prints the obtained # permutation if size == 1: print(a) return for i in range(size): heapPermutation(a, size-1) # if size is odd, swap 0th i.e (first) # and (size-1)th i.e (last) element # else If size is even, swap ith # and (size-1)th i.e (last) element if size & 1: a[0], a[size-1] = a[size-1], a[0] else: a[i], a[size-1] = a[size-1], a[i] # Driver codea = [1, 2, 3]n = len(a)heapPermutation(a, n) # This code is contributed by ankush_953# This code was cleaned up to by more pythonic by glubs9", "e": 4544, "s": 3777, "text": null }, { "code": "// C# program to print all permutations using// Heap's algorithmusing System; public class GFG { // Prints the array static void printArr(int[] a, int n) { for (int i = 0; i < n; i++) Console.Write(a[i] + \" \"); Console.WriteLine(); } // Generating permutation using Heap Algorithm static void heapPermutation(int[] a, int size, int n) { // if size becomes 1 then prints the obtained // permutation if (size == 1) printArr(a, n); for (int i = 0; i < size; i++) { heapPermutation(a, size - 1, n); // if size is odd, swap 0th i.e (first) and // (size-1)th i.e (last) element if (size % 2 == 1) { int temp = a[0]; a[0] = a[size - 1]; a[size - 1] = temp; } // If size is even, swap ith and // (size-1)th i.e (last) element else { int temp = a[i]; a[i] = a[size - 1]; a[size - 1] = temp; } } } // Driver code public static void Main() { int[] a = { 1, 2, 3 }; heapPermutation(a, a.Length, a.Length); }} /* This Java code is contributed by 29AjayKumar*/", "e": 5807, "s": 4544, "text": null }, { "code": "<script> // JavaScript program to print all permutations using// Heap's algorithm // Prints the arrayfunction printArr(a,n){ document.write(a.join(\" \")+\"<br>\"); } // Generating permutation using Heap Algorithmfunction heapPermutation(a,size,n){ // if size becomes 1 then prints the obtained // permutation if (size == 1) printArr(a, n); for (let i = 0; i < size; i++) { heapPermutation(a, size - 1, n); // if size is odd, swap 0th i.e (first) and // (size-1)th i.e (last) element if (size % 2 == 1) { let temp = a[0]; a[0] = a[size - 1]; a[size - 1] = temp; } // If size is even, swap ith // and (size-1)th i.e last element else { let temp = a[i]; a[i] = a[size - 1]; a[size - 1] = temp; } }} // Driver codelet a=[1, 2, 3];heapPermutation(a, a.length, a.length); // This code is contributed by rag2127 </script>", "e": 6868, "s": 5807, "text": null }, { "code": null, "e": 6877, "s": 6868, "text": "Output: " }, { "code": null, "e": 6913, "s": 6877, "text": "1 2 3\n2 1 3\n3 1 2\n1 3 2\n2 3 1\n3 2 1" }, { "code": null, "e": 7286, "s": 6913, "text": "References: 1. β€œhttps://en.wikipedia.org/wiki/Heap%27s_algorithm#cite_note-3This article is contributed by Rahul Agrawal .If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 7298, "s": 7286, "text": "29AjayKumar" }, { "code": null, "e": 7312, "s": 7298, "text": "sanskar27jain" }, { "code": null, "e": 7323, "s": 7312, "text": "ankush_953" }, { "code": null, "e": 7338, "s": 7323, "text": "bhargavbhatiya" }, { "code": null, "e": 7347, "s": 7338, "text": "jontefry" }, { "code": null, "e": 7355, "s": 7347, "text": "rag2127" }, { "code": null, "e": 7367, "s": 7355, "text": "permutation" }, { "code": null, "e": 7381, "s": 7367, "text": "Combinatorial" }, { "code": null, "e": 7393, "s": 7381, "text": "permutation" }, { "code": null, "e": 7407, "s": 7393, "text": "Combinatorial" }, { "code": null, "e": 7505, "s": 7407, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7542, "s": 7505, "text": "Count of subsets with sum equal to X" }, { "code": null, "e": 7604, "s": 7542, "text": "Find the K-th Permutation Sequence of first N natural numbers" }, { "code": null, "e": 7691, "s": 7604, "text": "Count Derangements (Permutation such that no element appears in its original position)" }, { "code": null, "e": 7768, "s": 7691, "text": "Find the Number of Permutations that satisfy the given condition in an array" }, { "code": null, "e": 7837, "s": 7768, "text": "Stack Permutations (Check if an array is stack permutation of other)" }, { "code": null, "e": 7868, "s": 7837, "text": "Lexicographic rank of a string" }, { "code": null, "e": 7925, "s": 7868, "text": "Python program to get all subsets of given size of a set" }, { "code": null, "e": 7960, "s": 7925, "text": "Number of unique pairs in an array" }, { "code": null, "e": 8027, "s": 7960, "text": "Find all distinct subsets of a given set using BitMasking Approach" } ]
Teaching Learning based Optimization (TLBO)
12 Apr, 2021 The process of finding optimal values for the specific parameters of a given system to fulfill all design requirements while considering the lowest possible cost is referred to as an optimization. Optimization problems can be found in all fields of science. In general Optimization problem can be written as, optimize subject to, where are the objectives, while and are the equality and inequality constraints, respectively. In the case when N=1, it is called single-objective optimization. When Nβ‰₯2, it becomes a multi-objective optimization problem whose solution strategy is different from those for a single objective. This article mainly concerns single-objective optimization problems. Many scholars and researchers have developed several meta heuristics to address complex/unsolved optimization problems. Example: Particle Swarm Optimization, Grey wolf optimization, Ant colony Optimization, Genetic Algorithms, Cuckoo search algorithm etc. This article aims to introduce a novel meta-heuristic optimization technique called Teaching Learning Based Optimization (TLBO). Teaching learning-based optimization (TLBO) is a population-based meta-heuristic optimization technique that simulates the environment of a classroom to optimize a given objective function and it was proposed by R.V. Rao et al. in 2011. In a classroom, the teacher puts his hard work and makes all the learners of a class educated. Then the learners interact with themselves to further modify and improve their gained knowledge. This algorithm consists of two phases: 1) Teacher phase All the students learn from teacher and gain knowledge 2) Learner phase Students interact among themselves to share knowledge with each other Data structure to store students of class Figure1: Data structure to store students Data structure to store ith student of the class Figure2: Data structure to store ith student 1) Teaching phase Student with minimum fitness value is considered as teacher Xmean is used in this phase, where Xmean is the mean of all the students in the class New solution generation equation :Xnew = X + r*(Xteacher – TF*Xmean) ( 1)where TF is the teaching factor and is either 1 or 2 (chosen randomly) Xnew = X + r*(Xteacher – TF*Xmean) ( 1) where TF is the teaching factor and is either 1 or 2 (chosen randomly) If Xnew is better than X. Then replace X with Xnew 2) Learner phase Xpartner: A randomly chosen fellow student from class Xpartner is chosen to interact and exchange knowledge New solution generation equationLet fitness of Xparter is Fpartner and that of X is FIf(F < Fpartner ) ( 2)Xnew = X + r*(X – Xpartner )ElseXnew = X – r*(X – Xpartner) Let fitness of Xparter is Fpartner and that of X is F If(F < Fpartner ) ( 2)Xnew = X + r*(X – Xpartner ) Xnew = X + r*(X – Xpartner ) ElseXnew = X – r*(X – Xpartner) Xnew = X – r*(X – Xpartner) d. IF Xnew is better than X. Then replace X with Xnew Parameters of problem:Number of dimensions (d)Lower bound (minx)Upper bound (maxx) Number of dimensions (d) Lower bound (minx) Upper bound (maxx) Hyperparameters of the algorithm:Number of particles (N)Maximum number of iterations (max_iter) Number of particles (N) Maximum number of iterations (max_iter) Step1: Randomly initialize Class of N students Xi ( i=1, 2, ..., n) Step2: Compute fitness value of all the students Step3: For Iter in range(max_iter): # loop max_iter times For i in range(N): # for each student # Teaching phase----------- Xteacher = student with least fitness value Xmean = mean of all the students TF ( teaching factor) = either 1 or 2 ( randomly chosen ) Xnew = class[i].position + r*(Xteacher - TF*Xmean) # if Xnew < minx OR Xnew > maxx then clip it Xnew = min(Xnew, minx) Xnew = max(Xnew, maxx) # compute fitness of new solution fnew = fitness(Xnew) # greedy selection strategy if(fnew < class[i].fitness) class[i].position = Xnew class[i].fitness = fnew # Learning phase------------ Xpartner = randomly chosen student from class if(class[i].fitness < Xpartner.fitness): Xnew = class[i].position + r*(class[i].position - Xpartner) else Xnew = class[i].position - r*(class[i].position - Xpartner) # if Xnew < minx OR Xnew > maxx then clip it Xnew = min(Xnew, minx) Xnew = max(Xnew, maxx) # compute fitness of new solution fnew = fitness(Xnew) # greedy selection strategy if(fnew < class[i].fitness) class[i].position = Xnew class[i].fitness = fnew End-for End -for Step 4: Return best student from class Machine Learning Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Recurrent Neural Network ML | Monte Carlo Tree Search (MCTS) Markov Decision Process Support Vector Machine Algorithm DBSCAN Clustering in ML | Density based clustering Normalization vs Standardization Bagging vs Boosting in Machine Learning Types of Environments in AI Principal Component Analysis with Python Intuition of Adam Optimizer
[ { "code": null, "e": 52, "s": 24, "text": "\n12 Apr, 2021" }, { "code": null, "e": 310, "s": 52, "text": "The process of finding optimal values for the specific parameters of a given system to fulfill all design requirements while considering the lowest possible cost is referred to as an optimization. Optimization problems can be found in all fields of science." }, { "code": null, "e": 363, "s": 310, "text": "In general Optimization problem can be written as, " }, { "code": null, "e": 373, "s": 363, "text": "optimize " }, { "code": null, "e": 387, "s": 373, "text": "subject to, " }, { "code": null, "e": 794, "s": 429, "text": "where are the objectives, while and are the equality and inequality constraints, respectively. In the case when N=1, it is called single-objective optimization. When Nβ‰₯2, it becomes a multi-objective optimization problem whose solution strategy is different from those for a single objective. This article mainly concerns single-objective optimization problems." }, { "code": null, "e": 1052, "s": 794, "text": "Many scholars and researchers have developed several meta heuristics to address complex/unsolved optimization problems. Example: Particle Swarm Optimization, Grey wolf optimization, Ant colony Optimization, Genetic Algorithms, Cuckoo search algorithm etc. " }, { "code": null, "e": 1181, "s": 1052, "text": "This article aims to introduce a novel meta-heuristic optimization technique called Teaching Learning Based Optimization (TLBO)." }, { "code": null, "e": 1418, "s": 1181, "text": "Teaching learning-based optimization (TLBO) is a population-based meta-heuristic optimization technique that simulates the environment of a classroom to optimize a given objective function and it was proposed by R.V. Rao et al. in 2011." }, { "code": null, "e": 1614, "s": 1418, "text": " In a classroom, the teacher puts his hard work and makes all the learners of a class educated. Then the learners interact with themselves to further modify and improve their gained knowledge." }, { "code": null, "e": 1655, "s": 1614, "text": "This algorithm consists of two phases: " }, { "code": null, "e": 1672, "s": 1655, "text": "1) Teacher phase" }, { "code": null, "e": 1727, "s": 1672, "text": "All the students learn from teacher and gain knowledge" }, { "code": null, "e": 1746, "s": 1727, "text": "2) Learner phase " }, { "code": null, "e": 1818, "s": 1746, "text": "Students interact among themselves to share knowledge with each other " }, { "code": null, "e": 1860, "s": 1818, "text": "Data structure to store students of class" }, { "code": null, "e": 1902, "s": 1860, "text": "Figure1: Data structure to store students" }, { "code": null, "e": 1951, "s": 1902, "text": "Data structure to store ith student of the class" }, { "code": null, "e": 1996, "s": 1951, "text": "Figure2: Data structure to store ith student" }, { "code": null, "e": 2014, "s": 1996, "text": "1) Teaching phase" }, { "code": null, "e": 2074, "s": 2014, "text": "Student with minimum fitness value is considered as teacher" }, { "code": null, "e": 2160, "s": 2074, "text": "Xmean is used in this phase, where Xmean is the mean of all the students in the class" }, { "code": null, "e": 2326, "s": 2160, "text": "New solution generation equation :Xnew = X + r*(Xteacher – TF*Xmean) ( 1)where TF is the teaching factor and is either 1 or 2 (chosen randomly)" }, { "code": null, "e": 2388, "s": 2326, "text": "Xnew = X + r*(Xteacher – TF*Xmean) ( 1)" }, { "code": null, "e": 2459, "s": 2388, "text": "where TF is the teaching factor and is either 1 or 2 (chosen randomly)" }, { "code": null, "e": 2510, "s": 2459, "text": "If Xnew is better than X. Then replace X with Xnew" }, { "code": null, "e": 2527, "s": 2510, "text": "2) Learner phase" }, { "code": null, "e": 2581, "s": 2527, "text": "Xpartner: A randomly chosen fellow student from class" }, { "code": null, "e": 2635, "s": 2581, "text": "Xpartner is chosen to interact and exchange knowledge" }, { "code": null, "e": 2862, "s": 2635, "text": "New solution generation equationLet fitness of Xparter is Fpartner and that of X is FIf(F < Fpartner ) ( 2)Xnew = X + r*(X – Xpartner )ElseXnew = X – r*(X – Xpartner)" }, { "code": null, "e": 2916, "s": 2862, "text": "Let fitness of Xparter is Fpartner and that of X is F" }, { "code": null, "e": 3027, "s": 2916, "text": "If(F < Fpartner ) ( 2)Xnew = X + r*(X – Xpartner )" }, { "code": null, "e": 3056, "s": 3027, "text": "Xnew = X + r*(X – Xpartner )" }, { "code": null, "e": 3088, "s": 3056, "text": "ElseXnew = X – r*(X – Xpartner)" }, { "code": null, "e": 3116, "s": 3088, "text": "Xnew = X – r*(X – Xpartner)" }, { "code": null, "e": 3170, "s": 3116, "text": "d. IF Xnew is better than X. Then replace X with Xnew" }, { "code": null, "e": 3253, "s": 3170, "text": "Parameters of problem:Number of dimensions (d)Lower bound (minx)Upper bound (maxx)" }, { "code": null, "e": 3278, "s": 3253, "text": "Number of dimensions (d)" }, { "code": null, "e": 3297, "s": 3278, "text": "Lower bound (minx)" }, { "code": null, "e": 3316, "s": 3297, "text": "Upper bound (maxx)" }, { "code": null, "e": 3412, "s": 3316, "text": "Hyperparameters of the algorithm:Number of particles (N)Maximum number of iterations (max_iter)" }, { "code": null, "e": 3436, "s": 3412, "text": "Number of particles (N)" }, { "code": null, "e": 3476, "s": 3436, "text": "Maximum number of iterations (max_iter)" }, { "code": null, "e": 5539, "s": 3476, "text": "Step1: Randomly initialize Class of N students Xi ( i=1, 2, ..., n)\nStep2: Compute fitness value of all the students\nStep3: For Iter in range(max_iter): # loop max_iter times \n For i in range(N): # for each student\n # Teaching phase-----------\n Xteacher = student with least fitness value\n Xmean = mean of all the students\n TF ( teaching factor) = either 1 or 2 ( randomly chosen ) \n Xnew = class[i].position + r*(Xteacher - TF*Xmean)\n \n # if Xnew < minx OR Xnew > maxx then clip it\n Xnew = min(Xnew, minx)\n Xnew = max(Xnew, maxx)\n \n # compute fitness of new solution\n fnew = fitness(Xnew)\n \n # greedy selection strategy\n if(fnew < class[i].fitness)\n class[i].position = Xnew\n class[i].fitness = fnew\n \n # Learning phase------------\n Xpartner = randomly chosen student from class\n \n if(class[i].fitness < Xpartner.fitness):\n Xnew = class[i].position + r*(class[i].position - Xpartner)\n else\n Xnew = class[i].position - r*(class[i].position - Xpartner)\n \n # if Xnew < minx OR Xnew > maxx then clip it\n Xnew = min(Xnew, minx)\n Xnew = max(Xnew, maxx)\n \n # compute fitness of new solution\n fnew = fitness(Xnew)\n \n # greedy selection strategy\n if(fnew < class[i].fitness)\n class[i].position = Xnew\n class[i].fitness = fnew \n End-for\n End -for\nStep 4: Return best student from class" }, { "code": null, "e": 5556, "s": 5539, "text": "Machine Learning" }, { "code": null, "e": 5573, "s": 5556, "text": "Machine Learning" }, { "code": null, "e": 5671, "s": 5573, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5712, "s": 5671, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 5748, "s": 5712, "text": "ML | Monte Carlo Tree Search (MCTS)" }, { "code": null, "e": 5772, "s": 5748, "text": "Markov Decision Process" }, { "code": null, "e": 5805, "s": 5772, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 5856, "s": 5805, "text": "DBSCAN Clustering in ML | Density based clustering" }, { "code": null, "e": 5889, "s": 5856, "text": "Normalization vs Standardization" }, { "code": null, "e": 5929, "s": 5889, "text": "Bagging vs Boosting in Machine Learning" }, { "code": null, "e": 5957, "s": 5929, "text": "Types of Environments in AI" }, { "code": null, "e": 5998, "s": 5957, "text": "Principal Component Analysis with Python" } ]
Puzzle | Minimum distance for Lizard
19 Apr, 2021 A lizard is present on one corner of cube, It wants to reach diagonally opposite corner of cube. You have to calculate minimum distance lizard has to cover to reach its destination.Note : Lizard can’t fly, it moves along the wall.You are given a representing side of cube.you have to calculate minimum distance lizard has to travel. Examples: Input : 5 Output :11.1803 Input :2 Output :4.47214 As we have to calculate the minimum distance from one corner to another diagonally opposite corner. if lizard able to fly then the shortest distance will be length of diagonal. But it can’t. So, to calculate minimum distance, just open the cube, as describe in diagram. Let us suppose, lizard is initially at point E.and it has to reach at point A(as A is diagonally opposite to E).Now we have to find AE. Just use Pythagoras theorem, As AC=a CE=CD+DE=2a C++ Java Python3 C# PHP Javascript // CPP program to find minimum distance to be travlled// by lizard.#include <bits/stdc++.h>#define ll long long intusing namespace std;int main(){ // side of cube ll a = 5; // understand from diagram ll AC = a; // understand from diagram ll CE = 2 * a; // minimum distance double shortestDistace = sqrt(AC * AC + CE * CE); cout << shortestDistace << endl; return 0;} //Java program to find minimum//distance to be travelled by lizardimport java.util.*; class solution{public static void main(String arr[]){ // side of the cube int a = 5; // understand from diagram int AC = a; // understand from diagram int CE = 2 * a; // minimum distance double shortestDistace = Math.sqrt(AC * AC + CE * CE); System.out.println(shortestDistace);}} # Python3 program to find minimum# distance to be travelled by lizard import math #side of cubeif __name__=='__main__': a = 5 #understand from diagram AC = a #understand from diagram CE = 2 * a #minimum distance shortestDistace = math.sqrt(AC * AC + CE * CE) print(shortestDistace) #this code is Contributed by Shashank_Sharma // C# program to find minimum// distance to be travelled by lizardusing System; class GFG{public static void Main(){ // side of the cube int a = 5; // understand from diagram int AC = a; // understand from diagram int CE = 2 * a; // minimum distance double shortestDistace = Math.Sqrt(AC * AC + CE * CE); Console.Write(shortestDistace);}} // This code is contributed by ita_c <?php// PHP program to find minimum distance// to be travlled by lizard. // side of cube$a = 5; // understand from diagram$AC = $a; // understand from diagram$CE = 2 * $a; // minimum distance$shortestDistance = (double)(sqrt($AC * $AC + $CE * $CE)); echo $shortestDistance . "\n"; // This code is contributed// by Akanksha Rai?> <script> // Javascript program to find minimum distance to be travlled// by lizard. // side of cubevar a = 5; // understand from diagramvar AC = a; // understand from diagramvar CE = 2 * a; // minimum distancevar shortestDistace = Math.sqrt(AC * AC + CE * CE); document.write( shortestDistace.toFixed(4)); </script> 11.1803 Shashank_Sharma SURENDRA_GANGWAR ukasp Akanksha_Rai itsok Geometric Puzzles Geometric Puzzles Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Optimum location of point to minimize total distance Check whether a given point lies inside a triangle or not Program for Point of Intersection of Two Lines Window to Viewport Transformation in Computer Graphics with Implementation Given n line segments, find if any two segments intersect SDE SHEET - A Complete Guide for SDE Preparation Puzzle 1 | (How to Measure 45 minutes using two identical wires?) Algorithm to solve Rubik's Cube Puzzle 2 | (Find ages of daughters) Puzzle 3 | (Calculate total distance travelled by bee)
[ { "code": null, "e": 52, "s": 24, "text": "\n19 Apr, 2021" }, { "code": null, "e": 397, "s": 52, "text": "A lizard is present on one corner of cube, It wants to reach diagonally opposite corner of cube. You have to calculate minimum distance lizard has to cover to reach its destination.Note : Lizard can’t fly, it moves along the wall.You are given a representing side of cube.you have to calculate minimum distance lizard has to travel. Examples: " }, { "code": null, "e": 449, "s": 397, "text": "Input : 5\nOutput :11.1803\n\nInput :2\nOutput :4.47214" }, { "code": null, "e": 644, "s": 451, "text": "As we have to calculate the minimum distance from one corner to another diagonally opposite corner. if lizard able to fly then the shortest distance will be length of diagonal. But it can’t. " }, { "code": null, "e": 909, "s": 644, "text": "So, to calculate minimum distance, just open the cube, as describe in diagram. Let us suppose, lizard is initially at point E.and it has to reach at point A(as A is diagonally opposite to E).Now we have to find AE. Just use Pythagoras theorem, As AC=a CE=CD+DE=2a " }, { "code": null, "e": 920, "s": 916, "text": "C++" }, { "code": null, "e": 925, "s": 920, "text": "Java" }, { "code": null, "e": 933, "s": 925, "text": "Python3" }, { "code": null, "e": 936, "s": 933, "text": "C#" }, { "code": null, "e": 940, "s": 936, "text": "PHP" }, { "code": null, "e": 951, "s": 940, "text": "Javascript" }, { "code": "// CPP program to find minimum distance to be travlled// by lizard.#include <bits/stdc++.h>#define ll long long intusing namespace std;int main(){ // side of cube ll a = 5; // understand from diagram ll AC = a; // understand from diagram ll CE = 2 * a; // minimum distance double shortestDistace = sqrt(AC * AC + CE * CE); cout << shortestDistace << endl; return 0;}", "e": 1352, "s": 951, "text": null }, { "code": "//Java program to find minimum//distance to be travelled by lizardimport java.util.*; class solution{public static void main(String arr[]){ // side of the cube int a = 5; // understand from diagram int AC = a; // understand from diagram int CE = 2 * a; // minimum distance double shortestDistace = Math.sqrt(AC * AC + CE * CE); System.out.println(shortestDistace);}}", "e": 1750, "s": 1352, "text": null }, { "code": "# Python3 program to find minimum# distance to be travelled by lizard import math #side of cubeif __name__=='__main__': a = 5 #understand from diagram AC = a #understand from diagram CE = 2 * a #minimum distance shortestDistace = math.sqrt(AC * AC + CE * CE) print(shortestDistace) #this code is Contributed by Shashank_Sharma", "e": 2093, "s": 1750, "text": null }, { "code": "// C# program to find minimum// distance to be travelled by lizardusing System; class GFG{public static void Main(){ // side of the cube int a = 5; // understand from diagram int AC = a; // understand from diagram int CE = 2 * a; // minimum distance double shortestDistace = Math.Sqrt(AC * AC + CE * CE); Console.Write(shortestDistace);}} // This code is contributed by ita_c", "e": 2500, "s": 2093, "text": null }, { "code": "<?php// PHP program to find minimum distance// to be travlled by lizard. // side of cube$a = 5; // understand from diagram$AC = $a; // understand from diagram$CE = 2 * $a; // minimum distance$shortestDistance = (double)(sqrt($AC * $AC + $CE * $CE)); echo $shortestDistance . \"\\n\"; // This code is contributed// by Akanksha Rai?>", "e": 2862, "s": 2500, "text": null }, { "code": "<script> // Javascript program to find minimum distance to be travlled// by lizard. // side of cubevar a = 5; // understand from diagramvar AC = a; // understand from diagramvar CE = 2 * a; // minimum distancevar shortestDistace = Math.sqrt(AC * AC + CE * CE); document.write( shortestDistace.toFixed(4)); </script>", "e": 3178, "s": 2862, "text": null }, { "code": null, "e": 3186, "s": 3178, "text": "11.1803" }, { "code": null, "e": 3204, "s": 3188, "text": "Shashank_Sharma" }, { "code": null, "e": 3221, "s": 3204, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 3227, "s": 3221, "text": "ukasp" }, { "code": null, "e": 3240, "s": 3227, "text": "Akanksha_Rai" }, { "code": null, "e": 3246, "s": 3240, "text": "itsok" }, { "code": null, "e": 3256, "s": 3246, "text": "Geometric" }, { "code": null, "e": 3264, "s": 3256, "text": "Puzzles" }, { "code": null, "e": 3274, "s": 3264, "text": "Geometric" }, { "code": null, "e": 3282, "s": 3274, "text": "Puzzles" }, { "code": null, "e": 3380, "s": 3282, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3433, "s": 3380, "text": "Optimum location of point to minimize total distance" }, { "code": null, "e": 3491, "s": 3433, "text": "Check whether a given point lies inside a triangle or not" }, { "code": null, "e": 3538, "s": 3491, "text": "Program for Point of Intersection of Two Lines" }, { "code": null, "e": 3613, "s": 3538, "text": "Window to Viewport Transformation in Computer Graphics with Implementation" }, { "code": null, "e": 3671, "s": 3613, "text": "Given n line segments, find if any two segments intersect" }, { "code": null, "e": 3720, "s": 3671, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 3786, "s": 3720, "text": "Puzzle 1 | (How to Measure 45 minutes using two identical wires?)" }, { "code": null, "e": 3818, "s": 3786, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 3854, "s": 3818, "text": "Puzzle 2 | (Find ages of daughters)" } ]
Fix β€œExecution failed app:processDebugResources” in Android Studio
23 Jun, 2021 Resources are the files and static content that the application’s code uses, such as animations, images, layouts, and string values. These files stored in the resource directory can be referenced from the application’s code but when a non-existent reference is called android throws an β€œExecution failed app:processDebugResources” error. In this article, we will be discussing 5 different methods to solve this error. Method 1: Change the version of buildTools Method 2: Run Gradle with –stacktrace Method 3: Add required libraries Method 4: Clean project Method 5: Invalid Caches/Restart If the android SDK corresponding to the buildToolsVersion used in the app is not installed, make sure to change the buildToolsVersion to the latest Android SDK Build Tools version already installed. Step 1: Navigate to Tools > SDK Manager Step 2: Navigate to SDK Tools & click β€œShow Package Details” and look for the latest version of the Android SDK Build Tools Version installed. Step 3: Navigate to app > Gradle Script > build.gradle (Module:app) and make sure the buildToolsVersion is the same as the latest version of the build tools already installed. Step 4: Sync the project to solve the issue. (a) Make sure not to give any references to a non-existent string in the resources. A reference to a string not defined in the strings.xml file can cause this error. (b) Make sure to follow the naming conventions in the layout, strings, color, attrs, styles, drawable, and various directories in the resources folder. To find out what’s exactly causing the error, we can use the –stacktrace command. Step 1: Navigate to File > Settings. Step 2: Navigate to Build, Execution, Deployment > Compiler and add β€œβ€“stacktrace” in Command-line Options. Step 3: Click Apply and OK. If you are running a 64-bit version of Ubuntu, install the 32-bit libraries with the following command: sudo apt-get install libc6:i386 libncurses5:i386 libstdc++6:i386 lib32z1 libbz2-1.0:i386 If you are running 64-bit Fedora, install the libraries with the following command: sudo yum install zlib.i686 ncurses-libs.i686 bzip2-libs.i686 To find out how to add these libraries, please visit the official website https://developer.android.com/studio/install A clean project removes the build artifacts and recompiles the project again, thereby solving the issue. Navigate to Build > Clean Project The only way to solve some errors is to clean out the cached data which can be done by Navigating to File > Invalidate Caches/Restart > Invalidate Cache and Restart. Android-Studio Picked Android Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Add Views Dynamically and Store Data in Arraylist in Android? Android SDK and it's Components Flutter - Custom Bottom Navigation Bar How to Communicate Between Fragments in Android? Retrofit with Kotlin Coroutine in Android How to Post Data to API using Retrofit in Android? Flutter - Stack Widget Introduction to Android Development Activity Lifecycle in Android with Demo App Fragment Lifecycle in Android
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Jun, 2021" }, { "code": null, "e": 446, "s": 28, "text": "Resources are the files and static content that the application’s code uses, such as animations, images, layouts, and string values. These files stored in the resource directory can be referenced from the application’s code but when a non-existent reference is called android throws an β€œExecution failed app:processDebugResources” error. In this article, we will be discussing 5 different methods to solve this error." }, { "code": null, "e": 489, "s": 446, "text": "Method 1: Change the version of buildTools" }, { "code": null, "e": 527, "s": 489, "text": "Method 2: Run Gradle with –stacktrace" }, { "code": null, "e": 560, "s": 527, "text": "Method 3: Add required libraries" }, { "code": null, "e": 584, "s": 560, "text": "Method 4: Clean project" }, { "code": null, "e": 617, "s": 584, "text": "Method 5: Invalid Caches/Restart" }, { "code": null, "e": 816, "s": 617, "text": "If the android SDK corresponding to the buildToolsVersion used in the app is not installed, make sure to change the buildToolsVersion to the latest Android SDK Build Tools version already installed." }, { "code": null, "e": 856, "s": 816, "text": "Step 1: Navigate to Tools > SDK Manager" }, { "code": null, "e": 999, "s": 856, "text": "Step 2: Navigate to SDK Tools & click β€œShow Package Details” and look for the latest version of the Android SDK Build Tools Version installed." }, { "code": null, "e": 1175, "s": 999, "text": "Step 3: Navigate to app > Gradle Script > build.gradle (Module:app) and make sure the buildToolsVersion is the same as the latest version of the build tools already installed." }, { "code": null, "e": 1221, "s": 1175, "text": "Step 4: Sync the project to solve the issue. " }, { "code": null, "e": 1387, "s": 1221, "text": "(a) Make sure not to give any references to a non-existent string in the resources. A reference to a string not defined in the strings.xml file can cause this error." }, { "code": null, "e": 1539, "s": 1387, "text": "(b) Make sure to follow the naming conventions in the layout, strings, color, attrs, styles, drawable, and various directories in the resources folder." }, { "code": null, "e": 1622, "s": 1539, "text": "To find out what’s exactly causing the error, we can use the –stacktrace command. " }, { "code": null, "e": 1659, "s": 1622, "text": "Step 1: Navigate to File > Settings." }, { "code": null, "e": 1766, "s": 1659, "text": "Step 2: Navigate to Build, Execution, Deployment > Compiler and add β€œβ€“stacktrace” in Command-line Options." }, { "code": null, "e": 1795, "s": 1766, "text": "Step 3: Click Apply and OK. " }, { "code": null, "e": 1899, "s": 1795, "text": "If you are running a 64-bit version of Ubuntu, install the 32-bit libraries with the following command:" }, { "code": null, "e": 1988, "s": 1899, "text": "sudo apt-get install libc6:i386 libncurses5:i386 libstdc++6:i386 lib32z1 libbz2-1.0:i386" }, { "code": null, "e": 2073, "s": 1988, "text": "If you are running 64-bit Fedora, install the libraries with the following command: " }, { "code": null, "e": 2134, "s": 2073, "text": "sudo yum install zlib.i686 ncurses-libs.i686 bzip2-libs.i686" }, { "code": null, "e": 2253, "s": 2134, "text": "To find out how to add these libraries, please visit the official website https://developer.android.com/studio/install" }, { "code": null, "e": 2392, "s": 2253, "text": "A clean project removes the build artifacts and recompiles the project again, thereby solving the issue. Navigate to Build > Clean Project" }, { "code": null, "e": 2559, "s": 2392, "text": "The only way to solve some errors is to clean out the cached data which can be done by Navigating to File > Invalidate Caches/Restart > Invalidate Cache and Restart. " }, { "code": null, "e": 2574, "s": 2559, "text": "Android-Studio" }, { "code": null, "e": 2581, "s": 2574, "text": "Picked" }, { "code": null, "e": 2589, "s": 2581, "text": "Android" }, { "code": null, "e": 2597, "s": 2589, "text": "Android" }, { "code": null, "e": 2695, "s": 2597, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2764, "s": 2695, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 2796, "s": 2764, "text": "Android SDK and it's Components" }, { "code": null, "e": 2835, "s": 2796, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 2884, "s": 2835, "text": "How to Communicate Between Fragments in Android?" }, { "code": null, "e": 2926, "s": 2884, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 2977, "s": 2926, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 3000, "s": 2977, "text": "Flutter - Stack Widget" }, { "code": null, "e": 3036, "s": 3000, "text": "Introduction to Android Development" }, { "code": null, "e": 3080, "s": 3036, "text": "Activity Lifecycle in Android with Demo App" } ]
Type Annotations in Julia
12 Oct, 2020 Julia is a dynamically typed language i.e. the type of the variable need not be declared in the program statically. Along with this, it also provides a technique to comment on the type of variable to the Just-in-Time (JIT) compiler at the runtime. Moreover, Julia supports both dynamic as well as static typing. This distinctive feature of Julia differentiates it from the other programming languages. Type-annotating variables in Julia can be done using the :: operator. This operator confirms that the value on the left is the same type as the value on the right. Syntax: <expr>::<type> where, expr: It can be an expression for computing a value or an assignment statement for a variable or an declaration of a variable. type: It is the data type of the variable being used in the program. Julia type annotations can be used for two types of expressions: Type Assert: It is an expression that is used for computing a certain value of a variable. Example 1 : Julia # Julia program to illustrate Type Assertionb = 10 # assures at runtime that 'b' will be an integera = b :: Int print(a) Output: Example 2: Julia # Julia program to illustrate Type Assertionc = 20.5d = 30.4 # assures at runtime that 'c+d' will be a float64c + d::Float64 print(c + d) Output: Example 3: Julia # Julia program to illustrate Type Assertionc = 10.5 # assures at runtime that 'c+c' will be an integer c + c::Int Output: ERROR: TypeError: in typeassert, expected Int64, got a value of type Float64 Stacktrace: [1] top-level scope at REPL[2]:1 Variable Type Declaration: These are left-hand sides of assignments or declarations of local variables. It also covers type fields of a struct and named tuples. Function arguments and return type can also be type-annotated. Example 4: Julia # Julia program for variable type declarationstruct example # this field will always contain only integer values x ::Int end x = 20print(x) Output: Example 5: Julia # Julia program for variable type declarationstruct Person # this field will always contain only string values name::String # this field will always contain only integer values age::Int end p = Person("Max", 24) Output: Example 6: Julia # Function accepting Float64 value # and returning a Float32 value function example(x ::Float64) ::Float32 cos(Ο€ * x) end # calling the functionresult = example(1.5) # print resultprint(result) Output: Julia Data-science Julia Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Vectors in Julia Getting rounded value of a number in Julia - round() Method Manipulating matrices in Julia Reshaping array dimensions in Julia | Array reshape() Method Storing Output on a File in Julia Exception handling in Julia Formatting of Strings in Julia Tuples in Julia Creating array with repeated elements in Julia - repeat() Method Get array dimensions and size of a dimension in Julia - size() Method
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Oct, 2020" }, { "code": null, "e": 430, "s": 28, "text": "Julia is a dynamically typed language i.e. the type of the variable need not be declared in the program statically. Along with this, it also provides a technique to comment on the type of variable to the Just-in-Time (JIT) compiler at the runtime. Moreover, Julia supports both dynamic as well as static typing. This distinctive feature of Julia differentiates it from the other programming languages." }, { "code": null, "e": 594, "s": 430, "text": "Type-annotating variables in Julia can be done using the :: operator. This operator confirms that the value on the left is the same type as the value on the right." }, { "code": null, "e": 603, "s": 594, "text": "Syntax: " }, { "code": null, "e": 618, "s": 603, "text": "<expr>::<type>" }, { "code": null, "e": 625, "s": 618, "text": "where," }, { "code": null, "e": 753, "s": 625, "text": "expr: It can be an expression for computing a value or an assignment statement for a variable or an declaration of a variable." }, { "code": null, "e": 822, "s": 753, "text": "type: It is the data type of the variable being used in the program." }, { "code": null, "e": 887, "s": 822, "text": "Julia type annotations can be used for two types of expressions:" }, { "code": null, "e": 978, "s": 887, "text": "Type Assert: It is an expression that is used for computing a certain value of a variable." }, { "code": null, "e": 990, "s": 978, "text": "Example 1 :" }, { "code": null, "e": 996, "s": 990, "text": "Julia" }, { "code": "# Julia program to illustrate Type Assertionb = 10 # assures at runtime that 'b' will be an integera = b :: Int print(a)", "e": 1124, "s": 996, "text": null }, { "code": null, "e": 1132, "s": 1124, "text": "Output:" }, { "code": null, "e": 1143, "s": 1132, "text": "Example 2:" }, { "code": null, "e": 1149, "s": 1143, "text": "Julia" }, { "code": "# Julia program to illustrate Type Assertionc = 20.5d = 30.4 # assures at runtime that 'c+d' will be a float64c + d::Float64 print(c + d)", "e": 1292, "s": 1149, "text": null }, { "code": null, "e": 1300, "s": 1292, "text": "Output:" }, { "code": null, "e": 1311, "s": 1300, "text": "Example 3:" }, { "code": null, "e": 1317, "s": 1311, "text": "Julia" }, { "code": "# Julia program to illustrate Type Assertionc = 10.5 # assures at runtime that 'c+c' will be an integer c + c::Int", "e": 1434, "s": 1317, "text": null }, { "code": null, "e": 1442, "s": 1434, "text": "Output:" }, { "code": null, "e": 1565, "s": 1442, "text": "ERROR: TypeError: in typeassert, expected Int64, got a value of type Float64\nStacktrace:\n[1] top-level scope at REPL[2]:1\n" }, { "code": null, "e": 1592, "s": 1565, "text": "Variable Type Declaration:" }, { "code": null, "e": 1669, "s": 1592, "text": "These are left-hand sides of assignments or declarations of local variables." }, { "code": null, "e": 1726, "s": 1669, "text": "It also covers type fields of a struct and named tuples." }, { "code": null, "e": 1789, "s": 1726, "text": "Function arguments and return type can also be type-annotated." }, { "code": null, "e": 1800, "s": 1789, "text": "Example 4:" }, { "code": null, "e": 1806, "s": 1800, "text": "Julia" }, { "code": "# Julia program for variable type declarationstruct example # this field will always contain only integer values x ::Int end x = 20print(x)", "e": 1953, "s": 1806, "text": null }, { "code": null, "e": 1961, "s": 1953, "text": "Output:" }, { "code": null, "e": 1972, "s": 1961, "text": "Example 5:" }, { "code": null, "e": 1978, "s": 1972, "text": "Julia" }, { "code": "# Julia program for variable type declarationstruct Person # this field will always contain only string values name::String # this field will always contain only integer values age::Int end p = Person(\"Max\", 24)", "e": 2202, "s": 1978, "text": null }, { "code": null, "e": 2211, "s": 2202, "text": " Output:" }, { "code": null, "e": 2223, "s": 2211, "text": "Example 6: " }, { "code": null, "e": 2229, "s": 2223, "text": "Julia" }, { "code": "# Function accepting Float64 value # and returning a Float32 value function example(x ::Float64) ::Float32 cos(Ο€ * x) end # calling the functionresult = example(1.5) # print resultprint(result)", "e": 2432, "s": 2229, "text": null }, { "code": null, "e": 2440, "s": 2432, "text": "Output:" }, { "code": null, "e": 2459, "s": 2440, "text": "Julia Data-science" }, { "code": null, "e": 2465, "s": 2459, "text": "Julia" }, { "code": null, "e": 2563, "s": 2465, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2580, "s": 2563, "text": "Vectors in Julia" }, { "code": null, "e": 2640, "s": 2580, "text": "Getting rounded value of a number in Julia - round() Method" }, { "code": null, "e": 2671, "s": 2640, "text": "Manipulating matrices in Julia" }, { "code": null, "e": 2732, "s": 2671, "text": "Reshaping array dimensions in Julia | Array reshape() Method" }, { "code": null, "e": 2766, "s": 2732, "text": "Storing Output on a File in Julia" }, { "code": null, "e": 2794, "s": 2766, "text": "Exception handling in Julia" }, { "code": null, "e": 2825, "s": 2794, "text": "Formatting of Strings in Julia" }, { "code": null, "e": 2841, "s": 2825, "text": "Tuples in Julia" }, { "code": null, "e": 2906, "s": 2841, "text": "Creating array with repeated elements in Julia - repeat() Method" } ]
multiset find() function in C++ STL
07 Jul, 2022 The multiset::find() is a built-in function in C++ STL which returns an iterator pointing to the lower_bound of the element which is searched in the multiset container. If the element is not found, then the iterator points to the position past the last element in the set. Syntax: multiset_name.find(element) Parameters: The function accepts one mandatory parameter element which specifies the element to be searched in the multiset container. Return Value: The function returns an iterator which points to the element which is searched in the multiset container. If the element is not found, then the iterator points to the position just after the last element in the multiset. Time complexity: If n is the size of multiset, then the time complexity of multiset::find() function is logarithmic order of n i.e. O(log(n)). Below program illustrates the above function. Program 1: CPP // CPP program to demonstrate the// multiset::find() function#include <bits/stdc++.h>using namespace std;int main(){ // Initialize multiset multiset<int> s; s.insert(1); s.insert(4); s.insert(2); s.insert(5); s.insert(3); s.insert(3); s.insert(3); s.insert(5); cout << "The set elements are: "; for (auto it = s.begin(); it != s.end(); it++) cout << *it << " "; // iterator pointing to // position where 2 is auto pos = s.find(3); // prints the set elements cout << "\nThe set elements after 3 are: "; for (auto it = pos; it != s.end(); it++) cout << *it << " "; return 0;} The set elements are: 1 2 3 3 3 4 5 5 The set elements after 3 are: 3 3 3 4 5 5 Program 2: CPP // CPP program to demonstrate the// multiset::find() function#include <bits/stdc++.h>using namespace std;int main(){ // Initialize multiset multiset<char> s; s.insert('a'); s.insert('a'); s.insert('a'); s.insert('b'); s.insert('c'); s.insert('a'); s.insert('a'); s.insert('c'); cout << "The set elements are: "; for (auto it = s.begin(); it != s.end(); it++) cout << *it << " "; // iterator pointing to // position where 2 is auto pos = s.find('b'); // prints the set elements cout << "\nThe set elements after b are: "; for (auto it = pos; it != s.end(); it++) cout << *it << " "; return 0;} The set elements are: a a a a a b c c The set elements after b are: b c c rishabhpandey7681 CPP-Functions cpp-multiset 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": "\n07 Jul, 2022" }, { "code": null, "e": 327, "s": 53, "text": "The multiset::find() is a built-in function in C++ STL which returns an iterator pointing to the lower_bound of the element which is searched in the multiset container. If the element is not found, then the iterator points to the position past the last element in the set. " }, { "code": null, "e": 335, "s": 327, "text": "Syntax:" }, { "code": null, "e": 363, "s": 335, "text": "multiset_name.find(element)" }, { "code": null, "e": 499, "s": 363, "text": "Parameters: The function accepts one mandatory parameter element which specifies the element to be searched in the multiset container. " }, { "code": null, "e": 735, "s": 499, "text": "Return Value: The function returns an iterator which points to the element which is searched in the multiset container. If the element is not found, then the iterator points to the position just after the last element in the multiset. " }, { "code": null, "e": 879, "s": 735, "text": "Time complexity: If n is the size of multiset, then the time complexity of multiset::find() function is logarithmic order of n i.e. O(log(n)). " }, { "code": null, "e": 925, "s": 879, "text": "Below program illustrates the above function." }, { "code": null, "e": 938, "s": 925, "text": " Program 1: " }, { "code": null, "e": 942, "s": 938, "text": "CPP" }, { "code": "// CPP program to demonstrate the// multiset::find() function#include <bits/stdc++.h>using namespace std;int main(){ // Initialize multiset multiset<int> s; s.insert(1); s.insert(4); s.insert(2); s.insert(5); s.insert(3); s.insert(3); s.insert(3); s.insert(5); cout << \"The set elements are: \"; for (auto it = s.begin(); it != s.end(); it++) cout << *it << \" \"; // iterator pointing to // position where 2 is auto pos = s.find(3); // prints the set elements cout << \"\\nThe set elements after 3 are: \"; for (auto it = pos; it != s.end(); it++) cout << *it << \" \"; return 0;}", "e": 1547, "s": 942, "text": null }, { "code": null, "e": 1628, "s": 1547, "text": "The set elements are: 1 2 3 3 3 4 5 5 \nThe set elements after 3 are: 3 3 3 4 5 5" }, { "code": null, "e": 1640, "s": 1628, "text": "Program 2: " }, { "code": null, "e": 1644, "s": 1640, "text": "CPP" }, { "code": "// CPP program to demonstrate the// multiset::find() function#include <bits/stdc++.h>using namespace std;int main(){ // Initialize multiset multiset<char> s; s.insert('a'); s.insert('a'); s.insert('a'); s.insert('b'); s.insert('c'); s.insert('a'); s.insert('a'); s.insert('c'); cout << \"The set elements are: \"; for (auto it = s.begin(); it != s.end(); it++) cout << *it << \" \"; // iterator pointing to // position where 2 is auto pos = s.find('b'); // prints the set elements cout << \"\\nThe set elements after b are: \"; for (auto it = pos; it != s.end(); it++) cout << *it << \" \"; return 0;}", "e": 2268, "s": 1644, "text": null }, { "code": null, "e": 2343, "s": 2268, "text": "The set elements are: a a a a a b c c \nThe set elements after b are: b c c" }, { "code": null, "e": 2361, "s": 2343, "text": "rishabhpandey7681" }, { "code": null, "e": 2375, "s": 2361, "text": "CPP-Functions" }, { "code": null, "e": 2388, "s": 2375, "text": "cpp-multiset" }, { "code": null, "e": 2392, "s": 2388, "text": "STL" }, { "code": null, "e": 2396, "s": 2392, "text": "C++" }, { "code": null, "e": 2400, "s": 2396, "text": "STL" }, { "code": null, "e": 2404, "s": 2400, "text": "CPP" } ]
LocalDate minus() method in Java with Examples
28 Jan, 2022 In LocalDate class, there are two types of minus() method depending upon the parameters passed to it. minus() method of a LocalDate class used to Returns a copy of this LocalDate with the specified amount of unit subtracted to LocalDate.If it is not possible to subtract the amount, because the unit is not supported or for some other reason, an exception is thrown.Syntax: public LocalDate minus(long amountToSubtract, TemporalUnit unit) Parameters: This method accepts two parameters: amountToSubtract: which is the amount of the unit to subtract to the result, may be negative unit: which is the unit of the amount to subtract. Return value: This method returns LocalDate based on this date-time with the specified amount subtracted.Exception: This method throws following Exceptions: DateTimeException: if the subtraction cannot be made UnsupportedTemporalTypeException: if the unit is not supported ArithmeticException: if numeric overflow occurs Below programs illustrate the minus() method:Program 1: Java // Java program to demonstrate// LocalDate.minus() method import java.time.*;import java.time.temporal.ChronoUnit; public class GFG { public static void main(String[] args) { // create a LocalDate object LocalDate zonedlt = LocalDate.parse("2018-12-06"); // subtract 12 Years to LocalDate LocalDate value = zonedlt.minus(12, ChronoUnit.YEARS); // print result System.out.println("LocalDate after " + "subtracting Months: " + value); }} LocalDate after subtracting Months: 2006-12-06 minus() method of a LocalDate class used to returns a copy of this LocalDate with the specified amount subtracted to LocalDate.The amount is typically Period or Duration but may be any other type implementing the TemporalAmount interface.Syntax: public LocalDate minus(TemporalAmount amountTosubtract) Parameters: This method accepts one single parameter amountTosubtract which is the amount to subtract, It should not be null.Return value: This method returns LocalDate based on this date-time with the subtraction made, not null.Exception: This method throws following Exceptions: DateTimeException: if the subtraction cannot be made ArithmeticException: if numeric overflow occurs Below programs illustrate the minus() method:Program 1: Java // Java program to demonstrate// LocalDate.minus() method import java.time.*;public class GFG { public static void main(String[] args) { // create a LocalDate object LocalDate zonedlt = LocalDate.parse("2018-12-06"); // subtract 30 Days to LocalDate LocalDate value = zonedlt.minus(Period.ofDays(30)); // print result System.out.println("LocalDate after" + " subtracting Days: " + value); }} LocalDate after subtracting Days: 2018-11-06 Reference: https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#minus(java.time.temporal.TemporalAmount) https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#minus(long, java.time.temporal.TemporalUnit) saurabh1990aror Java-Functions Java-LocalDate Java-time package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples Stream In Java ArrayList in Java Collections in Java Singleton Class in Java Multidimensional Arrays in Java Set in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jan, 2022" }, { "code": null, "e": 131, "s": 28, "text": "In LocalDate class, there are two types of minus() method depending upon the parameters passed to it. " }, { "code": null, "e": 405, "s": 131, "text": "minus() method of a LocalDate class used to Returns a copy of this LocalDate with the specified amount of unit subtracted to LocalDate.If it is not possible to subtract the amount, because the unit is not supported or for some other reason, an exception is thrown.Syntax: " }, { "code": null, "e": 493, "s": 405, "text": "public LocalDate minus(long amountToSubtract,\n TemporalUnit unit)" }, { "code": null, "e": 543, "s": 493, "text": "Parameters: This method accepts two parameters: " }, { "code": null, "e": 636, "s": 543, "text": "amountToSubtract: which is the amount of the unit to subtract to the result, may be negative" }, { "code": null, "e": 687, "s": 636, "text": "unit: which is the unit of the amount to subtract." }, { "code": null, "e": 846, "s": 687, "text": "Return value: This method returns LocalDate based on this date-time with the specified amount subtracted.Exception: This method throws following Exceptions: " }, { "code": null, "e": 899, "s": 846, "text": "DateTimeException: if the subtraction cannot be made" }, { "code": null, "e": 962, "s": 899, "text": "UnsupportedTemporalTypeException: if the unit is not supported" }, { "code": null, "e": 1010, "s": 962, "text": "ArithmeticException: if numeric overflow occurs" }, { "code": null, "e": 1068, "s": 1010, "text": "Below programs illustrate the minus() method:Program 1: " }, { "code": null, "e": 1073, "s": 1068, "text": "Java" }, { "code": "// Java program to demonstrate// LocalDate.minus() method import java.time.*;import java.time.temporal.ChronoUnit; public class GFG { public static void main(String[] args) { // create a LocalDate object LocalDate zonedlt = LocalDate.parse(\"2018-12-06\"); // subtract 12 Years to LocalDate LocalDate value = zonedlt.minus(12, ChronoUnit.YEARS); // print result System.out.println(\"LocalDate after \" + \"subtracting Months: \" + value); }}", "e": 1637, "s": 1073, "text": null }, { "code": null, "e": 1684, "s": 1637, "text": "LocalDate after subtracting Months: 2006-12-06" }, { "code": null, "e": 1934, "s": 1686, "text": "minus() method of a LocalDate class used to returns a copy of this LocalDate with the specified amount subtracted to LocalDate.The amount is typically Period or Duration but may be any other type implementing the TemporalAmount interface.Syntax: " }, { "code": null, "e": 1990, "s": 1934, "text": "public LocalDate minus(TemporalAmount amountTosubtract)" }, { "code": null, "e": 2273, "s": 1990, "text": "Parameters: This method accepts one single parameter amountTosubtract which is the amount to subtract, It should not be null.Return value: This method returns LocalDate based on this date-time with the subtraction made, not null.Exception: This method throws following Exceptions: " }, { "code": null, "e": 2326, "s": 2273, "text": "DateTimeException: if the subtraction cannot be made" }, { "code": null, "e": 2374, "s": 2326, "text": "ArithmeticException: if numeric overflow occurs" }, { "code": null, "e": 2432, "s": 2374, "text": "Below programs illustrate the minus() method:Program 1: " }, { "code": null, "e": 2437, "s": 2432, "text": "Java" }, { "code": "// Java program to demonstrate// LocalDate.minus() method import java.time.*;public class GFG { public static void main(String[] args) { // create a LocalDate object LocalDate zonedlt = LocalDate.parse(\"2018-12-06\"); // subtract 30 Days to LocalDate LocalDate value = zonedlt.minus(Period.ofDays(30)); // print result System.out.println(\"LocalDate after\" + \" subtracting Days: \" + value); }}", "e": 2957, "s": 2437, "text": null }, { "code": null, "e": 3002, "s": 2957, "text": "LocalDate after subtracting Days: 2018-11-06" }, { "code": null, "e": 3016, "s": 3004, "text": "Reference: " }, { "code": null, "e": 3125, "s": 3016, "text": "https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#minus(java.time.temporal.TemporalAmount)" }, { "code": null, "e": 3238, "s": 3125, "text": "https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#minus(long, java.time.temporal.TemporalUnit)" }, { "code": null, "e": 3256, "s": 3240, "text": "saurabh1990aror" }, { "code": null, "e": 3271, "s": 3256, "text": "Java-Functions" }, { "code": null, "e": 3286, "s": 3271, "text": "Java-LocalDate" }, { "code": null, "e": 3304, "s": 3286, "text": "Java-time package" }, { "code": null, "e": 3309, "s": 3304, "text": "Java" }, { "code": null, "e": 3314, "s": 3309, "text": "Java" }, { "code": null, "e": 3412, "s": 3314, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3463, "s": 3412, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 3494, "s": 3463, "text": "How to iterate any Map in Java" }, { "code": null, "e": 3513, "s": 3494, "text": "Interfaces in Java" }, { "code": null, "e": 3543, "s": 3513, "text": "HashMap in Java with Examples" }, { "code": null, "e": 3558, "s": 3543, "text": "Stream In Java" }, { "code": null, "e": 3576, "s": 3558, "text": "ArrayList in Java" }, { "code": null, "e": 3596, "s": 3576, "text": "Collections in Java" }, { "code": null, "e": 3620, "s": 3596, "text": "Singleton Class in Java" }, { "code": null, "e": 3652, "s": 3620, "text": "Multidimensional Arrays in Java" } ]
Print all sequences of given length
11 Oct, 2021 Given two integers k and n, write a function that prints all the sequences of length k composed of numbers 1,2..n. You need to print these sequences in sorted order.Examples: Input: k = 2, n = 3 Output: 1 1 1 2 1 3 2 1 2 2 2 3 3 1 3 2 3 3 Input: k = 3, n = 4 Output: 1 1 1 1 1 2 1 1 3 1 1 4 1 2 1 ..... ..... 4 3 4 4 4 1 4 4 2 4 4 3 4 4 4 Method 1 (Simple and Iterative): The simple idea to print all sequences in sorted order is to start from {1 1 ... 1} and keep incrementing the sequence while the sequence doesn’t become {n n ... n}. Following is the detailed process.1) Create an output array arr[] of size k. Initialize the array as {1, 1...1}. 2) Print the array arr[]. 3) Update the array arr[] so that it becomes immediate successor (to be printed) of itself. For example, immediate successor of {1, 1, 1} is {1, 1, 2}, immediate successor of {1, 4, 4} is {2, 1, 1} and immediate successor of {4, 4, 3} is {4 4 4}. 4) Repeat steps 2 and 3 while there is a successor array. In other words, while the output array arr[] doesn’t become {n, n .. n}Now let us talk about how to modify the array so that it contains immediate successor. By definition, the immediate successor should have the same first p terms and larger (p+l)th term. In the original array, (p+1)th term (or arr[p]) is smaller than n and all terms after arr[p] i.e., arr[p+1], arr[p+2], ... arr[k-1] are n. To find the immediate successor, we find the point p in the previously printed array. To find point p, we start from rightmost side and keep moving till we find a number arr[p] such that arr[p] is smaller than n (or not n). Once we find such a point, we increment it arr[p] by 1 and make all the elements after arr[p] as 1 i.e., we do arr[p+1] = 1, arr[p+2] = 1 .. arr[k-1] = 1. Following are the detailed steps to get immediate successor of arr[]1) Start from the rightmost term arr[k-1] and move toward left. Find the first element arr[p] that is not same as n. 2) Increment arr[p] by 1 3) Starting from arr[p+1] to arr[k-1], set the value of all terms as 1. C++ C Java Python3 C# Javascript // CPP program of above approach#include<iostream>using namespace std;/* A utility function that prints a given arr[] of length size*/void printArray(int arr[], int size){ for(int i = 0; i < size; i++) cout <<" "<< arr[i]; cout <<"\n"; return;} /* This function returns 0 if there are no more sequences to be printed, otherwise modifies arr[] so that arr[] contains next sequence to be printed */int getSuccessor(int arr[], int k, int n){ /* start from the rightmost side and find the first number less than n */ int p = k - 1; while (arr[p] == n) p--; /* If all numbers are n in the array then there is no successor, return 0 */ if (p < 0) return 0; /* Update arr[] so that it contains successor */ arr[p] = arr[p] + 1; for(int i = p + 1; i < k; i++) arr[i] = 1; return 1;} /* The main function that prints all sequences from 1, 1, ..1 to n, n, ..n */void printSequences(int n, int k){ int *arr = new int[k]; /* Initialize the current sequence as the first sequence to be printed */ for(int i = 0; i < k; i++) arr[i] = 1; /* The loop breaks when there are no more successors to be printed */ while(1) { /* Print the current sequence */ printArray(arr, k); /* Update arr[] so that it contains next sequence to be printed. And if there are no more sequences then break the loop */ if(getSuccessor(arr, k, n) == 0) break; } delete(arr); // free dynamically allocated array return;} /* Driver Program to test above functions */int main(){ int n = 3; int k = 2; printSequences(n, k); return 0;} // this code is contributed by shivanisinghss2110 // CPP program of above approach#include<stdio.h> /* A utility function that prints a given arr[] of length size*/void printArray(int arr[], int size){ for(int i = 0; i < size; i++) printf("%d ", arr[i]); printf("\n"); return;} /* This function returns 0 if there are no more sequences to be printed, otherwise modifies arr[] so that arr[] contains next sequence to be printed */int getSuccessor(int arr[], int k, int n){ /* start from the rightmost side and find the first number less than n */ int p = k - 1; while (arr[p] == n) p--; /* If all numbers are n in the array then there is no successor, return 0 */ if (p < 0) return 0; /* Update arr[] so that it contains successor */ arr[p] = arr[p] + 1; for(int i = p + 1; i < k; i++) arr[i] = 1; return 1;} /* The main function that prints all sequences from 1, 1, ..1 to n, n, ..n */void printSequences(int n, int k){ int *arr = new int[k]; /* Initialize the current sequence as the first sequence to be printed */ for(int i = 0; i < k; i++) arr[i] = 1; /* The loop breaks when there are no more successors to be printed */ while(1) { /* Print the current sequence */ printArray(arr, k); /* Update arr[] so that it contains next sequence to be printed. And if there are no more sequences then break the loop */ if(getSuccessor(arr, k, n) == 0) break; } delete(arr); // free dynamically allocated array return;} /* Driver Program to test above functions */int main(){ int n = 3; int k = 2; printSequences(n, k); return 0;} // JAVA program of above approach class GFG{ /* A utility function that prints a given arr[] of length size*/ static void printArray(int arr[], int size) { for (int i = 0; i < size; i++) { System.out.printf("%d ", arr[i]); } System.out.printf("\n"); return; } /* This function returns 0 if there are no more sequences to be printed, otherwise modifies arr[] so that arr[] contains next sequence to be printed */ static int getSuccessor(int arr[], int k, int n) { /* start from the rightmost side and find the first number less than n */ int p = k - 1; while (arr[p] == n) { p--; if (p < 0) { break; } } /* If all numbers are n in the array then there is no successor, return 0 */ if (p < 0) { return 0; } /* Update arr[] so that it contains successor */ arr[p] = arr[p] + 1; for (int i = p + 1; i < k; i++) { arr[i] = 1; } return 1; } /* The main function that prints all sequences from 1, 1, ..1 to n, n, ..n */ static void printSequences(int n, int k) { int[] arr = new int[k]; /* Initialize the current sequence as the first sequence to be printed */ for (int i = 0; i < k; i++) { arr[i] = 1; } /* The loop breaks when there are no more successors to be printed */ while (true) { /* Print the current sequence */ printArray(arr, k); /* Update arr[] so that it contains next sequence to be printed. And if there are no more sequences then break the loop */ if (getSuccessor(arr, k, n) == 0) { break; } } } /* Driver code */ public static void main(String[] args) { int n = 3; int k = 2; printSequences(n, k); }} // This code is contributed by PrinciRaj1992 # Python3 program of above approach # A utility function that prints# a given arr[] of length size#def printArray(arr, size): for i in range(size): print(arr[i], end = " ") print() return # This function returns 0 if there are# no more sequences to be printed, otherwise# modifies arr[] so that arr[] contains# next sequence to be printed #def getSuccessor(arr, k, n): # start from the rightmost side and # find the first number less than n p = k - 1 while (arr[p] == n and 0 <= p < k): p -= 1 # If all numbers are n in the array # then there is no successor, return 0 if (p < 0): return 0 # Update arr[] so that it contains successor arr[p] = arr[p] + 1 i = p + 1 while(i < k): arr[i] = 1 i += 1 return 1 # The main function that prints all sequences# from 1, 1, ..1 to n, n, ..ndef printSequences(n, k): arr = [0] * k # Initialize the current sequence as # the first sequence to be printed # for i in range(k): arr[i] = 1 # The loop breaks when there are # no more successors to be printed while(1): # Print the current sequence printArray(arr, k) # Update arr[] so that it contains # next sequence to be printed. And if # there are no more sequences then # break the loop if(getSuccessor(arr, k, n) == 0): break return # Driver coden = 3k = 2printSequences(n, k) # This code is contributed by shubhamsingh10 // C# program of above approachusing System; class GFG{ /* A utility function that prints a given []arr of length size*/ static void printArray(int []arr, int size) { for (int i = 0; i < size; i++) { Console.Write("{0} ", arr[i]); } Console.Write("\n"); return; } /* This function returns 0 if there are no more sequences to be printed, otherwise modifies []arr so that []arr contains next sequence to be printed */ static int getSuccessor(int []arr, int k, int n) { /* start from the rightmost side and find the first number less than n */ int p = k - 1; while (arr[p] == n) { p--; if (p < 0) { break; } } /* If all numbers are n in the array then there is no successor, return 0 */ if (p < 0) { return 0; } /* Update []arr so that it contains successor */ arr[p] = arr[p] + 1; for (int i = p + 1; i < k; i++) { arr[i] = 1; } return 1; } /* The main function that prints all sequences from 1, 1, ..1 to n, n, ..n */ static void printSequences(int n, int k) { int[] arr = new int[k]; /* Initialize the current sequence as the first sequence to be printed */ for (int i = 0; i < k; i++) { arr[i] = 1; } /* The loop breaks when there are no more successors to be printed */ while (true) { /* Print the current sequence */ printArray(arr, k); /* Update []arr so that it contains next sequence to be printed. And if there are no more sequences then break the loop */ if (getSuccessor(arr, k, n) == 0) { break; } } } /* Driver code */ public static void Main(String[] args) { int n = 3; int k = 2; printSequences(n, k); }} // This code is contributed by Rajput-Ji <script> // javascript program of above approach /* A utility function that prints agiven arr of length size*/function printArray(arr , size){ for (i = 0; i < size; i++) { document.write(arr[i]+" "); } document.write("<br>"); return;} /* This function returns 0 if there areno more sequences to be printed, otherwisemodifies arr so that arr containsnext sequence to be printed */function getSuccessor(arr , k , n){ /* start from the rightmost side and find the first number less than n */ var p = k - 1; while (arr[p] == n) { p--; if (p < 0) { break; } } /* If all numbers are n in the array then there is no successor, return 0 */ if (p < 0) { return 0; } /* Update arr so that it contains successor */ arr[p] = arr[p] + 1; for (i = p + 1; i < k; i++) { arr[i] = 1; } return 1;} /* The main function that prints allsequences from 1, 1, ..1 to n, n, ..n */function printSequences(n , k){ var arr = Array.from({length: k}, (_, i) => 0); /* Initialize the current sequence as the first sequence to be printed */ for (i = 0; i < k; i++) { arr[i] = 1; } /* The loop breaks when there are no more successors to be printed */ while (true) { /* Print the current sequence */ printArray(arr, k); /* Update arr so that it contains next sequence to be printed. And if there are no more sequences then break the loop */ if (getSuccessor(arr, k, n) == 0) { break; } }} /* Driver code */var n = 3;var k = 2;printSequences(n, k); // This code is contributed by 29AjayKumar </script> Output: 1 1 1 2 1 3 2 1 2 2 2 3 3 1 3 2 3 3 Time Complexity: There are total n^k sequences. Printing a sequence and finding its successor take O(k) time. So time complexity of above implementation is O(k*n^k). Auxiliary Space: O(k)Method 2 (Tricky and Recursive) The recursive function printSequencesRecur generates and prints all sequences of length k. The idea is to use one more parameter index. The function printSequencesRecur keeps all the terms in arr[] sane till index, update the value at index and recursively calls itself for more terms after index. C++ C Java Python3 C# PHP Javascript // C++ program of above approach#include<iostream>using namespace std; /* A utility function that prints a given arr[] of length size*/void printArray(int arr[], int size){ for(int i = 0; i < size; i++) cout<< " "<< arr[i]; cout<<"\n"; return;} /* The core function that recursively generates and prints all sequences of length k */void printSequencesRecur(int arr[], int n, int k, int index){ int i; if (k == 0) { printArray(arr, index); } if (k > 0) { for(i = 1; i<=n; ++i) { arr[index] = i; printSequencesRecur(arr, n, k-1, index+1); } }} /* A function that uses printSequencesRecur() to prints all sequences from 1, 1, ..1 to n, n, ..n */void printSequences(int n, int k){ int *arr = new int[k]; printSequencesRecur(arr, n, k, 0); delete(arr); // free dynamically allocated array return;} /* Driver Program to test above functions */int main(){ int n = 3; int k = 2; printSequences(n, k); return 0;} // This code is contributed by shivanisinghss2110 // C++ program of above approach#include<stdio.h> /* A utility function that prints a given arr[] of length size*/void printArray(int arr[], int size){ for(int i = 0; i < size; i++) printf("%d ", arr[i]); printf("\n"); return;} /* The core function that recursively generates and prints all sequences of length k */void printSequencesRecur(int arr[], int n, int k, int index){ int i; if (k == 0) { printArray(arr, index); } if (k > 0) { for(i = 1; i<=n; ++i) { arr[index] = i; printSequencesRecur(arr, n, k-1, index+1); } }} /* A function that uses printSequencesRecur() to prints all sequences from 1, 1, ..1 to n, n, ..n */void printSequences(int n, int k){ int *arr = new int[k]; printSequencesRecur(arr, n, k, 0); delete(arr); // free dynamically allocated array return;} /* Driver Program to test above functions */int main(){ int n = 3; int k = 2; printSequences(n, k); return 0;} // Java program of above approach class GfG { /* A utility function that prints a given arr[] of length size*/static void printArray(int arr[], int size){ for(int i = 0; i < size; i++) System.out.print(arr[i] + " ");System.out.println(); return;} /* The core function that recursively generates and prints all sequences oflength k */static void printSequencesRecur(int arr[], int n, int k, int index){int i;if (k == 0){ printArray(arr, index);}if (k > 0){ for(i = 1; i<=n; ++i) { arr[index] = i; printSequencesRecur(arr, n, k-1, index+1); }}} /* A function that uses printSequencesRecur() to prints all sequencesfrom 1, 1, ..1 to n, n, ..n */static void printSequences(int n, int k){ int arr[] = new int[k]; printSequencesRecur(arr, n, k, 0); return ;} /* Driver Program to test above functions */public static void main(String[] args){ int n = 3; int k = 2; printSequences(n, k);}} # Python3 program of above approach # A utility function that prints a# given arr[] of length sizedef printArray(arr, size): for i in range(size): print(arr[i], end = " "); print(""); return; # The core function that recursively# generates and prints all sequences# of length kdef printSequencesRecur(arr, n, k, index): if (k == 0): printArray(arr, index); if (k > 0): for i in range(1, n + 1): arr[index] = i; printSequencesRecur(arr, n, k - 1, index + 1); # A function that uses printSequencesRecur() to# prints all sequences from 1, 1, ..1 to n, n, ..ndef printSequences(n, k): arr = [0] * n; printSequencesRecur(arr, n, k, 0); return; # Driver Coden = 3;k = 2;printSequences(n, k); # This code is contributed mits // C# program of above approachusing System; class GFG{ /* A utility function that prints a givenarr[] of length size*/static void printArray(int []arr, int size){ for(int i = 0; i < size; i++) Console.Write(arr[i] + " "); Console.WriteLine(); return;} /* The core function that recursively generatesand prints all sequences of length k */static void printSequencesRecur(int []arr, int n, int k, int index){ int i; if (k == 0) { printArray(arr, index); } if (k > 0) { for(i = 1; i<=n; ++i) { arr[index] = i; printSequencesRecur(arr, n, k - 1, index + 1); } }} /* A function that uses printSequencesRecur() toprints all sequences from 1, 1, ..1 to n, n, ..n */static void printSequences(int n, int k){ int[] arr = new int[k]; printSequencesRecur(arr, n, k, 0); return;} // Driver Codepublic static void Main(){ int n = 3; int k = 2; printSequences(n, k);}} // This code is contributed// by Akanksha Rai <?php// PHP program of above approach /* A utility function that prints agiven arr[] of length size*/function printArray($arr, $size){ for($i = 0; $i < $size; $i++) echo $arr[$i] . " "; echo "\n"; return;} /* The core function that recursively generatesand prints all sequences of length k */function printSequencesRecur($arr, $n, $k, $index){ if ($k == 0) { printArray($arr, $index); } if ($k > 0) { for($i = 1; $i <= $n; ++$i) { $arr[$index] = $i; printSequencesRecur($arr, $n, $k - 1, $index + 1); } }} /* A function that uses printSequencesRecur() toprints all sequences from 1, 1, ..1 to n, n, ..n */function printSequences($n, $k){ $arr = array(); printSequencesRecur($arr, $n, $k, 0); return;} // Driver Code$n = 3;$k = 2;printSequences($n, $k); // This code is contributed// by Akanksha Rai?> <script>// javascript program of above approach /* A utility function that prints a given arr of length size*/function printArray(arr, size){ for(i = 0; i < size; i++) document.write(arr[i] + " "); document.write("<br>"); return;} /* The core function that recursivelygenerates and prints all sequences oflength k */function printSequencesRecur(arr , n , k , index){ var i; if (k == 0) { printArray(arr, index); } if (k > 0) { for(i = 1; i <= n; ++i) { arr[index] = i; printSequencesRecur(arr, n, k - 1, index+1); } }} /* A function that uses printSequencesRecur()to prints all sequences from 1, 1, ..1 to n, n, ..n */function printSequences(n, k){ var arr = Array.from({length: k}, (_, i) => 0); printSequencesRecur(arr, n, k, 0); return ;} /* Driver Program to test above functions */var n = 3;var k = 2;printSequences(n, k); // This code is contributed by Amit Katiyar.</script> Output: 1 1 1 2 1 3 2 1 2 2 2 3 3 1 3 2 3 3 Time Complexity: There are n^k sequences and printing a sequence takes O(k) time. So time complexity is O(k*n^k). Auxiliary Space: O(k)Thanks to mopurizwarriors for suggesting above method. As suggested by alphayoung, we can avoid use of arrays for small sequences that can fit in an integer. Following is the implementation for same. C++ C Java Python3 C# PHP Javascript // C++ program of above approach /* The core function that generates andprints all sequences of length k */void printSeqRecur(int num, int pos, int k, int n){ if (pos == k) { cout << num << endl; return; } for (int i = 1; i <= n; i++) { printSeqRecur(num * 10 + i, pos + 1, k, n); }} /* A function that uses printSequencesRecur()to prints all sequencesfrom 1, 1, ..1 to n, n, ..n */void printSequences(int k, int n){ printSeqRecur(0, 0, k, n);} // This code is contributed by SHUBHAMSINGH10 // C program of above approach/* The core function that generates and prints all sequences of length k */void printSeqRecur(int num, int pos, int k, int n){ if (pos == k) { printf("%d \n", num); return; } for (int i = 1; i <= n; i++) { printSeqRecur(num * 10 + i, pos + 1, k, n); }} /* A function that uses printSequencesRecur() to prints all sequences from 1, 1, ..1 to n, n, ..n */void printSequences(int k, int n){ printSeqRecur(0, 0, k, n);} // Java program of above approach /* The core function that generates and prints all sequences of length k */static void printSeqRecur(int num, int pos, int k, int n){ if (pos == k) { System.out.print(num + " "); return; } for (int i = 1; i <= n; i++) { printSeqRecur(num * 10 + i, pos + 1, k, n); }} /* A function that uses printSequencesRecur() to prints all sequencesfrom 1, 1, ..1 to n, n, ..n */static void printSequences(int k, int n){ printSeqRecur(0, 0, k, n);} # Python program of above approach# We have used number instead of# arrays to prevent linear time# required to print each stringdef printSeqRecur ( num , n, k ): if n == 0: # if total digits become equal # to n, print the number and return print(num ) return for _ in range(1, k + 1): printSeqRecur (num * 10 + _, n - 1, k) # Driver Codeif __name__ == "__main__": k = 3 # length of k-ary string n = 2 # string can take values # from 1,2,3...n printSeqRecur(0, n, k) # This code is contributed# by shivam purohit // C# program of above approach /* The core function that generatesand prints all sequences of length k */static void printSeqRecur(int num, int pos, int k, int n){ if (pos == k) { Console.Write(num + " "); return; } for (int i = 1; i <= n; i++) { printSeqRecur(num * 10 + i, pos + 1, k, n); }} /* A function that uses printSequencesRecur()to prints all sequences from 1, 1, ..1 to n, n, ..n */static void printSequences(int k, int n){ printSeqRecur(0, 0, k, n);} // This code is contributed by Code_Mech <?php// PHP program of above approach// We have used number instead of// arrays to prevent linear time// required to print each stringfunction printSeqRecur ($num ,$n, $k){ if ($n == 0) { # if total digits become equal # to n, print the number and return print($num . "\n"); return; } for ($i = 1; $i < $k + 1; $i++) printSeqRecur($num * 10 + $i, $n - 1, $k);} // Driver Code$k = 3; // length of k-ary string$n = 2; // string can take values // from 1,2,3...nprintSeqRecur(0, $n, $k); // This code is contributed mits?> <script> // Javascript program of above approach /* The core function that generates andprints all sequences of length k */function printSeqRecur( num, pos, k, n){ if (pos == k) { document.write( num + "<br>" ); return; } for (var i = 1; i <= n; i++) { printSeqRecur(num * 10 + i, pos + 1, k, n); }} /* A function that uses printSequencesRecur()to prints all sequencesfrom 1, 1, ..1 to n, n, ..n */function printSequences( k, n){ printSeqRecur(0, 0, k, n);} // This code is contributed by SoumikMondal</script> Time Complexity: O(k*n^k) Auxiliary Space: O(n * k) References: Algorithms and Programming: Problems and Solutions by Alexander ShenPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Shivam Purohit 2 prerna saini Mithun Kumar Akanksha_Rai Code_Mech princiraj1992 Rajput-Ji SHUBHAMSINGH10 amit143katiyar 29AjayKumar SoumikMondal subham348 subhammahato348 shivanisinghss2110 subsequence Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Operators in C / C++ Sieve of Eratosthenes Prime Numbers Program to find GCD or HCF of two numbers Find minimum number of coins that make a given value Minimum number of jumps to reach end Algorithm to solve Rubik's Cube The Knight's tour problem | Backtracking-1 Program for Decimal to Binary Conversion
[ { "code": null, "e": 54, "s": 26, "text": "\n11 Oct, 2021" }, { "code": null, "e": 231, "s": 54, "text": "Given two integers k and n, write a function that prints all the sequences of length k composed of numbers 1,2..n. You need to print these sequences in sorted order.Examples: " }, { "code": null, "e": 297, "s": 231, "text": "Input: k = 2, n = 3\n\nOutput: \n1 1\n1 2\n1 3\n2 1\n2 2\n2 3\n3 1\n3 2\n3 3" }, { "code": null, "e": 402, "s": 299, "text": "Input: k = 3, n = 4\n\nOutput: \n1 1 1\n1 1 2\n1 1 3\n1 1 4\n1 2 1\n.....\n.....\n4 3 4\n4 4 1\n4 4 2\n4 4 3\n4 4 4" }, { "code": null, "e": 2103, "s": 402, "text": "Method 1 (Simple and Iterative): The simple idea to print all sequences in sorted order is to start from {1 1 ... 1} and keep incrementing the sequence while the sequence doesn’t become {n n ... n}. Following is the detailed process.1) Create an output array arr[] of size k. Initialize the array as {1, 1...1}. 2) Print the array arr[]. 3) Update the array arr[] so that it becomes immediate successor (to be printed) of itself. For example, immediate successor of {1, 1, 1} is {1, 1, 2}, immediate successor of {1, 4, 4} is {2, 1, 1} and immediate successor of {4, 4, 3} is {4 4 4}. 4) Repeat steps 2 and 3 while there is a successor array. In other words, while the output array arr[] doesn’t become {n, n .. n}Now let us talk about how to modify the array so that it contains immediate successor. By definition, the immediate successor should have the same first p terms and larger (p+l)th term. In the original array, (p+1)th term (or arr[p]) is smaller than n and all terms after arr[p] i.e., arr[p+1], arr[p+2], ... arr[k-1] are n. To find the immediate successor, we find the point p in the previously printed array. To find point p, we start from rightmost side and keep moving till we find a number arr[p] such that arr[p] is smaller than n (or not n). Once we find such a point, we increment it arr[p] by 1 and make all the elements after arr[p] as 1 i.e., we do arr[p+1] = 1, arr[p+2] = 1 .. arr[k-1] = 1. Following are the detailed steps to get immediate successor of arr[]1) Start from the rightmost term arr[k-1] and move toward left. Find the first element arr[p] that is not same as n. 2) Increment arr[p] by 1 3) Starting from arr[p+1] to arr[k-1], set the value of all terms as 1. " }, { "code": null, "e": 2107, "s": 2103, "text": "C++" }, { "code": null, "e": 2109, "s": 2107, "text": "C" }, { "code": null, "e": 2114, "s": 2109, "text": "Java" }, { "code": null, "e": 2122, "s": 2114, "text": "Python3" }, { "code": null, "e": 2125, "s": 2122, "text": "C#" }, { "code": null, "e": 2136, "s": 2125, "text": "Javascript" }, { "code": "// CPP program of above approach#include<iostream>using namespace std;/* A utility function that prints a given arr[] of length size*/void printArray(int arr[], int size){ for(int i = 0; i < size; i++) cout <<\" \"<< arr[i]; cout <<\"\\n\"; return;} /* This function returns 0 if there are no more sequences to be printed, otherwise modifies arr[] so that arr[] contains next sequence to be printed */int getSuccessor(int arr[], int k, int n){ /* start from the rightmost side and find the first number less than n */ int p = k - 1; while (arr[p] == n) p--; /* If all numbers are n in the array then there is no successor, return 0 */ if (p < 0) return 0; /* Update arr[] so that it contains successor */ arr[p] = arr[p] + 1; for(int i = p + 1; i < k; i++) arr[i] = 1; return 1;} /* The main function that prints all sequences from 1, 1, ..1 to n, n, ..n */void printSequences(int n, int k){ int *arr = new int[k]; /* Initialize the current sequence as the first sequence to be printed */ for(int i = 0; i < k; i++) arr[i] = 1; /* The loop breaks when there are no more successors to be printed */ while(1) { /* Print the current sequence */ printArray(arr, k); /* Update arr[] so that it contains next sequence to be printed. And if there are no more sequences then break the loop */ if(getSuccessor(arr, k, n) == 0) break; } delete(arr); // free dynamically allocated array return;} /* Driver Program to test above functions */int main(){ int n = 3; int k = 2; printSequences(n, k); return 0;} // this code is contributed by shivanisinghss2110", "e": 3843, "s": 2136, "text": null }, { "code": "// CPP program of above approach#include<stdio.h> /* A utility function that prints a given arr[] of length size*/void printArray(int arr[], int size){ for(int i = 0; i < size; i++) printf(\"%d \", arr[i]); printf(\"\\n\"); return;} /* This function returns 0 if there are no more sequences to be printed, otherwise modifies arr[] so that arr[] contains next sequence to be printed */int getSuccessor(int arr[], int k, int n){ /* start from the rightmost side and find the first number less than n */ int p = k - 1; while (arr[p] == n) p--; /* If all numbers are n in the array then there is no successor, return 0 */ if (p < 0) return 0; /* Update arr[] so that it contains successor */ arr[p] = arr[p] + 1; for(int i = p + 1; i < k; i++) arr[i] = 1; return 1;} /* The main function that prints all sequences from 1, 1, ..1 to n, n, ..n */void printSequences(int n, int k){ int *arr = new int[k]; /* Initialize the current sequence as the first sequence to be printed */ for(int i = 0; i < k; i++) arr[i] = 1; /* The loop breaks when there are no more successors to be printed */ while(1) { /* Print the current sequence */ printArray(arr, k); /* Update arr[] so that it contains next sequence to be printed. And if there are no more sequences then break the loop */ if(getSuccessor(arr, k, n) == 0) break; } delete(arr); // free dynamically allocated array return;} /* Driver Program to test above functions */int main(){ int n = 3; int k = 2; printSequences(n, k); return 0;}", "e": 5483, "s": 3843, "text": null }, { "code": "// JAVA program of above approach class GFG{ /* A utility function that prints a given arr[] of length size*/ static void printArray(int arr[], int size) { for (int i = 0; i < size; i++) { System.out.printf(\"%d \", arr[i]); } System.out.printf(\"\\n\"); return; } /* This function returns 0 if there are no more sequences to be printed, otherwise modifies arr[] so that arr[] contains next sequence to be printed */ static int getSuccessor(int arr[], int k, int n) { /* start from the rightmost side and find the first number less than n */ int p = k - 1; while (arr[p] == n) { p--; if (p < 0) { break; } } /* If all numbers are n in the array then there is no successor, return 0 */ if (p < 0) { return 0; } /* Update arr[] so that it contains successor */ arr[p] = arr[p] + 1; for (int i = p + 1; i < k; i++) { arr[i] = 1; } return 1; } /* The main function that prints all sequences from 1, 1, ..1 to n, n, ..n */ static void printSequences(int n, int k) { int[] arr = new int[k]; /* Initialize the current sequence as the first sequence to be printed */ for (int i = 0; i < k; i++) { arr[i] = 1; } /* The loop breaks when there are no more successors to be printed */ while (true) { /* Print the current sequence */ printArray(arr, k); /* Update arr[] so that it contains next sequence to be printed. And if there are no more sequences then break the loop */ if (getSuccessor(arr, k, n) == 0) { break; } } } /* Driver code */ public static void main(String[] args) { int n = 3; int k = 2; printSequences(n, k); }} // This code is contributed by PrinciRaj1992", "e": 7580, "s": 5483, "text": null }, { "code": "# Python3 program of above approach # A utility function that prints# a given arr[] of length size#def printArray(arr, size): for i in range(size): print(arr[i], end = \" \") print() return # This function returns 0 if there are# no more sequences to be printed, otherwise# modifies arr[] so that arr[] contains# next sequence to be printed #def getSuccessor(arr, k, n): # start from the rightmost side and # find the first number less than n p = k - 1 while (arr[p] == n and 0 <= p < k): p -= 1 # If all numbers are n in the array # then there is no successor, return 0 if (p < 0): return 0 # Update arr[] so that it contains successor arr[p] = arr[p] + 1 i = p + 1 while(i < k): arr[i] = 1 i += 1 return 1 # The main function that prints all sequences# from 1, 1, ..1 to n, n, ..ndef printSequences(n, k): arr = [0] * k # Initialize the current sequence as # the first sequence to be printed # for i in range(k): arr[i] = 1 # The loop breaks when there are # no more successors to be printed while(1): # Print the current sequence printArray(arr, k) # Update arr[] so that it contains # next sequence to be printed. And if # there are no more sequences then # break the loop if(getSuccessor(arr, k, n) == 0): break return # Driver coden = 3k = 2printSequences(n, k) # This code is contributed by shubhamsingh10", "e": 9121, "s": 7580, "text": null }, { "code": "// C# program of above approachusing System; class GFG{ /* A utility function that prints a given []arr of length size*/ static void printArray(int []arr, int size) { for (int i = 0; i < size; i++) { Console.Write(\"{0} \", arr[i]); } Console.Write(\"\\n\"); return; } /* This function returns 0 if there are no more sequences to be printed, otherwise modifies []arr so that []arr contains next sequence to be printed */ static int getSuccessor(int []arr, int k, int n) { /* start from the rightmost side and find the first number less than n */ int p = k - 1; while (arr[p] == n) { p--; if (p < 0) { break; } } /* If all numbers are n in the array then there is no successor, return 0 */ if (p < 0) { return 0; } /* Update []arr so that it contains successor */ arr[p] = arr[p] + 1; for (int i = p + 1; i < k; i++) { arr[i] = 1; } return 1; } /* The main function that prints all sequences from 1, 1, ..1 to n, n, ..n */ static void printSequences(int n, int k) { int[] arr = new int[k]; /* Initialize the current sequence as the first sequence to be printed */ for (int i = 0; i < k; i++) { arr[i] = 1; } /* The loop breaks when there are no more successors to be printed */ while (true) { /* Print the current sequence */ printArray(arr, k); /* Update []arr so that it contains next sequence to be printed. And if there are no more sequences then break the loop */ if (getSuccessor(arr, k, n) == 0) { break; } } } /* Driver code */ public static void Main(String[] args) { int n = 3; int k = 2; printSequences(n, k); }} // This code is contributed by Rajput-Ji", "e": 11221, "s": 9121, "text": null }, { "code": "<script> // javascript program of above approach /* A utility function that prints agiven arr of length size*/function printArray(arr , size){ for (i = 0; i < size; i++) { document.write(arr[i]+\" \"); } document.write(\"<br>\"); return;} /* This function returns 0 if there areno more sequences to be printed, otherwisemodifies arr so that arr containsnext sequence to be printed */function getSuccessor(arr , k , n){ /* start from the rightmost side and find the first number less than n */ var p = k - 1; while (arr[p] == n) { p--; if (p < 0) { break; } } /* If all numbers are n in the array then there is no successor, return 0 */ if (p < 0) { return 0; } /* Update arr so that it contains successor */ arr[p] = arr[p] + 1; for (i = p + 1; i < k; i++) { arr[i] = 1; } return 1;} /* The main function that prints allsequences from 1, 1, ..1 to n, n, ..n */function printSequences(n , k){ var arr = Array.from({length: k}, (_, i) => 0); /* Initialize the current sequence as the first sequence to be printed */ for (i = 0; i < k; i++) { arr[i] = 1; } /* The loop breaks when there are no more successors to be printed */ while (true) { /* Print the current sequence */ printArray(arr, k); /* Update arr so that it contains next sequence to be printed. And if there are no more sequences then break the loop */ if (getSuccessor(arr, k, n) == 0) { break; } }} /* Driver code */var n = 3;var k = 2;printSequences(n, k); // This code is contributed by 29AjayKumar </script>", "e": 12935, "s": 11221, "text": null }, { "code": null, "e": 12944, "s": 12935, "text": "Output: " }, { "code": null, "e": 12980, "s": 12944, "text": "1 1\n1 2\n1 3\n2 1\n2 2\n2 3\n3 1\n3 2\n3 3" }, { "code": null, "e": 13146, "s": 12980, "text": "Time Complexity: There are total n^k sequences. Printing a sequence and finding its successor take O(k) time. So time complexity of above implementation is O(k*n^k)." }, { "code": null, "e": 13499, "s": 13146, "text": "Auxiliary Space: O(k)Method 2 (Tricky and Recursive) The recursive function printSequencesRecur generates and prints all sequences of length k. The idea is to use one more parameter index. The function printSequencesRecur keeps all the terms in arr[] sane till index, update the value at index and recursively calls itself for more terms after index. " }, { "code": null, "e": 13503, "s": 13499, "text": "C++" }, { "code": null, "e": 13505, "s": 13503, "text": "C" }, { "code": null, "e": 13510, "s": 13505, "text": "Java" }, { "code": null, "e": 13518, "s": 13510, "text": "Python3" }, { "code": null, "e": 13521, "s": 13518, "text": "C#" }, { "code": null, "e": 13525, "s": 13521, "text": "PHP" }, { "code": null, "e": 13536, "s": 13525, "text": "Javascript" }, { "code": "// C++ program of above approach#include<iostream>using namespace std; /* A utility function that prints a given arr[] of length size*/void printArray(int arr[], int size){ for(int i = 0; i < size; i++) cout<< \" \"<< arr[i]; cout<<\"\\n\"; return;} /* The core function that recursively generates and prints all sequences of length k */void printSequencesRecur(int arr[], int n, int k, int index){ int i; if (k == 0) { printArray(arr, index); } if (k > 0) { for(i = 1; i<=n; ++i) { arr[index] = i; printSequencesRecur(arr, n, k-1, index+1); } }} /* A function that uses printSequencesRecur() to prints all sequences from 1, 1, ..1 to n, n, ..n */void printSequences(int n, int k){ int *arr = new int[k]; printSequencesRecur(arr, n, k, 0); delete(arr); // free dynamically allocated array return;} /* Driver Program to test above functions */int main(){ int n = 3; int k = 2; printSequences(n, k); return 0;} // This code is contributed by shivanisinghss2110", "e": 14582, "s": 13536, "text": null }, { "code": "// C++ program of above approach#include<stdio.h> /* A utility function that prints a given arr[] of length size*/void printArray(int arr[], int size){ for(int i = 0; i < size; i++) printf(\"%d \", arr[i]); printf(\"\\n\"); return;} /* The core function that recursively generates and prints all sequences of length k */void printSequencesRecur(int arr[], int n, int k, int index){ int i; if (k == 0) { printArray(arr, index); } if (k > 0) { for(i = 1; i<=n; ++i) { arr[index] = i; printSequencesRecur(arr, n, k-1, index+1); } }} /* A function that uses printSequencesRecur() to prints all sequences from 1, 1, ..1 to n, n, ..n */void printSequences(int n, int k){ int *arr = new int[k]; printSequencesRecur(arr, n, k, 0); delete(arr); // free dynamically allocated array return;} /* Driver Program to test above functions */int main(){ int n = 3; int k = 2; printSequences(n, k); return 0;}", "e": 15561, "s": 14582, "text": null }, { "code": "// Java program of above approach class GfG { /* A utility function that prints a given arr[] of length size*/static void printArray(int arr[], int size){ for(int i = 0; i < size; i++) System.out.print(arr[i] + \" \");System.out.println(); return;} /* The core function that recursively generates and prints all sequences oflength k */static void printSequencesRecur(int arr[], int n, int k, int index){int i;if (k == 0){ printArray(arr, index);}if (k > 0){ for(i = 1; i<=n; ++i) { arr[index] = i; printSequencesRecur(arr, n, k-1, index+1); }}} /* A function that uses printSequencesRecur() to prints all sequencesfrom 1, 1, ..1 to n, n, ..n */static void printSequences(int n, int k){ int arr[] = new int[k]; printSequencesRecur(arr, n, k, 0); return ;} /* Driver Program to test above functions */public static void main(String[] args){ int n = 3; int k = 2; printSequences(n, k);}}", "e": 16499, "s": 15561, "text": null }, { "code": "# Python3 program of above approach # A utility function that prints a# given arr[] of length sizedef printArray(arr, size): for i in range(size): print(arr[i], end = \" \"); print(\"\"); return; # The core function that recursively# generates and prints all sequences# of length kdef printSequencesRecur(arr, n, k, index): if (k == 0): printArray(arr, index); if (k > 0): for i in range(1, n + 1): arr[index] = i; printSequencesRecur(arr, n, k - 1, index + 1); # A function that uses printSequencesRecur() to# prints all sequences from 1, 1, ..1 to n, n, ..ndef printSequences(n, k): arr = [0] * n; printSequencesRecur(arr, n, k, 0); return; # Driver Coden = 3;k = 2;printSequences(n, k); # This code is contributed mits", "e": 17322, "s": 16499, "text": null }, { "code": "// C# program of above approachusing System; class GFG{ /* A utility function that prints a givenarr[] of length size*/static void printArray(int []arr, int size){ for(int i = 0; i < size; i++) Console.Write(arr[i] + \" \"); Console.WriteLine(); return;} /* The core function that recursively generatesand prints all sequences of length k */static void printSequencesRecur(int []arr, int n, int k, int index){ int i; if (k == 0) { printArray(arr, index); } if (k > 0) { for(i = 1; i<=n; ++i) { arr[index] = i; printSequencesRecur(arr, n, k - 1, index + 1); } }} /* A function that uses printSequencesRecur() toprints all sequences from 1, 1, ..1 to n, n, ..n */static void printSequences(int n, int k){ int[] arr = new int[k]; printSequencesRecur(arr, n, k, 0); return;} // Driver Codepublic static void Main(){ int n = 3; int k = 2; printSequences(n, k);}} // This code is contributed// by Akanksha Rai", "e": 18362, "s": 17322, "text": null }, { "code": "<?php// PHP program of above approach /* A utility function that prints agiven arr[] of length size*/function printArray($arr, $size){ for($i = 0; $i < $size; $i++) echo $arr[$i] . \" \"; echo \"\\n\"; return;} /* The core function that recursively generatesand prints all sequences of length k */function printSequencesRecur($arr, $n, $k, $index){ if ($k == 0) { printArray($arr, $index); } if ($k > 0) { for($i = 1; $i <= $n; ++$i) { $arr[$index] = $i; printSequencesRecur($arr, $n, $k - 1, $index + 1); } }} /* A function that uses printSequencesRecur() toprints all sequences from 1, 1, ..1 to n, n, ..n */function printSequences($n, $k){ $arr = array(); printSequencesRecur($arr, $n, $k, 0); return;} // Driver Code$n = 3;$k = 2;printSequences($n, $k); // This code is contributed// by Akanksha Rai?>", "e": 19289, "s": 18362, "text": null }, { "code": "<script>// javascript program of above approach /* A utility function that prints a given arr of length size*/function printArray(arr, size){ for(i = 0; i < size; i++) document.write(arr[i] + \" \"); document.write(\"<br>\"); return;} /* The core function that recursivelygenerates and prints all sequences oflength k */function printSequencesRecur(arr , n , k , index){ var i; if (k == 0) { printArray(arr, index); } if (k > 0) { for(i = 1; i <= n; ++i) { arr[index] = i; printSequencesRecur(arr, n, k - 1, index+1); } }} /* A function that uses printSequencesRecur()to prints all sequences from 1, 1, ..1 to n, n, ..n */function printSequences(n, k){ var arr = Array.from({length: k}, (_, i) => 0); printSequencesRecur(arr, n, k, 0); return ;} /* Driver Program to test above functions */var n = 3;var k = 2;printSequences(n, k); // This code is contributed by Amit Katiyar.</script>", "e": 20264, "s": 19289, "text": null }, { "code": null, "e": 20272, "s": 20264, "text": "Output:" }, { "code": null, "e": 20308, "s": 20272, "text": "1 1\n1 2\n1 3\n2 1\n2 2\n2 3\n3 1\n3 2\n3 3" }, { "code": null, "e": 20422, "s": 20308, "text": "Time Complexity: There are n^k sequences and printing a sequence takes O(k) time. So time complexity is O(k*n^k)." }, { "code": null, "e": 20645, "s": 20422, "text": "Auxiliary Space: O(k)Thanks to mopurizwarriors for suggesting above method. As suggested by alphayoung, we can avoid use of arrays for small sequences that can fit in an integer. Following is the implementation for same. " }, { "code": null, "e": 20649, "s": 20645, "text": "C++" }, { "code": null, "e": 20651, "s": 20649, "text": "C" }, { "code": null, "e": 20656, "s": 20651, "text": "Java" }, { "code": null, "e": 20664, "s": 20656, "text": "Python3" }, { "code": null, "e": 20667, "s": 20664, "text": "C#" }, { "code": null, "e": 20671, "s": 20667, "text": "PHP" }, { "code": null, "e": 20682, "s": 20671, "text": "Javascript" }, { "code": "// C++ program of above approach /* The core function that generates andprints all sequences of length k */void printSeqRecur(int num, int pos, int k, int n){ if (pos == k) { cout << num << endl; return; } for (int i = 1; i <= n; i++) { printSeqRecur(num * 10 + i, pos + 1, k, n); }} /* A function that uses printSequencesRecur()to prints all sequencesfrom 1, 1, ..1 to n, n, ..n */void printSequences(int k, int n){ printSeqRecur(0, 0, k, n);} // This code is contributed by SHUBHAMSINGH10", "e": 21215, "s": 20682, "text": null }, { "code": "// C program of above approach/* The core function that generates and prints all sequences of length k */void printSeqRecur(int num, int pos, int k, int n){ if (pos == k) { printf(\"%d \\n\", num); return; } for (int i = 1; i <= n; i++) { printSeqRecur(num * 10 + i, pos + 1, k, n); }} /* A function that uses printSequencesRecur() to prints all sequences from 1, 1, ..1 to n, n, ..n */void printSequences(int k, int n){ printSeqRecur(0, 0, k, n);}", "e": 21699, "s": 21215, "text": null }, { "code": "// Java program of above approach /* The core function that generates and prints all sequences of length k */static void printSeqRecur(int num, int pos, int k, int n){ if (pos == k) { System.out.print(num + \" \"); return; } for (int i = 1; i <= n; i++) { printSeqRecur(num * 10 + i, pos + 1, k, n); }} /* A function that uses printSequencesRecur() to prints all sequencesfrom 1, 1, ..1 to n, n, ..n */static void printSequences(int k, int n){ printSeqRecur(0, 0, k, n);}", "e": 22205, "s": 21699, "text": null }, { "code": "# Python program of above approach# We have used number instead of# arrays to prevent linear time# required to print each stringdef printSeqRecur ( num , n, k ): if n == 0: # if total digits become equal # to n, print the number and return print(num ) return for _ in range(1, k + 1): printSeqRecur (num * 10 + _, n - 1, k) # Driver Codeif __name__ == \"__main__\": k = 3 # length of k-ary string n = 2 # string can take values # from 1,2,3...n printSeqRecur(0, n, k) # This code is contributed# by shivam purohit", "e": 22786, "s": 22205, "text": null }, { "code": "// C# program of above approach /* The core function that generatesand prints all sequences of length k */static void printSeqRecur(int num, int pos, int k, int n){ if (pos == k) { Console.Write(num + \" \"); return; } for (int i = 1; i <= n; i++) { printSeqRecur(num * 10 + i, pos + 1, k, n); }} /* A function that uses printSequencesRecur()to prints all sequences from 1, 1, ..1 to n, n, ..n */static void printSequences(int k, int n){ printSeqRecur(0, 0, k, n);} // This code is contributed by Code_Mech", "e": 23360, "s": 22786, "text": null }, { "code": "<?php// PHP program of above approach// We have used number instead of// arrays to prevent linear time// required to print each stringfunction printSeqRecur ($num ,$n, $k){ if ($n == 0) { # if total digits become equal # to n, print the number and return print($num . \"\\n\"); return; } for ($i = 1; $i < $k + 1; $i++) printSeqRecur($num * 10 + $i, $n - 1, $k);} // Driver Code$k = 3; // length of k-ary string$n = 2; // string can take values // from 1,2,3...nprintSeqRecur(0, $n, $k); // This code is contributed mits?>", "e": 23964, "s": 23360, "text": null }, { "code": "<script> // Javascript program of above approach /* The core function that generates andprints all sequences of length k */function printSeqRecur( num, pos, k, n){ if (pos == k) { document.write( num + \"<br>\" ); return; } for (var i = 1; i <= n; i++) { printSeqRecur(num * 10 + i, pos + 1, k, n); }} /* A function that uses printSequencesRecur()to prints all sequencesfrom 1, 1, ..1 to n, n, ..n */function printSequences( k, n){ printSeqRecur(0, 0, k, n);} // This code is contributed by SoumikMondal</script>", "e": 24520, "s": 23964, "text": null }, { "code": null, "e": 24546, "s": 24520, "text": "Time Complexity: O(k*n^k)" }, { "code": null, "e": 24572, "s": 24546, "text": "Auxiliary Space: O(n * k)" }, { "code": null, "e": 24778, "s": 24572, "text": "References: Algorithms and Programming: Problems and Solutions by Alexander ShenPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 24795, "s": 24778, "text": "Shivam Purohit 2" }, { "code": null, "e": 24808, "s": 24795, "text": "prerna saini" }, { "code": null, "e": 24821, "s": 24808, "text": "Mithun Kumar" }, { "code": null, "e": 24834, "s": 24821, "text": "Akanksha_Rai" }, { "code": null, "e": 24844, "s": 24834, "text": "Code_Mech" }, { "code": null, "e": 24858, "s": 24844, "text": "princiraj1992" }, { "code": null, "e": 24868, "s": 24858, "text": "Rajput-Ji" }, { "code": null, "e": 24883, "s": 24868, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 24898, "s": 24883, "text": "amit143katiyar" }, { "code": null, "e": 24910, "s": 24898, "text": "29AjayKumar" }, { "code": null, "e": 24923, "s": 24910, "text": "SoumikMondal" }, { "code": null, "e": 24933, "s": 24923, "text": "subham348" }, { "code": null, "e": 24949, "s": 24933, "text": "subhammahato348" }, { "code": null, "e": 24968, "s": 24949, "text": "shivanisinghss2110" }, { "code": null, "e": 24980, "s": 24968, "text": "subsequence" }, { "code": null, "e": 24993, "s": 24980, "text": "Mathematical" }, { "code": null, "e": 25006, "s": 24993, "text": "Mathematical" }, { "code": null, "e": 25104, "s": 25006, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25128, "s": 25104, "text": "Merge two sorted arrays" }, { "code": null, "e": 25149, "s": 25128, "text": "Operators in C / C++" }, { "code": null, "e": 25171, "s": 25149, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 25185, "s": 25171, "text": "Prime Numbers" }, { "code": null, "e": 25227, "s": 25185, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 25280, "s": 25227, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 25317, "s": 25280, "text": "Minimum number of jumps to reach end" }, { "code": null, "e": 25349, "s": 25317, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 25392, "s": 25349, "text": "The Knight's tour problem | Backtracking-1" } ]
How to use External Modules and NPM in a project ?
17 Sep, 2021 Need for External Modules: For a large JavaScript application, it becomes difficult and messy to write the whole code in just one JavaScript file. This is where CommonJS comes into the picture and this CommonJS format defines a module format that can be used up for breaking your JS application into multiple files. Node.js adopts this CommonJS format for organizing our JS application into multiple files. Within this Node.js application, we have the module.exports property which is used to determine the export from the current module. Types of Node modules: Module in Node.js is a simple or complex functionality organized into single or multiple JS files which can be used again throughout the Node.js application. There are three types of Node.js modules: Local/File-based modules: It define the Node modules within a file in our application and is used within our application. Core modules: The core modules are inbuilt modules in Node.js. These modules provide sufficient functionality so that external module designers can add in their own functionality that can be used while developing Node applications. The core modules include path, file system, os, util, and a few others. Third-party modules: Third-party modules are the external Node modules. These are the third-party Node modules developed by Node developers that are made available through the Node ecosystem. But we need a package manager that maintains all the modules so that they can be accessed with ease. This is where NPM comes into the picture. NPM (Node Package Manager): NPM is the default package manager for JavaScript runtime environment in Node.js. The Node.js Package Manager (npm) is the default and most popular package manager in Node.js ecosystem that is primarily used to install and maintain external modules in Node.js application. Users can basically install the node modules needed for their application using npm. How to export Modules ? First, initialize a node.js application by typing in npm init in the command prompt/terminal (make sure you are present in the current project folder). It will create a package.json file.Use the following syntax to add a module in Node.js project. Syntax: var module = require("module_name"); Creating own modules and using it: First, initialize node in a directory by typing npm init in the command prompt/terminal. Creating a Node.js module (rectange.js): javascript module.exports = (length, breadth, callback) => { if (length <= 0 || breadth <= 0) setTimeout(() => callback(new Error( "Dimensions cannot be negative: length = " + length + ", and breadth = " + breadth), null), 5000); else setTimeout(() => callback(null, { Perimeter: () => (2*(length+breadth)), Area:() => (length*breadth) }), 5000);} Using the Node module in your application (module.js): javascript var rect = require('./rectangle');module.exports.Rect = function Rect(l, b) { rect(l, b, (err, rectangle) => { if (err) console.log("There is an ERROR!!: ", err.message); else { console.log("Area of rectangle with dimensions length = " + l + " and breadth = " + b + " : " + rectangle.Area()); console.log("Perimeter of the rectangle with dimensions length = " + l + " and breadth = " + b + " : " + rectangle.Perimeter()); } console.log("\n\n"); });}; Initializing the main file (index.js): javascript var rect = require("./module");rect.Rect(5, 2);rect.Rect(-1, 0);rect.Rect(12, 4);rect.Rect(8, 6);rect.Rect(3, 4); Output: simmytarika5 Node.js-Misc Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Node.js fs.writeFile() Method How to install the previous version of node.js and npm ? Difference between promise and async await in Node.js Mongoose | findByIdAndUpdate() Function Installation of Node.js on Windows Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Sep, 2021" }, { "code": null, "e": 792, "s": 28, "text": "Need for External Modules: For a large JavaScript application, it becomes difficult and messy to write the whole code in just one JavaScript file. This is where CommonJS comes into the picture and this CommonJS format defines a module format that can be used up for breaking your JS application into multiple files. Node.js adopts this CommonJS format for organizing our JS application into multiple files. Within this Node.js application, we have the module.exports property which is used to determine the export from the current module. Types of Node modules: Module in Node.js is a simple or complex functionality organized into single or multiple JS files which can be used again throughout the Node.js application. There are three types of Node.js modules: " }, { "code": null, "e": 914, "s": 792, "text": "Local/File-based modules: It define the Node modules within a file in our application and is used within our application." }, { "code": null, "e": 1218, "s": 914, "text": "Core modules: The core modules are inbuilt modules in Node.js. These modules provide sufficient functionality so that external module designers can add in their own functionality that can be used while developing Node applications. The core modules include path, file system, os, util, and a few others." }, { "code": null, "e": 1553, "s": 1218, "text": "Third-party modules: Third-party modules are the external Node modules. These are the third-party Node modules developed by Node developers that are made available through the Node ecosystem. But we need a package manager that maintains all the modules so that they can be accessed with ease. This is where NPM comes into the picture." }, { "code": null, "e": 2221, "s": 1553, "text": "NPM (Node Package Manager): NPM is the default package manager for JavaScript runtime environment in Node.js. The Node.js Package Manager (npm) is the default and most popular package manager in Node.js ecosystem that is primarily used to install and maintain external modules in Node.js application. Users can basically install the node modules needed for their application using npm. How to export Modules ? First, initialize a node.js application by typing in npm init in the command prompt/terminal (make sure you are present in the current project folder). It will create a package.json file.Use the following syntax to add a module in Node.js project. Syntax: " }, { "code": null, "e": 2258, "s": 2221, "text": "var module = require(\"module_name\");" }, { "code": null, "e": 2384, "s": 2258, "text": "Creating own modules and using it: First, initialize node in a directory by typing npm init in the command prompt/terminal. " }, { "code": null, "e": 2427, "s": 2384, "text": "Creating a Node.js module (rectange.js): " }, { "code": null, "e": 2438, "s": 2427, "text": "javascript" }, { "code": "module.exports = (length, breadth, callback) => { if (length <= 0 || breadth <= 0) setTimeout(() => callback(new Error( \"Dimensions cannot be negative: length = \" + length + \", and breadth = \" + breadth), null), 5000); else setTimeout(() => callback(null, { Perimeter: () => (2*(length+breadth)), Area:() => (length*breadth) }), 5000);}", "e": 2871, "s": 2438, "text": null }, { "code": null, "e": 2928, "s": 2871, "text": "Using the Node module in your application (module.js): " }, { "code": null, "e": 2939, "s": 2928, "text": "javascript" }, { "code": "var rect = require('./rectangle');module.exports.Rect = function Rect(l, b) { rect(l, b, (err, rectangle) => { if (err) console.log(\"There is an ERROR!!: \", err.message); else { console.log(\"Area of rectangle with dimensions length = \" + l + \" and breadth = \" + b + \" : \" + rectangle.Area()); console.log(\"Perimeter of the rectangle with dimensions length = \" + l + \" and breadth = \" + b + \" : \" + rectangle.Perimeter()); } console.log(\"\\n\\n\"); });};", "e": 3498, "s": 2939, "text": null }, { "code": null, "e": 3539, "s": 3498, "text": "Initializing the main file (index.js): " }, { "code": null, "e": 3550, "s": 3539, "text": "javascript" }, { "code": "var rect = require(\"./module\");rect.Rect(5, 2);rect.Rect(-1, 0);rect.Rect(12, 4);rect.Rect(8, 6);rect.Rect(3, 4);", "e": 3664, "s": 3550, "text": null }, { "code": null, "e": 3674, "s": 3664, "text": "Output: " }, { "code": null, "e": 3689, "s": 3676, "text": "simmytarika5" }, { "code": null, "e": 3702, "s": 3689, "text": "Node.js-Misc" }, { "code": null, "e": 3709, "s": 3702, "text": "Picked" }, { "code": null, "e": 3717, "s": 3709, "text": "Node.js" }, { "code": null, "e": 3734, "s": 3717, "text": "Web Technologies" }, { "code": null, "e": 3832, "s": 3734, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3862, "s": 3832, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 3919, "s": 3862, "text": "How to install the previous version of node.js and npm ?" }, { "code": null, "e": 3973, "s": 3919, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 4013, "s": 3973, "text": "Mongoose | findByIdAndUpdate() Function" }, { "code": null, "e": 4048, "s": 4013, "text": "Installation of Node.js on Windows" }, { "code": null, "e": 4110, "s": 4048, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4171, "s": 4110, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4221, "s": 4171, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 4264, "s": 4221, "text": "How to fetch data from an API in ReactJS ?" } ]
Primitive Wrapper Classes are Immutable in Java
12 Dec, 2021 In Java, an immutable class is a class (Integer, Byte, Long, Float, Double, Character, Boolean, and Short) which once created then its body can not be changed and the same applies to immutable objects which once created cannot be changed. Now the question arises that we do need the help of wrapper classes while dealing with primitive data types in Java where these classes are made immutable. Geeks, now you must be wondering why do we make them as immutable for which we will be listing some advantages as listed below as follows: They are automatically synchronized as their state them can not be altered by virtue of the definition of immutability. There are zero scopes of inconsistency as an object of the wrapper class can not be altered. It helps in caching as one instance of a specific type itself can facilitate dozen of applications. Tip: Best usage of wrapper classes as immutable objects is as keys of the Map. Example: Java // Java Program to Demonstrate that Primitive// Wrapper Classes are Immutable // Main classclass GFG { // Main driver method public static void main(String[] args) { // Getting an integer value Integer i = new Integer(12); // Printing the same integer value System.out.println(i); // Calling method 2 modify(i); // Now printing the value stored in above integer System.out.println(i); } // Method 2 // To modify integer value private static void modify(Integer i) { i = i + 1; }} Output: Output explanation: Here the parameter β€˜i’ is the reference in modifying and refers to the same object as β€˜i’ in main(), but changes made to β€˜i’ are not reflected in main() method. It is because all primitive wrapper classes (Integer, Byte, Long, Float, Double, Character, Boolean, and Short) are immutable in Java, so operations like addition and subtraction create a new object and not modify the old. The below line of code in the modify method is operating on wrapper class Integer, not an int, and does the following as described below as follows: i = i + 1; Unbox β€˜i’ to an int value Add 1 to that value Box the result into another Integer object Assign the resulting Integer to β€˜i’ (thus changing what object β€˜i’ references) Since object references are passed by value, the action taken in the modified method does not change i that was used as an argument in the call to modify. Thus the main routine still prints 12 after the method returns. This article is contributed by Yogesh D Doshi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. simmytarika5 solankimayank sweetyty java-wrapper-class Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Split() String method in Java with examples Arrays.sort() in Java with examples Reverse a string in Java Object Oriented Programming (OOPs) Concept in Java For-each loop in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples Stream In Java
[ { "code": null, "e": 52, "s": 24, "text": "\n12 Dec, 2021" }, { "code": null, "e": 448, "s": 52, "text": "In Java, an immutable class is a class (Integer, Byte, Long, Float, Double, Character, Boolean, and Short) which once created then its body can not be changed and the same applies to immutable objects which once created cannot be changed. Now the question arises that we do need the help of wrapper classes while dealing with primitive data types in Java where these classes are made immutable. " }, { "code": null, "e": 587, "s": 448, "text": "Geeks, now you must be wondering why do we make them as immutable for which we will be listing some advantages as listed below as follows:" }, { "code": null, "e": 707, "s": 587, "text": "They are automatically synchronized as their state them can not be altered by virtue of the definition of immutability." }, { "code": null, "e": 800, "s": 707, "text": "There are zero scopes of inconsistency as an object of the wrapper class can not be altered." }, { "code": null, "e": 900, "s": 800, "text": "It helps in caching as one instance of a specific type itself can facilitate dozen of applications." }, { "code": null, "e": 981, "s": 900, "text": "Tip: Best usage of wrapper classes as immutable objects is as keys of the Map. " }, { "code": null, "e": 990, "s": 981, "text": "Example:" }, { "code": null, "e": 995, "s": 990, "text": "Java" }, { "code": "// Java Program to Demonstrate that Primitive// Wrapper Classes are Immutable // Main classclass GFG { // Main driver method public static void main(String[] args) { // Getting an integer value Integer i = new Integer(12); // Printing the same integer value System.out.println(i); // Calling method 2 modify(i); // Now printing the value stored in above integer System.out.println(i); } // Method 2 // To modify integer value private static void modify(Integer i) { i = i + 1; }}", "e": 1558, "s": 995, "text": null }, { "code": null, "e": 1566, "s": 1558, "text": "Output:" }, { "code": null, "e": 1587, "s": 1566, "text": "Output explanation: " }, { "code": null, "e": 2120, "s": 1587, "text": "Here the parameter β€˜i’ is the reference in modifying and refers to the same object as β€˜i’ in main(), but changes made to β€˜i’ are not reflected in main() method. It is because all primitive wrapper classes (Integer, Byte, Long, Float, Double, Character, Boolean, and Short) are immutable in Java, so operations like addition and subtraction create a new object and not modify the old. The below line of code in the modify method is operating on wrapper class Integer, not an int, and does the following as described below as follows:" }, { "code": null, "e": 2131, "s": 2120, "text": "i = i + 1;" }, { "code": null, "e": 2157, "s": 2131, "text": "Unbox β€˜i’ to an int value" }, { "code": null, "e": 2177, "s": 2157, "text": "Add 1 to that value" }, { "code": null, "e": 2220, "s": 2177, "text": "Box the result into another Integer object" }, { "code": null, "e": 2299, "s": 2220, "text": "Assign the resulting Integer to β€˜i’ (thus changing what object β€˜i’ references)" }, { "code": null, "e": 2518, "s": 2299, "text": "Since object references are passed by value, the action taken in the modified method does not change i that was used as an argument in the call to modify. Thus the main routine still prints 12 after the method returns." }, { "code": null, "e": 2691, "s": 2518, "text": "This article is contributed by Yogesh D Doshi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 2704, "s": 2691, "text": "simmytarika5" }, { "code": null, "e": 2718, "s": 2704, "text": "solankimayank" }, { "code": null, "e": 2727, "s": 2718, "text": "sweetyty" }, { "code": null, "e": 2746, "s": 2727, "text": "java-wrapper-class" }, { "code": null, "e": 2751, "s": 2746, "text": "Java" }, { "code": null, "e": 2756, "s": 2751, "text": "Java" }, { "code": null, "e": 2854, "s": 2756, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2869, "s": 2854, "text": "Arrays in Java" }, { "code": null, "e": 2913, "s": 2869, "text": "Split() String method in Java with examples" }, { "code": null, "e": 2949, "s": 2913, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 2974, "s": 2949, "text": "Reverse a string in Java" }, { "code": null, "e": 3025, "s": 2974, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 3047, "s": 3025, "text": "For-each loop in Java" }, { "code": null, "e": 3078, "s": 3047, "text": "How to iterate any Map in Java" }, { "code": null, "e": 3097, "s": 3078, "text": "Interfaces in Java" }, { "code": null, "e": 3127, "s": 3097, "text": "HashMap in Java with Examples" } ]
Map of pairs in STL
18 Oct, 2017 Map in STL is used to hash key and value. We generally see map being used for standard data types. We can also use map for pairs. For example consider a simple problem, given a matrix and positions visited, print which positions are not visited. // C++ program to demonstrate use of map// for pairs#include <bits/stdc++.h>using namespace std; map<pair<int, int>, int> vis; // Print positions that are not marked// as visitedvoid printPositions(int a[3][3]){ for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) if (vis[{ i, j }] == 0) cout << "(" << i << ", " << j << ")" << "\n";} int main(){ int mat[3][3] = { { 0, 1, 2 }, { 3, 4, 5 }, { 6, 7, 8 } }; // Marking some positions as visited vis[{ 0, 0 }] = 1; // visit (0, 0) vis[{ 1, 0 }] = 1; // visit (1, 0) vis[{ 1, 1 }] = 1; // visit (1, 1) vis[{ 2, 2 }] = 1; // visit (2, 2) // print which positions in matrix are not visited by rat printPositions(mat); return 0;} Output: (0, 1) (0, 2) (1, 2) (2, 0) (2, 1) This article is contributed by Abhishek Rajput. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. cpp-pair 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": "\n18 Oct, 2017" }, { "code": null, "e": 182, "s": 52, "text": "Map in STL is used to hash key and value. We generally see map being used for standard data types. We can also use map for pairs." }, { "code": null, "e": 298, "s": 182, "text": "For example consider a simple problem, given a matrix and positions visited, print which positions are not visited." }, { "code": "// C++ program to demonstrate use of map// for pairs#include <bits/stdc++.h>using namespace std; map<pair<int, int>, int> vis; // Print positions that are not marked// as visitedvoid printPositions(int a[3][3]){ for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) if (vis[{ i, j }] == 0) cout << \"(\" << i << \", \" << j << \")\" << \"\\n\";} int main(){ int mat[3][3] = { { 0, 1, 2 }, { 3, 4, 5 }, { 6, 7, 8 } }; // Marking some positions as visited vis[{ 0, 0 }] = 1; // visit (0, 0) vis[{ 1, 0 }] = 1; // visit (1, 0) vis[{ 1, 1 }] = 1; // visit (1, 1) vis[{ 2, 2 }] = 1; // visit (2, 2) // print which positions in matrix are not visited by rat printPositions(mat); return 0;}", "e": 1065, "s": 298, "text": null }, { "code": null, "e": 1073, "s": 1065, "text": "Output:" }, { "code": null, "e": 1109, "s": 1073, "text": "(0, 1)\n(0, 2)\n(1, 2)\n(2, 0)\n(2, 1)\n" }, { "code": null, "e": 1412, "s": 1109, "text": "This article is contributed by Abhishek Rajput. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 1537, "s": 1412, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 1546, "s": 1537, "text": "cpp-pair" }, { "code": null, "e": 1550, "s": 1546, "text": "STL" }, { "code": null, "e": 1554, "s": 1550, "text": "C++" }, { "code": null, "e": 1558, "s": 1554, "text": "STL" }, { "code": null, "e": 1562, "s": 1558, "text": "CPP" } ]
C | Operators | Question 1
08 May, 2017 #include "stdio.h" int main() { int x, y = 5, z = 5; x = y == z; printf("%d", x); getchar(); return 0; } (A) 0(B) 1(C) 5(D) Compiler Error Answer: (B) Explanation: The crux of the question lies in the statement x = y==z. The operator == is executed before = because precedence of comparison operators (<=, >= and ==) is higher than assignment operator =.The result of a comparison operator is either 0 or 1 based on the comparison result. Since y is equal to z, value of the expression y == z becomes 1 and the value is assigned to x via the assignment operator. C Quiz Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C | Dynamic Memory Allocation | Question 5 C | Advanced Pointer | Question 9 C | File Handling | Question 5 C | Loops & Control Structure | Question 5 C | Advanced Pointer | Question 2 C | Advanced Pointer | Question 3 C | Advanced Pointer | Question 4 C | Pointer Basics | Question 7 C | File Handling | Question 3 C | Structure & Union | Question 2
[ { "code": null, "e": 52, "s": 24, "text": "\n08 May, 2017" }, { "code": null, "e": 178, "s": 52, "text": "#include \"stdio.h\"\nint main() \n{ \n int x, y = 5, z = 5; \n x = y == z; \n printf(\"%d\", x); \n \n getchar(); \n return 0; \n}\n" }, { "code": null, "e": 212, "s": 178, "text": "(A) 0(B) 1(C) 5(D) Compiler Error" }, { "code": null, "e": 224, "s": 212, "text": "Answer: (B)" }, { "code": null, "e": 638, "s": 226, "text": "Explanation: The crux of the question lies in the statement x = y==z. The operator == is executed before = because precedence of comparison operators (<=, >= and ==) is higher than assignment operator =.The result of a comparison operator is either 0 or 1 based on the comparison result. Since y is equal to z, value of the expression y == z becomes 1 and the value is assigned to x via the assignment operator." }, { "code": null, "e": 645, "s": 638, "text": "C Quiz" }, { "code": null, "e": 743, "s": 645, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 786, "s": 743, "text": "C | Dynamic Memory Allocation | Question 5" }, { "code": null, "e": 820, "s": 786, "text": "C | Advanced Pointer | Question 9" }, { "code": null, "e": 851, "s": 820, "text": "C | File Handling | Question 5" }, { "code": null, "e": 894, "s": 851, "text": "C | Loops & Control Structure | Question 5" }, { "code": null, "e": 928, "s": 894, "text": "C | Advanced Pointer | Question 2" }, { "code": null, "e": 962, "s": 928, "text": "C | Advanced Pointer | Question 3" }, { "code": null, "e": 996, "s": 962, "text": "C | Advanced Pointer | Question 4" }, { "code": null, "e": 1028, "s": 996, "text": "C | Pointer Basics | Question 7" }, { "code": null, "e": 1059, "s": 1028, "text": "C | File Handling | Question 3" } ]
Calendar set() Method in Java with Examples
21 Feb, 2019 The set(int calndr_field, int new_val) method in Calendar class is used to set the calndr_field value to a new_val. The older field of this calendar get replaced by a new field. Syntax: public void set(int calndr_field, int new_val) Parameters: The method takes two parameters: calndr_field: This is of Calendar type and refers to the field of the calendar that is to be altered. new_val: This refers to the new value that is to be replaced with. Return Value: The method does not return any value. Below programs illustrate the working of set() Method of Calendar class:Example 1: // Java code to illustrate// set() method import java.util.*;public class Calendar_Demo { public static void main(String args[]) { // Creating a calendar Calendar calndr = Calendar.getInstance(); // Displaying the month System.out.println("The Current Month is: " + calndr.get( Calendar.MONTH)); // Replacing with a new value calndr.set(Calendar.MONTH, 11); // Displaying the modified result System.out.println("Altered Month is: " + calndr.get( Calendar.MONTH)); }} The Current Month is: 1 Altered Month is: 11 Example 2: // Java code to illustrate// set() method import java.util.*;public class Calendar_Demo { public static void main(String args[]) { // Creating a calendar Calendar calndr = Calendar.getInstance(); // Displaying the Year System.out.println("The Current year is: " + calndr.get( Calendar.YEAR)); // Replacing with a new value calndr.set(Calendar.YEAR, 1996); // Displaying the modified result System.out.println("Altered year is: " + calndr.get( Calendar.YEAR)); }} The Current year is: 2019 Altered year is: 1996 Reference: https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html#set-int-int- Java - util package Java-Calendar Java-Functions Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples Stream In Java ArrayList in Java Collections in Java Singleton Class in Java Multidimensional Arrays in Java Set in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Feb, 2019" }, { "code": null, "e": 206, "s": 28, "text": "The set(int calndr_field, int new_val) method in Calendar class is used to set the calndr_field value to a new_val. The older field of this calendar get replaced by a new field." }, { "code": null, "e": 214, "s": 206, "text": "Syntax:" }, { "code": null, "e": 261, "s": 214, "text": "public void set(int calndr_field, int new_val)" }, { "code": null, "e": 306, "s": 261, "text": "Parameters: The method takes two parameters:" }, { "code": null, "e": 408, "s": 306, "text": "calndr_field: This is of Calendar type and refers to the field of the calendar that is to be altered." }, { "code": null, "e": 475, "s": 408, "text": "new_val: This refers to the new value that is to be replaced with." }, { "code": null, "e": 527, "s": 475, "text": "Return Value: The method does not return any value." }, { "code": null, "e": 610, "s": 527, "text": "Below programs illustrate the working of set() Method of Calendar class:Example 1:" }, { "code": "// Java code to illustrate// set() method import java.util.*;public class Calendar_Demo { public static void main(String args[]) { // Creating a calendar Calendar calndr = Calendar.getInstance(); // Displaying the month System.out.println(\"The Current Month is: \" + calndr.get( Calendar.MONTH)); // Replacing with a new value calndr.set(Calendar.MONTH, 11); // Displaying the modified result System.out.println(\"Altered Month is: \" + calndr.get( Calendar.MONTH)); }}", "e": 1267, "s": 610, "text": null }, { "code": null, "e": 1313, "s": 1267, "text": "The Current Month is: 1\nAltered Month is: 11\n" }, { "code": null, "e": 1324, "s": 1313, "text": "Example 2:" }, { "code": "// Java code to illustrate// set() method import java.util.*;public class Calendar_Demo { public static void main(String args[]) { // Creating a calendar Calendar calndr = Calendar.getInstance(); // Displaying the Year System.out.println(\"The Current year is: \" + calndr.get( Calendar.YEAR)); // Replacing with a new value calndr.set(Calendar.YEAR, 1996); // Displaying the modified result System.out.println(\"Altered year is: \" + calndr.get( Calendar.YEAR)); }}", "e": 1977, "s": 1324, "text": null }, { "code": null, "e": 2026, "s": 1977, "text": "The Current year is: 2019\nAltered year is: 1996\n" }, { "code": null, "e": 2116, "s": 2026, "text": "Reference: https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html#set-int-int-" }, { "code": null, "e": 2136, "s": 2116, "text": "Java - util package" }, { "code": null, "e": 2150, "s": 2136, "text": "Java-Calendar" }, { "code": null, "e": 2165, "s": 2150, "text": "Java-Functions" }, { "code": null, "e": 2170, "s": 2165, "text": "Java" }, { "code": null, "e": 2175, "s": 2170, "text": "Java" }, { "code": null, "e": 2273, "s": 2175, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2324, "s": 2273, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 2355, "s": 2324, "text": "How to iterate any Map in Java" }, { "code": null, "e": 2374, "s": 2355, "text": "Interfaces in Java" }, { "code": null, "e": 2404, "s": 2374, "text": "HashMap in Java with Examples" }, { "code": null, "e": 2419, "s": 2404, "text": "Stream In Java" }, { "code": null, "e": 2437, "s": 2419, "text": "ArrayList in Java" }, { "code": null, "e": 2457, "s": 2437, "text": "Collections in Java" }, { "code": null, "e": 2481, "s": 2457, "text": "Singleton Class in Java" }, { "code": null, "e": 2513, "s": 2481, "text": "Multidimensional Arrays in Java" } ]
Python – Multimode of List
10 Feb, 2020 Sometimes, while working with Python lists we can have a problem in which we need to find mode in list i.e most frequently occurring character. But sometimes, we can have more than 1 modes. This situation is called multimode. Lets discuss certain ways in which this task can be performed. Method #1 : Using loop + formulaThe simpler manner to approach this problem is to employ the formula for finding multimode and perform using loop shorthands. This is the most basic approach to solve this problem. # Python3 code to demonstrate working of # Multimode of List# using loop + formula import mathfrom collections import Counter # initialize list test_list = [1, 2, 1, 2, 3, 4, 3] # printing original list print("The original list is : " + str(test_list)) # Multimode of List# using loop + formula res = []test_list1 = Counter(test_list) temp = test_list1.most_common(1)[0][1] for ele in test_list: if test_list.count(ele) == temp: res.append(ele)res = list(set(res)) # printing result print("The multimode of list is : " + str(res)) The original list is : [1, 2, 1, 2, 3, 4, 3] The multimode of list is : [1, 2, 3] Method #2 : Using statistics.multimode()This task can also be performed using inbuilt function of mulimode(). This is new in Python versions >= 3.8. # Python3 code to demonstrate working of # Multimode of List# using statistics.multimode() import statistics # initialize list test_list = [1, 2, 1, 2, 3, 4, 3] # printing original list print("The original list is : " + str(test_list)) # Multimode of List# using statistics.multimode() res = statistics.multimode(test_list) # printing result print("The multimode of list is : " + str(res)) The original list is : [1, 2, 1, 2, 3, 4, 3] The multimode of list is : [1, 2, 3] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Feb, 2020" }, { "code": null, "e": 317, "s": 28, "text": "Sometimes, while working with Python lists we can have a problem in which we need to find mode in list i.e most frequently occurring character. But sometimes, we can have more than 1 modes. This situation is called multimode. Lets discuss certain ways in which this task can be performed." }, { "code": null, "e": 530, "s": 317, "text": "Method #1 : Using loop + formulaThe simpler manner to approach this problem is to employ the formula for finding multimode and perform using loop shorthands. This is the most basic approach to solve this problem." }, { "code": "# Python3 code to demonstrate working of # Multimode of List# using loop + formula import mathfrom collections import Counter # initialize list test_list = [1, 2, 1, 2, 3, 4, 3] # printing original list print(\"The original list is : \" + str(test_list)) # Multimode of List# using loop + formula res = []test_list1 = Counter(test_list) temp = test_list1.most_common(1)[0][1] for ele in test_list: if test_list.count(ele) == temp: res.append(ele)res = list(set(res)) # printing result print(\"The multimode of list is : \" + str(res)) ", "e": 1072, "s": 530, "text": null }, { "code": null, "e": 1155, "s": 1072, "text": "The original list is : [1, 2, 1, 2, 3, 4, 3]\nThe multimode of list is : [1, 2, 3]\n" }, { "code": null, "e": 1306, "s": 1157, "text": "Method #2 : Using statistics.multimode()This task can also be performed using inbuilt function of mulimode(). This is new in Python versions >= 3.8." }, { "code": "# Python3 code to demonstrate working of # Multimode of List# using statistics.multimode() import statistics # initialize list test_list = [1, 2, 1, 2, 3, 4, 3] # printing original list print(\"The original list is : \" + str(test_list)) # Multimode of List# using statistics.multimode() res = statistics.multimode(test_list) # printing result print(\"The multimode of list is : \" + str(res)) ", "e": 1705, "s": 1306, "text": null }, { "code": null, "e": 1788, "s": 1705, "text": "The original list is : [1, 2, 1, 2, 3, 4, 3]\nThe multimode of list is : [1, 2, 3]\n" }, { "code": null, "e": 1809, "s": 1788, "text": "Python list-programs" }, { "code": null, "e": 1816, "s": 1809, "text": "Python" }, { "code": null, "e": 1832, "s": 1816, "text": "Python Programs" }, { "code": null, "e": 1930, "s": 1832, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1962, "s": 1930, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1989, "s": 1962, "text": "Python Classes and Objects" }, { "code": null, "e": 2010, "s": 1989, "text": "Python OOPs Concepts" }, { "code": null, "e": 2041, "s": 2010, "text": "Python | os.path.join() method" }, { "code": null, "e": 2097, "s": 2041, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2119, "s": 2097, "text": "Defaultdict in Python" }, { "code": null, "e": 2158, "s": 2119, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2196, "s": 2158, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2245, "s": 2196, "text": "Python | Convert string dictionary to dictionary" } ]
Python Program to find Sum of Negative, Positive Even and Positive Odd numbers in a List
26 Nov, 2020 Given a list. The task is to find the sum of Negative, Positive Even, and Positive Odd numbers present in the List. Examples: Input: -7 5 60 -34 1 Output: Sum of negative numbers is -41 Sum of even positive numbers is 60 Sum of odd positive numbers is 6 Input: 1 -1 50 -2 0 -3 Output: Sum of negative numbers is -6 Sum of even positive numbers is 50 Sum of odd positive numbers is 1 Negative numbers are the numbers less than 0 while positive even numbers are numbers greater than 0 and also divisible by 2. 0 is assumed to be a positive even number, in this case. Approach: The first approach input a list of numbers from the user. Two loops are run, one for the positive numbers and the other for the negative numbers, computing the numbers’ summation. If n is the size of the list of numbers, it takes O(2n) time complexity, for iterating over the list of numbers twice. Python3 class Sumofnumbers: # find sum of negative numbers def negSum(self, list): # counter for sum of # negative numbers neg_sum = 0 for num in list: # converting number # to integer explicitly num = int(num) # if negative number if(num < 0): # simply add to the # negative sum neg_sum + = num print("Sum of negative numbers is ", neg_sum) # find sum of positive numbers # according to categories def posSum(self, list): # counter for sum of # positive even numbers pos_even_sum = 0 # counter for sum of # positive odd numbers pos_odd_sum = 0 for num in list: # converting number # to integer explicitly num = int(num) # if negative number if(num >= 0): # if even positive if(num % 2 == 0): # add to positive # even sum pos_even_sum + = num else: # add to positive odd sum pos_odd_sum + = num print("Sum of even positive numbers is ", pos_even_sum) print("Sum of odd positive numbers is ", pos_odd_sum) # input a list of numberslist_num = [-7, 5, 60, -34, 1] # creating an object of classobj = Sumofnumbers() # calling method for sum# of all negative numbersobj.negSum(list_num) # calling method for# sum of all positive numbersobj.posSum(list_num) Output: Sum of negative numbers is -41 Sum of even positive numbers is 60 Sum of odd positive numbers is 6 The second approach computes the sum of respective numbers in a single loop. It maintains three counters for each of the three conditions, checks the condition and accordingly adds the value of the number in the current sum . If n is the size of the list of numbers, it takes O(n) time complexity, for iterating over the list of numbers once. Python3 class Sumofnumbers: # find sum of numbers # according to categories def Sum(self, list): # counter for sum # of negative numbers neg_sum = 0 # counter for sum of # positive even numbers pos_even_sum = 0 # counter for sum of # positive odd numbers pos_odd_sum = 0 for num in list: # converting number # to integer explicitly num = int(num) # if negative number if(num < 0): # simply add # to the negative sum neg_sum += num # if positive number else: # if even positive if(num % 2 == 0): # add to positive even sum pos_even_sum + = num else: # add to positive odd sum pos_odd_sum + = num print("Sum of negative numbers is ", neg_sum) print("Sum of even positive numbers is ", pos_even_sum) print("Sum of odd positive numbers is ", pos_odd_sum) # input a list of numberslist_num = [1, -1, 50, -2, 0, -3] # creating an object of classobj = Sumofnumbers() # calling method for# largest sum of all numbersobj.Sum(list_num) Output: Sum of negative numbers is -6 Sum of even positive numbers is 50 Sum of odd positive numbers is 1 Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Nov, 2020" }, { "code": null, "e": 144, "s": 28, "text": "Given a list. The task is to find the sum of Negative, Positive Even, and Positive Odd numbers present in the List." }, { "code": null, "e": 154, "s": 144, "text": "Examples:" }, { "code": null, "e": 422, "s": 154, "text": "Input: -7 5 60 -34 1 \nOutput: \nSum of negative numbers is -41 \nSum of even positive numbers is 60 \nSum of odd positive numbers is 6\n\nInput: 1 -1 50 -2 0 -3\nOutput:\nSum of negative numbers is -6\nSum of even positive numbers is 50\nSum of odd positive numbers is 1" }, { "code": null, "e": 605, "s": 422, "text": "Negative numbers are the numbers less than 0 while positive even numbers are numbers greater than 0 and also divisible by 2. 0 is assumed to be a positive even number, in this case. " }, { "code": null, "e": 615, "s": 605, "text": "Approach:" }, { "code": null, "e": 673, "s": 615, "text": "The first approach input a list of numbers from the user." }, { "code": null, "e": 795, "s": 673, "text": "Two loops are run, one for the positive numbers and the other for the negative numbers, computing the numbers’ summation." }, { "code": null, "e": 836, "s": 795, "text": "If n is the size of the list of numbers," }, { "code": null, "e": 914, "s": 836, "text": "it takes O(2n) time complexity, for iterating over the list of numbers twice." }, { "code": null, "e": 922, "s": 914, "text": "Python3" }, { "code": "class Sumofnumbers: # find sum of negative numbers def negSum(self, list): # counter for sum of # negative numbers neg_sum = 0 for num in list: # converting number # to integer explicitly num = int(num) # if negative number if(num < 0): # simply add to the # negative sum neg_sum + = num print(\"Sum of negative numbers is \", neg_sum) # find sum of positive numbers # according to categories def posSum(self, list): # counter for sum of # positive even numbers pos_even_sum = 0 # counter for sum of # positive odd numbers pos_odd_sum = 0 for num in list: # converting number # to integer explicitly num = int(num) # if negative number if(num >= 0): # if even positive if(num % 2 == 0): # add to positive # even sum pos_even_sum + = num else: # add to positive odd sum pos_odd_sum + = num print(\"Sum of even positive numbers is \", pos_even_sum) print(\"Sum of odd positive numbers is \", pos_odd_sum) # input a list of numberslist_num = [-7, 5, 60, -34, 1] # creating an object of classobj = Sumofnumbers() # calling method for sum# of all negative numbersobj.negSum(list_num) # calling method for# sum of all positive numbersobj.posSum(list_num)", "e": 2542, "s": 922, "text": null }, { "code": null, "e": 2550, "s": 2542, "text": "Output:" }, { "code": null, "e": 2653, "s": 2550, "text": "Sum of negative numbers is -41\nSum of even positive numbers is 60\nSum of odd positive numbers is 6\n" }, { "code": null, "e": 2997, "s": 2653, "text": "The second approach computes the sum of respective numbers in a single loop. It maintains three counters for each of the three conditions, checks the condition and accordingly adds the value of the number in the current sum . If n is the size of the list of numbers, it takes O(n) time complexity, for iterating over the list of numbers once. " }, { "code": null, "e": 3005, "s": 2997, "text": "Python3" }, { "code": "class Sumofnumbers: # find sum of numbers # according to categories def Sum(self, list): # counter for sum # of negative numbers neg_sum = 0 # counter for sum of # positive even numbers pos_even_sum = 0 # counter for sum of # positive odd numbers pos_odd_sum = 0 for num in list: # converting number # to integer explicitly num = int(num) # if negative number if(num < 0): # simply add # to the negative sum neg_sum += num # if positive number else: # if even positive if(num % 2 == 0): # add to positive even sum pos_even_sum + = num else: # add to positive odd sum pos_odd_sum + = num print(\"Sum of negative numbers is \", neg_sum) print(\"Sum of even positive numbers is \", pos_even_sum) print(\"Sum of odd positive numbers is \", pos_odd_sum) # input a list of numberslist_num = [1, -1, 50, -2, 0, -3] # creating an object of classobj = Sumofnumbers() # calling method for# largest sum of all numbersobj.Sum(list_num)", "e": 4396, "s": 3005, "text": null }, { "code": null, "e": 4405, "s": 4396, "text": "Output: " }, { "code": null, "e": 4507, "s": 4405, "text": "Sum of negative numbers is -6\nSum of even positive numbers is 50\nSum of odd positive numbers is 1\n" }, { "code": null, "e": 4528, "s": 4507, "text": "Python list-programs" }, { "code": null, "e": 4535, "s": 4528, "text": "Python" }, { "code": null, "e": 4551, "s": 4535, "text": "Python Programs" } ]
Determine Period Index and Column for DataFrame in Pandas
11 Jun, 2021 In Pandas to determine Period Index and Column for Data Frame, we will use the pandas.period_range() method. It is one of the general functions in Pandas that is used to return a fixed frequency PeriodIndex, with day (calendar) as the default frequency. Syntax: pandas.to_numeric(arg, errors=’raise’, downcast=None) Parameters:start : Left bound for generating periodsend : Right bound for generating periodsperiods : Number of periods to generatefreq : Frequency aliasname : Name of the resulting PeriodIndex Returns: PeriodIndex Example 1: Python3 import pandas as pd course = ["DBMS", "DSA", "OOPS", "System Design", "CN", ] # pass the period and starting indexwebinar_date = pd.period_range('2020-08-15', periods=5) # Determine Period Index and Column# for DataFramedf = pd.DataFrame(course, index=webinar_date, columns=['Course']) df Output: Example 2: Python3 import pandas as pd day = ["Sun", "Mon", "Tue", "Wed", "Thurs", "Fri", "Sat"] # pass the period and starting indexdaycode = pd.period_range('2020-08-15', periods=7) # Determine Period Index and Column for DataFramedf = pd.DataFrame(day, index=daycode, columns=['day']) df Output: Example 3: Python3 import pandas as pd Team = ["Ind", "Pak", "Aus"] # pass the period and starting indexmatch_date = pd.period_range('2020-08-01', periods=3) # Determine Period Index and Column for DataFramedf = pd.DataFrame(Team, index=match_date, columns=['Team']) df Output: khushboogoyal499 Python Pandas-exercise Python pandas-general-functions Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n11 Jun, 2021" }, { "code": null, "e": 308, "s": 54, "text": "In Pandas to determine Period Index and Column for Data Frame, we will use the pandas.period_range() method. It is one of the general functions in Pandas that is used to return a fixed frequency PeriodIndex, with day (calendar) as the default frequency." }, { "code": null, "e": 370, "s": 308, "text": "Syntax: pandas.to_numeric(arg, errors=’raise’, downcast=None)" }, { "code": null, "e": 564, "s": 370, "text": "Parameters:start : Left bound for generating periodsend : Right bound for generating periodsperiods : Number of periods to generatefreq : Frequency aliasname : Name of the resulting PeriodIndex" }, { "code": null, "e": 585, "s": 564, "text": "Returns: PeriodIndex" }, { "code": null, "e": 596, "s": 585, "text": "Example 1:" }, { "code": null, "e": 604, "s": 596, "text": "Python3" }, { "code": "import pandas as pd course = [\"DBMS\", \"DSA\", \"OOPS\", \"System Design\", \"CN\", ] # pass the period and starting indexwebinar_date = pd.period_range('2020-08-15', periods=5) # Determine Period Index and Column# for DataFramedf = pd.DataFrame(course, index=webinar_date, columns=['Course']) df", "e": 904, "s": 604, "text": null }, { "code": null, "e": 916, "s": 908, "text": "Output:" }, { "code": null, "e": 931, "s": 920, "text": "Example 2:" }, { "code": null, "e": 941, "s": 933, "text": "Python3" }, { "code": "import pandas as pd day = [\"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thurs\", \"Fri\", \"Sat\"] # pass the period and starting indexdaycode = pd.period_range('2020-08-15', periods=7) # Determine Period Index and Column for DataFramedf = pd.DataFrame(day, index=daycode, columns=['day']) df", "e": 1219, "s": 941, "text": null }, { "code": null, "e": 1231, "s": 1223, "text": "Output:" }, { "code": null, "e": 1246, "s": 1235, "text": "Example 3:" }, { "code": null, "e": 1256, "s": 1248, "text": "Python3" }, { "code": "import pandas as pd Team = [\"Ind\", \"Pak\", \"Aus\"] # pass the period and starting indexmatch_date = pd.period_range('2020-08-01', periods=3) # Determine Period Index and Column for DataFramedf = pd.DataFrame(Team, index=match_date, columns=['Team']) df", "e": 1507, "s": 1256, "text": null }, { "code": null, "e": 1519, "s": 1511, "text": "Output:" }, { "code": null, "e": 1540, "s": 1523, "text": "khushboogoyal499" }, { "code": null, "e": 1563, "s": 1540, "text": "Python Pandas-exercise" }, { "code": null, "e": 1595, "s": 1563, "text": "Python pandas-general-functions" }, { "code": null, "e": 1609, "s": 1595, "text": "Python-pandas" }, { "code": null, "e": 1616, "s": 1609, "text": "Python" } ]
How to insert element to arraylist for listview in Android?
This example demonstrate about How to insert element to arraylist for listview 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"?> <LinearLayoutxmlns:android = "http://schemas.android.com/apk/res/android" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = ".MainActivity" android:orientation = "vertical"> <EditText android:id = "@+id/name" android:layout_width = "match_parent" android:hint = "Enter Name" android:layout_height = "wrap_content" /> <LinearLayout android:layout_width = "wrap_content" android:layout_height = "wrap_content"> <Button android:id = "@+id/save" android:text = "Save" android:layout_width = "wrap_content" android:layout_height = "wrap_content" /> <Button android:id = "@+id/refresh" android:text = "Refresh" android:layout_width = "wrap_content" android:layout_height = "wrap_content" /> </LinearLayout> <ListView android:id = "@+id/listView" android:layout_width = "match_parent" android:layout_height = "wrap_content"> </ListView> </LinearLayout> In the above code, we have taken name as Edit text, when user click on save button it will store the data into arraylist. Click on refresh button to get the changes of listview. 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.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; public class MainActivityextends AppCompatActivity { Button save, refresh; EditTextname; ArrayAdapterarrayAdapter; private ListViewlistView; ArrayListarray_list; @Override protected void onCreate(Bundle readdInstanceState) { super.onCreate(readdInstanceState); setContentView(R.layout.activity_main); array_list = new ArrayList(); name = findViewById(R.id.name); listView = findViewById(R.id.listView); findViewById(R.id.refresh).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { arrayAdapter.notifyDataSetChanged(); listView.invalidateViews(); listView.refreshDrawableState(); } }); findViewById(R.id.save).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!name.getText().toString().isEmpty()) { array_list.add(name.getText().toString()); arrayAdapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, array_list); listView.setAdapter(arrayAdapter); Toast.makeText(MainActivity.this, "Inserted", Toast.LENGTH_LONG).show(); } else { name.setError("Enter NAME"); } } }); } } 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, we are inserting name into arraylist and displaying name in listview. Click here to download the project code
[ { "code": null, "e": 1152, "s": 1062, "text": "This example demonstrate about How to insert element to arraylist for listview in Android" }, { "code": null, "e": 1281, "s": 1152, "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": 1346, "s": 1281, "text": "Step 2 βˆ’ Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2495, "s": 1346, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayoutxmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\"\n android:orientation = \"vertical\">\n <EditText\n android:id = \"@+id/name\"\n android:layout_width = \"match_parent\"\n android:hint = \"Enter Name\"\n android:layout_height = \"wrap_content\" />\n <LinearLayout\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\">\n <Button\n android:id = \"@+id/save\"\n android:text = \"Save\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\" />\n <Button\n android:id = \"@+id/refresh\"\n android:text = \"Refresh\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\" />\n </LinearLayout>\n <ListView\n android:id = \"@+id/listView\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\">\n </ListView>\n</LinearLayout>" }, { "code": null, "e": 2673, "s": 2495, "text": "In the above code, we have taken name as Edit text, when user click on save button it will store the data into arraylist. Click on refresh button to get the changes of listview." }, { "code": null, "e": 2730, "s": 2673, "text": "Step 3 βˆ’ Add the following code to src/MainActivity.java" }, { "code": null, "e": 4417, "s": 2730, "text": "package com.example.andy.myapplication;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.ListView;\nimport android.widget.Toast;\nimport java.util.ArrayList;\npublic class MainActivityextends AppCompatActivity {\n Button save, refresh;\n EditTextname;\n ArrayAdapterarrayAdapter;\n private ListViewlistView;\n ArrayListarray_list;\n @Override\n protected void onCreate(Bundle readdInstanceState) {\n super.onCreate(readdInstanceState);\n setContentView(R.layout.activity_main);\n array_list = new ArrayList();\n name = findViewById(R.id.name);\n listView = findViewById(R.id.listView);\n findViewById(R.id.refresh).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n arrayAdapter.notifyDataSetChanged();\n listView.invalidateViews();\n listView.refreshDrawableState();\n }\n });\n findViewById(R.id.save).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (!name.getText().toString().isEmpty()) {\n array_list.add(name.getText().toString());\n arrayAdapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, array_list);\n listView.setAdapter(arrayAdapter);\n Toast.makeText(MainActivity.this, \"Inserted\", Toast.LENGTH_LONG).show();\n } else {\n name.setError(\"Enter NAME\");\n }\n }\n });\n }\n}" }, { "code": null, "e": 4764, "s": 4417, "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": 4855, "s": 4764, "text": "In the above result, we are inserting name into arraylist and displaying name in listview." }, { "code": null, "e": 4897, "s": 4855, "text": "Click here to download the project code" } ]
Visualize sinusoidal waves using Python - GeeksforGeeks
16 Sep, 2021 Sinusoidal waves are the most basic trigonometric periodic curves, which is also known as the sine curve. Here we will see how sine function is related to a circle. Even though the sine function is a trigonometric function, it has more to do with a circle rather than a triangle. Consider a simple equation of a circle: where r is the radius of the circle with center at origin (0,0) as shown in the figure below. Sine is nothing but the measurement of the y-displacement from the origin as the angle increases as shown in the figure below: We can visualize this definition of sine using python and the pygame module. Pygame is an open-source python package that is mainly used for creating video games. Create a circle with radius r. Draw the radius of the circle. The endpoints of the radius will be (0,0) and (r*cos a, r*sin a), where the point (r*cos a, r*sin a) will always be of the circle. Draw the sine curve Then draw a line that will join the starting point of the sine wave and the endpoint of the radius of the circle. The length is called the gap for sake of simplicity. Note: Here, the position of radius means the position of the head of the radius of the circle. Abs Draw a circle and animate its radius such that the endpoint of the radius will cover all the points on the circumference of the circle. This can be done using an infinite while loop and drawing a line from the center of the circle to (r* cos t,r*sin t). Then declare a list Ys to store all the r*sin t values at the beginning of the list. This will basically keep a track of all the r*sin t values from the initial position of the radius till its current new position. These values will be used later to show the sine curve. Create a for loop to loop through the elements of Ys and then draw a circle of radius 1 and width 1, with abscissa starting from 0 to len(Ys) and ordinate will be the corresponding Ys values i.e, Ys[i], where index i ∈ [0, len(Ys)-1]. The abscissa needs to be shifted by a certain amount enough to make the animation tidy. In the animation, the gap is shown by a black line that can be increased or decreased by the user. Python3 import numpy as npimport pygamefrom pygame.locals import * class trig: # to collect all the ordinates Ys = [] def __init__(self, width=1600, height=900, gap=100, fps=60, radius=100): # width of the window self.width = width # height of the window self.height = height # frame rate per second self.fps = fps self.screen = pygame.display.set_mode((self.width, self.height)) # setting the screen dimensions self.clock = pygame.time.Clock() # the distance between the radius self.gap = gap # pointer and the starting point of the curve # the will be the x axis self.t = 0 # length of the radius of the circle self.r = radius self.run = True while self.run: self.clock.tick(self.fps) # filling the whole canvas with white background self.screen.fill('white') for event in pygame.event.get(): if event.type == pygame.QUIT: self.run = False if event.type == KEYDOWN: if event.key == K_ESCAPE: pygame.quit() # center of the circle x, y = 400, 400 x += (self.r * np.cos(self.t)) y += (self.r * np.sin(self.t)) pygame.draw.line(self.screen, 'grey', (400, 400), (400+1000, 400), 3) # this will create a horizontal line pygame.draw.line(self.screen, 'grey', (400, 400 + self.r), (400+1000, 400+self.r), 3) # this will create a horizontal line above the circle pygame.draw.line(self.screen, 'grey', (400, 400 - self.r), (400+1000, 400-self.r), 3) # this will create a horizontal # line below the circle pygame.draw.circle(self.screen, 'blue', (400, 400), self.r, 5) # this will create a circle # with center (400,400) pygame.draw.line(self.screen, 'green', (400, 400), (x, y), 3) # this will draw the radius of the circle # inserting the y values # at the beginning of the Ys list self.Ys.insert(0, y) if len(self.Ys) > 1100 - self.gap: self.Ys.pop() # this will restrict the length # of the Ys to a certain limit # so that the animation # doesn't get out of the screen pygame.draw.line(self.screen, 'black', (x, y), (400+self.gap, self.Ys[0]), 3) # this will create the joining line # between the curve and the circle's radius for i in range(len(self.Ys)): pygame.draw.circle(self.screen, 'red', (i+400+self.gap, self.Ys[i]), 1, 1) # this will create the sin curve # it will create bunch of small circles # with varying centers in such a # way that it will trajectory of # the centers of all those small circles # will give rise to a sine curve if event.type == KEYDOWN: if event.key == K_RIGHT: self.gap += 1 if event.key == K_LEFT: self.gap -= 1 # this part of code gives the user # the freedom to set the speed of the # animation and also set the gap # between the circle and the sine curve self.t += 0.01 pygame.display.update() if __name__ == '__main__': sin = trig() pygame.quit() Output: Note: Use left and right arrows to decrease or increase the gap between the circle and the sine curve. Use ECS to exit the window or QUIT. adnanirshad158 Blogathon-2021 Python-PyGame Blogathon Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Create a Table With Multiple Foreign Keys in SQL? How to Import JSON Data into SQL Server? Stratified Sampling in Pandas How to pass data into table from a form using React Components SQL Query to Convert Datetime to Date 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": 26207, "s": 26179, "text": "\n16 Sep, 2021" }, { "code": null, "e": 26488, "s": 26207, "text": "Sinusoidal waves are the most basic trigonometric periodic curves, which is also known as the sine curve. Here we will see how sine function is related to a circle. Even though the sine function is a trigonometric function, it has more to do with a circle rather than a triangle. " }, { "code": null, "e": 26528, "s": 26488, "text": "Consider a simple equation of a circle:" }, { "code": null, "e": 26622, "s": 26528, "text": "where r is the radius of the circle with center at origin (0,0) as shown in the figure below." }, { "code": null, "e": 26749, "s": 26622, "text": "Sine is nothing but the measurement of the y-displacement from the origin as the angle increases as shown in the figure below:" }, { "code": null, "e": 26912, "s": 26749, "text": "We can visualize this definition of sine using python and the pygame module. Pygame is an open-source python package that is mainly used for creating video games." }, { "code": null, "e": 26943, "s": 26912, "text": "Create a circle with radius r." }, { "code": null, "e": 27105, "s": 26943, "text": "Draw the radius of the circle. The endpoints of the radius will be (0,0) and (r*cos a, r*sin a), where the point (r*cos a, r*sin a) will always be of the circle." }, { "code": null, "e": 27125, "s": 27105, "text": "Draw the sine curve" }, { "code": null, "e": 27292, "s": 27125, "text": "Then draw a line that will join the starting point of the sine wave and the endpoint of the radius of the circle. The length is called the gap for sake of simplicity." }, { "code": null, "e": 27391, "s": 27292, "text": "Note: Here, the position of radius means the position of the head of the radius of the circle. Abs" }, { "code": null, "e": 27730, "s": 27391, "text": "Draw a circle and animate its radius such that the endpoint of the radius will cover all the points on the circumference of the circle. This can be done using an infinite while loop and drawing a line from the center of the circle to (r* cos t,r*sin t). Then declare a list Ys to store all the r*sin t values at the beginning of the list." }, { "code": null, "e": 28240, "s": 27730, "text": "This will basically keep a track of all the r*sin t values from the initial position of the radius till its current new position. These values will be used later to show the sine curve. Create a for loop to loop through the elements of Ys and then draw a circle of radius 1 and width 1, with abscissa starting from 0 to len(Ys) and ordinate will be the corresponding Ys values i.e, Ys[i], where index i ∈ [0, len(Ys)-1]. The abscissa needs to be shifted by a certain amount enough to make the animation tidy." }, { "code": null, "e": 28339, "s": 28240, "text": "In the animation, the gap is shown by a black line that can be increased or decreased by the user." }, { "code": null, "e": 28347, "s": 28339, "text": "Python3" }, { "code": "import numpy as npimport pygamefrom pygame.locals import * class trig: # to collect all the ordinates Ys = [] def __init__(self, width=1600, height=900, gap=100, fps=60, radius=100): # width of the window self.width = width # height of the window self.height = height # frame rate per second self.fps = fps self.screen = pygame.display.set_mode((self.width, self.height)) # setting the screen dimensions self.clock = pygame.time.Clock() # the distance between the radius self.gap = gap # pointer and the starting point of the curve # the will be the x axis self.t = 0 # length of the radius of the circle self.r = radius self.run = True while self.run: self.clock.tick(self.fps) # filling the whole canvas with white background self.screen.fill('white') for event in pygame.event.get(): if event.type == pygame.QUIT: self.run = False if event.type == KEYDOWN: if event.key == K_ESCAPE: pygame.quit() # center of the circle x, y = 400, 400 x += (self.r * np.cos(self.t)) y += (self.r * np.sin(self.t)) pygame.draw.line(self.screen, 'grey', (400, 400), (400+1000, 400), 3) # this will create a horizontal line pygame.draw.line(self.screen, 'grey', (400, 400 + self.r), (400+1000, 400+self.r), 3) # this will create a horizontal line above the circle pygame.draw.line(self.screen, 'grey', (400, 400 - self.r), (400+1000, 400-self.r), 3) # this will create a horizontal # line below the circle pygame.draw.circle(self.screen, 'blue', (400, 400), self.r, 5) # this will create a circle # with center (400,400) pygame.draw.line(self.screen, 'green', (400, 400), (x, y), 3) # this will draw the radius of the circle # inserting the y values # at the beginning of the Ys list self.Ys.insert(0, y) if len(self.Ys) > 1100 - self.gap: self.Ys.pop() # this will restrict the length # of the Ys to a certain limit # so that the animation # doesn't get out of the screen pygame.draw.line(self.screen, 'black', (x, y), (400+self.gap, self.Ys[0]), 3) # this will create the joining line # between the curve and the circle's radius for i in range(len(self.Ys)): pygame.draw.circle(self.screen, 'red', (i+400+self.gap, self.Ys[i]), 1, 1) # this will create the sin curve # it will create bunch of small circles # with varying centers in such a # way that it will trajectory of # the centers of all those small circles # will give rise to a sine curve if event.type == KEYDOWN: if event.key == K_RIGHT: self.gap += 1 if event.key == K_LEFT: self.gap -= 1 # this part of code gives the user # the freedom to set the speed of the # animation and also set the gap # between the circle and the sine curve self.t += 0.01 pygame.display.update() if __name__ == '__main__': sin = trig() pygame.quit()", "e": 32446, "s": 28347, "text": null }, { "code": null, "e": 32454, "s": 32446, "text": "Output:" }, { "code": null, "e": 32595, "s": 32454, "text": "Note: Use left and right arrows to decrease or increase the gap between the circle and the sine curve. Use ECS to exit the window or QUIT." }, { "code": null, "e": 32610, "s": 32595, "text": "adnanirshad158" }, { "code": null, "e": 32625, "s": 32610, "text": "Blogathon-2021" }, { "code": null, "e": 32639, "s": 32625, "text": "Python-PyGame" }, { "code": null, "e": 32649, "s": 32639, "text": "Blogathon" }, { "code": null, "e": 32656, "s": 32649, "text": "Python" }, { "code": null, "e": 32754, "s": 32656, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32811, "s": 32754, "text": "How to Create a Table With Multiple Foreign Keys in SQL?" }, { "code": null, "e": 32852, "s": 32811, "text": "How to Import JSON Data into SQL Server?" }, { "code": null, "e": 32882, "s": 32852, "text": "Stratified Sampling in Pandas" }, { "code": null, "e": 32945, "s": 32882, "text": "How to pass data into table from a form using React Components" }, { "code": null, "e": 32983, "s": 32945, "text": "SQL Query to Convert Datetime to Date" }, { "code": null, "e": 33011, "s": 32983, "text": "Read JSON file using Python" }, { "code": null, "e": 33061, "s": 33011, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 33083, "s": 33061, "text": "Python map() function" } ]
Conditioning Plot - GeeksforGeeks
24 Sep, 2021 A conditioning plot or co-plot or subset plot is a scatter plot of two variables when conditioned on a third variable. The third variable is called the conditioning variable. This variable can have both values either continuous or categorical. In the continuous variable, we created subsets by dividing them into a smaller range of values. In categorical variables, the subsets are created based on different categories. Let’s take three variables X, Y and Z. Z be the variable which we divided into the k groups. Here, there are many ways in which a group can be formed such as: By dividing the data into equal size of k groups. By dividing the data into different clusters on the basis of scatter plot. By dividing the range of data points into equal values. The categorical data have natural grouping on the basis of different categories of the dataframe. Then, we plot n rows and m columns matrix where n*m >= k. Each set of (row, column) represents an individual scatter plot, in which each scatters plot consists of the following components. Vertical Axis: Variable Y Horizontal Axis: Variable X where, points in the group corresponding to row i and column j are used. The conditioning plot provides the answer to the following questions: Is there any relationship between the two variables? If there is a relationship then, does the nature of the relationship depend upon the third variable? Do different groups in the data behave similarly? Are there any outliers in the data? Python3 # code% matplotlib inlineimport numpy as npimport seaborn as snsimport matplotlib.pyplot as pltimport pandas as pd # load training file for titanic datasettitanic_dataset =pd.read_csv('train.csv') # head of datasettitanic_dataset.head() # conditioning plot on the basis of categorical variablessns.lmplot(x='Age', y ='Fare',hue='Survived', col ='Sex',data=titanic_dataset)sns.lmplot(x='Age', y ='Fare',hue='Survived', col ='Pclass',data=titanic_dataset) # conditioning plot on the basis of continuous variablesdf1, df2 = titanic_dataset.loc[titanic_dataset['Age'] < 20 ] , titanic_dataset.loc[titanic_dataset['Age'] >= 20 ] lm = sns.lmplot(x='Parch', y ='Fare',hue='Survived',data=df1)ax1 =lm.axesax1=plt.gca()ax1.set_title('Age < 20') lm_2 = sns.lmplot(x='Parch', y ='Fare',hue='Survived',data=df2) ax2 =lm_2.axesax2=plt.gca()ax2.set_title('Age >= 20') Conditional Plot on the basis of Sex Conditional Plot on the basis of Passenger_Class Conditional Plot on the basis of Age NIST handbook sagar0719kumar anikaseth98 ML-Statistics Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Linear Regression Activation functions in Neural Networks Python | Decision tree implementation Support Vector Machine Algorithm ML | Underfitting and Overfitting Read JSON file using Python Python map() function How to get column names in Pandas dataframe Python Dictionary Taking input in Python
[ { "code": null, "e": 26095, "s": 26067, "text": "\n24 Sep, 2021" }, { "code": null, "e": 26516, "s": 26095, "text": "A conditioning plot or co-plot or subset plot is a scatter plot of two variables when conditioned on a third variable. The third variable is called the conditioning variable. This variable can have both values either continuous or categorical. In the continuous variable, we created subsets by dividing them into a smaller range of values. In categorical variables, the subsets are created based on different categories." }, { "code": null, "e": 26675, "s": 26516, "text": "Let’s take three variables X, Y and Z. Z be the variable which we divided into the k groups. Here, there are many ways in which a group can be formed such as:" }, { "code": null, "e": 26725, "s": 26675, "text": "By dividing the data into equal size of k groups." }, { "code": null, "e": 26800, "s": 26725, "text": "By dividing the data into different clusters on the basis of scatter plot." }, { "code": null, "e": 26856, "s": 26800, "text": "By dividing the range of data points into equal values." }, { "code": null, "e": 26954, "s": 26856, "text": "The categorical data have natural grouping on the basis of different categories of the dataframe." }, { "code": null, "e": 27143, "s": 26954, "text": "Then, we plot n rows and m columns matrix where n*m >= k. Each set of (row, column) represents an individual scatter plot, in which each scatters plot consists of the following components." }, { "code": null, "e": 27169, "s": 27143, "text": "Vertical Axis: Variable Y" }, { "code": null, "e": 27197, "s": 27169, "text": "Horizontal Axis: Variable X" }, { "code": null, "e": 27271, "s": 27197, "text": "where, points in the group corresponding to row i and column j are used. " }, { "code": null, "e": 27341, "s": 27271, "text": "The conditioning plot provides the answer to the following questions:" }, { "code": null, "e": 27394, "s": 27341, "text": "Is there any relationship between the two variables?" }, { "code": null, "e": 27495, "s": 27394, "text": "If there is a relationship then, does the nature of the relationship depend upon the third variable?" }, { "code": null, "e": 27545, "s": 27495, "text": "Do different groups in the data behave similarly?" }, { "code": null, "e": 27581, "s": 27545, "text": "Are there any outliers in the data?" }, { "code": null, "e": 27589, "s": 27581, "text": "Python3" }, { "code": "# code% matplotlib inlineimport numpy as npimport seaborn as snsimport matplotlib.pyplot as pltimport pandas as pd # load training file for titanic datasettitanic_dataset =pd.read_csv('train.csv') # head of datasettitanic_dataset.head() # conditioning plot on the basis of categorical variablessns.lmplot(x='Age', y ='Fare',hue='Survived', col ='Sex',data=titanic_dataset)sns.lmplot(x='Age', y ='Fare',hue='Survived', col ='Pclass',data=titanic_dataset) # conditioning plot on the basis of continuous variablesdf1, df2 = titanic_dataset.loc[titanic_dataset['Age'] < 20 ] , titanic_dataset.loc[titanic_dataset['Age'] >= 20 ] lm = sns.lmplot(x='Parch', y ='Fare',hue='Survived',data=df1)ax1 =lm.axesax1=plt.gca()ax1.set_title('Age < 20') lm_2 = sns.lmplot(x='Parch', y ='Fare',hue='Survived',data=df2) ax2 =lm_2.axesax2=plt.gca()ax2.set_title('Age >= 20')", "e": 28447, "s": 27589, "text": null }, { "code": null, "e": 28484, "s": 28447, "text": "Conditional Plot on the basis of Sex" }, { "code": null, "e": 28533, "s": 28484, "text": "Conditional Plot on the basis of Passenger_Class" }, { "code": null, "e": 28570, "s": 28533, "text": "Conditional Plot on the basis of Age" }, { "code": null, "e": 28584, "s": 28570, "text": "NIST handbook" }, { "code": null, "e": 28599, "s": 28584, "text": "sagar0719kumar" }, { "code": null, "e": 28611, "s": 28599, "text": "anikaseth98" }, { "code": null, "e": 28625, "s": 28611, "text": "ML-Statistics" }, { "code": null, "e": 28642, "s": 28625, "text": "Machine Learning" }, { "code": null, "e": 28649, "s": 28642, "text": "Python" }, { "code": null, "e": 28666, "s": 28649, "text": "Machine Learning" }, { "code": null, "e": 28764, "s": 28666, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28787, "s": 28764, "text": "ML | Linear Regression" }, { "code": null, "e": 28827, "s": 28787, "text": "Activation functions in Neural Networks" }, { "code": null, "e": 28865, "s": 28827, "text": "Python | Decision tree implementation" }, { "code": null, "e": 28898, "s": 28865, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 28932, "s": 28898, "text": "ML | Underfitting and Overfitting" }, { "code": null, "e": 28960, "s": 28932, "text": "Read JSON file using Python" }, { "code": null, "e": 28982, "s": 28960, "text": "Python map() function" }, { "code": null, "e": 29026, "s": 28982, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 29044, "s": 29026, "text": "Python Dictionary" } ]