title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Effortless Exploratory Data Analysis (EDA) | by Raj Sangani | Towards Data Science
Before we jump to model building, understanding the data at hand is essential. Analysing the data alone can give us valuable insights to solve our problems. Moreover understanding data is very useful to determine which features would help our model, which features can be done away with , how can we deal with missing values & correlations and so on. Building a model after considering all these factors will ensure that it is robust & can be generalised well. Since the data science pipeline from EDA to model prototyping is somewhat structured (for simple ML tasks at least ) we can use tools like PyCaret to automate EDA, model building and tuning hyper-parameters. It has a ton of other features like bagging , boosting, stacking models, generating polynomial features from data , transforming categorical data with high cardinalities and many more, all of which I will talk about in a later article. Today our focus will be on EDA. It is worthwhile to note that PyCaret uses pandas-profiling under the hood to perform EDA. I have used the popular California Housing Prices dataset (1990) here. Let’s try and analyse what features affect housing prices within a block. I would strongly recommend users to try this code on Google Colab or Jupyter unless your device has enough RAM. Installing PyCaret and making it Colab ready. Installing PyCaret and making it Colab ready. !pip install pycaretfrom pycaret.utils import enable_colabenable_colab()import pandas as pdfrom pycaret.regression import *dataset=pd.read_csv('/content/housing.csv') #Read the Csv File 2. Generate the EDA report ! exp1 = setup(data = dataset, target = 'median_house_value', session_id=123 , profile=True) Make sure that the profile parameter is set to True Firstly it’s remarkable that the report was generated in only 18.99 seconds. Plus we have this really cool navbar to jump to sections within the report. Quickly head over to sample which basically shows us the head of the dataset. The overview section tells us about the dataset structure, the number of missing cells , duplicate cells, size taken up by the dataset and the number of variables along with their types. Let’s observe a numeric feature in detail (Longitude) under the Variables section. Once we click on toggle details under the variable name we have tons of data, the quantile statistics, standard deviations , distinct values within the column. This is just the beginning! Once we switch over to the histogram tab we can see the distribution of the variable. We also have the Common Values and Extreme Values tabs here that show us the frequency of the values in the column & also the Minimum and Maximum values in the column. On switching to the categories tab we get some amazing plots , especially the all important pie chart. We can also see the distinct values in our columns & their counts through charts. Under the interactions tab we can see how two variables are correlated. Feel free to play around with the features. As an example we can see how median_income is correlated with median_house_value. We can see how all numeric features are correlated & also toggle the correlation types. The report also describes how that specific type of correlation is calculated. This section tells us about the missing values in our columns. My favourite feature is the Matrix depiction of missing values since it shows us the rows that contain missing values ! In the diagram below, the white horizontal lines indicate the missing values. This EDA report is super helpful and covers almost all the basic requirements we need for simple EDA tasks. It does miss out on some important features like One Way Anova Test & Chi -Square Tests but you can’t have it all in 19 seconds and one line of code! Although this is very handy, I feel that EDA is not a sclerotic process and often for tough problems creative techniques that are not part of this library at the moment can be very insightful. Check out my GitHub for some other projects and the entire code. You can contact me on my website. Thank you for your time!
[ { "code": null, "e": 633, "s": 172, "text": "Before we jump to model building, understanding the data at hand is essential. Analysing the data alone can give us valuable insights to solve our problems. Moreover understanding data is very useful to determine which features would help our model, which features can be done away with , how can we deal with missing values & correlations and so on. Building a model after considering all these factors will ensure that it is robust & can be generalised well." }, { "code": null, "e": 1200, "s": 633, "text": "Since the data science pipeline from EDA to model prototyping is somewhat structured (for simple ML tasks at least ) we can use tools like PyCaret to automate EDA, model building and tuning hyper-parameters. It has a ton of other features like bagging , boosting, stacking models, generating polynomial features from data , transforming categorical data with high cardinalities and many more, all of which I will talk about in a later article. Today our focus will be on EDA. It is worthwhile to note that PyCaret uses pandas-profiling under the hood to perform EDA." }, { "code": null, "e": 1457, "s": 1200, "text": "I have used the popular California Housing Prices dataset (1990) here. Let’s try and analyse what features affect housing prices within a block. I would strongly recommend users to try this code on Google Colab or Jupyter unless your device has enough RAM." }, { "code": null, "e": 1503, "s": 1457, "text": "Installing PyCaret and making it Colab ready." }, { "code": null, "e": 1549, "s": 1503, "text": "Installing PyCaret and making it Colab ready." }, { "code": null, "e": 1735, "s": 1549, "text": "!pip install pycaretfrom pycaret.utils import enable_colabenable_colab()import pandas as pdfrom pycaret.regression import *dataset=pd.read_csv('/content/housing.csv') #Read the Csv File" }, { "code": null, "e": 1764, "s": 1735, "text": "2. Generate the EDA report !" }, { "code": null, "e": 1855, "s": 1764, "text": "exp1 = setup(data = dataset, target = 'median_house_value', session_id=123 , profile=True)" }, { "code": null, "e": 1907, "s": 1855, "text": "Make sure that the profile parameter is set to True" }, { "code": null, "e": 2060, "s": 1907, "text": "Firstly it’s remarkable that the report was generated in only 18.99 seconds. Plus we have this really cool navbar to jump to sections within the report." }, { "code": null, "e": 2138, "s": 2060, "text": "Quickly head over to sample which basically shows us the head of the dataset." }, { "code": null, "e": 2325, "s": 2138, "text": "The overview section tells us about the dataset structure, the number of missing cells , duplicate cells, size taken up by the dataset and the number of variables along with their types." }, { "code": null, "e": 2408, "s": 2325, "text": "Let’s observe a numeric feature in detail (Longitude) under the Variables section." }, { "code": null, "e": 2682, "s": 2408, "text": "Once we click on toggle details under the variable name we have tons of data, the quantile statistics, standard deviations , distinct values within the column. This is just the beginning! Once we switch over to the histogram tab we can see the distribution of the variable." }, { "code": null, "e": 2850, "s": 2682, "text": "We also have the Common Values and Extreme Values tabs here that show us the frequency of the values in the column & also the Minimum and Maximum values in the column." }, { "code": null, "e": 3035, "s": 2850, "text": "On switching to the categories tab we get some amazing plots , especially the all important pie chart. We can also see the distinct values in our columns & their counts through charts." }, { "code": null, "e": 3233, "s": 3035, "text": "Under the interactions tab we can see how two variables are correlated. Feel free to play around with the features. As an example we can see how median_income is correlated with median_house_value." }, { "code": null, "e": 3400, "s": 3233, "text": "We can see how all numeric features are correlated & also toggle the correlation types. The report also describes how that specific type of correlation is calculated." }, { "code": null, "e": 3661, "s": 3400, "text": "This section tells us about the missing values in our columns. My favourite feature is the Matrix depiction of missing values since it shows us the rows that contain missing values ! In the diagram below, the white horizontal lines indicate the missing values." }, { "code": null, "e": 3919, "s": 3661, "text": "This EDA report is super helpful and covers almost all the basic requirements we need for simple EDA tasks. It does miss out on some important features like One Way Anova Test & Chi -Square Tests but you can’t have it all in 19 seconds and one line of code!" }, { "code": null, "e": 4112, "s": 3919, "text": "Although this is very handy, I feel that EDA is not a sclerotic process and often for tough problems creative techniques that are not part of this library at the moment can be very insightful." } ]
Binary Search on Singly Linked List in C++
A singly linked list is a linked list (a data structure that stores a node’s value and the memory location of the next node) which can go only one way. A binary search is a search algorithm based on divide and rule. That finds the middle element of the structure and compares and uses recursive calls to the same algorithm for inequality. Here, we are given a singly linked list and an element to be found using a binary search. Since the singly linked list is a data structure that uses only one pointer, it is not easy to find its middle element. To mid of singly linked list, we use two pointer approaches. Step 1 : Initialize, start_node (head of list) and last_node (will have last value) , mid_node (middle node of the structure). Step 2 : Compare mid_node to element Step 2.1 : if mid_node = element, return value “found”. Step 2.2 : if mid_node > element, call binary search on lower_Half. Step 2.3 : if mid_node < element, call binary search on upper_Half. Step 3 : if entire list is traversed, return “Not found”. Live Demo #include<stdio.h> #include<stdlib.h> struct Node{ int data; struct Node* next; }; Node *newNode(int x){ struct Node* temp = new Node; temp->data = x; temp->next = NULL; return temp; } struct Node* mid_node(Node* start, Node* last){ if (start == NULL) return NULL; struct Node* slow = start; struct Node* fast = start -> next; while (fast != last){ fast = fast -> next; if (fast != last){ slow = slow -> next; fast = fast -> next; } } return slow; } struct Node* binarySearch(Node *head, int value){ struct Node* start = head; struct Node* last = NULL; do{ Node* mid = mid_node(start, last); if (mid == NULL) return NULL; if (mid -> data == value) return mid; else if (mid -> data < value) start = mid -> next; else last = mid; } while (last == NULL || last != start); return NULL; } int main(){ Node *head = newNode(54); head->next = newNode(12); head->next->next = newNode(18); head->next->next->next = newNode(23); head->next->next->next->next = newNode(52); head->next->next->next->next->next = newNode(76); int value = 52; if (binarySearch(head, value) == NULL) printf("Value is not present in linked list\n"); else printf("The value is present in linked list\n"); return 0; } The value is present in linked list
[ { "code": null, "e": 1214, "s": 1062, "text": "A singly linked list is a linked list (a data structure that stores a node’s value and the memory location of the next node) which can go only one way." }, { "code": null, "e": 1401, "s": 1214, "text": "A binary search is a search algorithm based on divide and rule. That finds the middle element of the structure and compares and uses recursive calls to the same algorithm for inequality." }, { "code": null, "e": 1491, "s": 1401, "text": "Here, we are given a singly linked list and an element to be found using a binary search." }, { "code": null, "e": 1672, "s": 1491, "text": "Since the singly linked list is a data structure that uses only one pointer, it is not easy to find its middle element. To mid of singly linked list, we use two pointer approaches." }, { "code": null, "e": 2095, "s": 1672, "text": "Step 1 : Initialize, start_node (head of list) and last_node (will have last value) , mid_node (middle node of the structure).\nStep 2 : Compare mid_node to element\n Step 2.1 : if mid_node = element, return value “found”.\n Step 2.2 : if mid_node > element, call binary search on lower_Half.\n Step 2.3 : if mid_node < element, call binary search on upper_Half.\nStep 3 : if entire list is traversed, return “Not found”." }, { "code": null, "e": 2106, "s": 2095, "text": " Live Demo" }, { "code": null, "e": 3494, "s": 2106, "text": "#include<stdio.h>\n#include<stdlib.h>\nstruct Node{\n int data;\n struct Node* next;\n};\nNode *newNode(int x){\n struct Node* temp = new Node;\n temp->data = x;\n temp->next = NULL;\n return temp;\n}\nstruct Node* mid_node(Node* start, Node* last){\n if (start == NULL)\n return NULL;\n struct Node* slow = start;\n struct Node* fast = start -> next;\n while (fast != last){\n fast = fast -> next;\n if (fast != last){\n slow = slow -> next;\n fast = fast -> next;\n }\n }\n return slow;\n}\nstruct Node* binarySearch(Node *head, int value){\n struct Node* start = head;\n struct Node* last = NULL;\n do{\n Node* mid = mid_node(start, last);\n if (mid == NULL)\n return NULL;\n if (mid -> data == value)\n return mid;\n else if (mid -> data < value)\n start = mid -> next;\n else\n last = mid;\n }\n while (last == NULL || last != start);\n return NULL;\n}\nint main(){\n Node *head = newNode(54);\n head->next = newNode(12);\n head->next->next = newNode(18);\n head->next->next->next = newNode(23);\n head->next->next->next->next = newNode(52);\n head->next->next->next->next->next = newNode(76);\n int value = 52;\n if (binarySearch(head, value) == NULL)\n printf(\"Value is not present in linked list\\n\");\n else\n printf(\"The value is present in linked list\\n\");\n return 0;\n}" }, { "code": null, "e": 3530, "s": 3494, "text": "The value is present in linked list" } ]
Raising an Exceptions in Python
You can raise exceptions in several ways by using the raise statement. The general syntax for the raise statement is as follows. raise [Exception [, args [, traceback]]] Here, Exception is the type of exception (for example, NameError) and argument is a value for the exception argument. The argument is optional; if not supplied, the exception argument is None. The final argument, traceback, is also optional (and rarely used in practice), and if present, is the traceback object used for the exception. An exception can be a string, a class or an object. Most of the exceptions that the Python core raises are classes, with an argument that is an instance of the class. Defining new exceptions is quite easy and can be done as follows − def functionName( level ): if level < 1: raise "Invalid level!", level # The code below to this would not be executed # if we raise the exception Note − In order to catch an exception, an "except" clause must refer to the same exception thrown either class object or simple string. For example, to capture above exception, we must write the except clause as follows − try: Business Logic here... except "Invalid level!": Exception handling here... else: Rest of the code here...
[ { "code": null, "e": 1191, "s": 1062, "text": "You can raise exceptions in several ways by using the raise statement. The general syntax for the raise statement is as follows." }, { "code": null, "e": 1232, "s": 1191, "text": "raise [Exception [, args [, traceback]]]" }, { "code": null, "e": 1425, "s": 1232, "text": "Here, Exception is the type of exception (for example, NameError) and argument is a value for the exception argument. The argument is optional; if not supplied, the exception argument is None." }, { "code": null, "e": 1568, "s": 1425, "text": "The final argument, traceback, is also optional (and rarely used in practice), and if present, is the traceback object used for the exception." }, { "code": null, "e": 1802, "s": 1568, "text": "An exception can be a string, a class or an object. Most of the exceptions that the Python core raises are classes, with an argument that is an instance of the class. Defining new exceptions is quite easy and can be done as follows −" }, { "code": null, "e": 1969, "s": 1802, "text": "def functionName( level ):\n if level < 1:\n raise \"Invalid level!\", level\n # The code below to this would not be executed\n # if we raise the exception" }, { "code": null, "e": 2191, "s": 1969, "text": "Note − In order to catch an exception, an \"except\" clause must refer to the same exception thrown either class object or simple string. For example, to capture above exception, we must write the except clause as follows −" }, { "code": null, "e": 2311, "s": 2191, "text": "try:\n Business Logic here...\nexcept \"Invalid level!\":\n Exception handling here...\nelse:\n Rest of the code here..." } ]
How to run matplotlib in Tkinter?
One of the well-known use-cases of Python is in Machine Learning and Data Science. In order to visualize and plot a dataset, we use the Matplotlib library. To plot a matplotlib graph in a Tkinter application, we have to import the library by initializing "from matplotlib.pyplot as plt". The plot can be drawn either by defining a range value or importing the dataset in the notebook. #Import the required Libraries from tkinter import * from tkinter import ttk import numpy as np import matplotlib.pyplot as plt #Create an instance of Tkinter frame win= Tk() #Set the geometry of the window win.geometry("700x250") def graph(): car_prices= np.random.normal(50000,4000,2000) plt.figure(figsize=(7,3)) plt.hist(car_prices, 25) plt.show() #Create a Button to plot the graph button= ttk.Button(win, text= "Graph", command= graph) button.pack() win.mainloop() Running the above code will display a window that contains a button. When we click the "Graph" button, it will display a graph on the main window.
[ { "code": null, "e": 1447, "s": 1062, "text": "One of the well-known use-cases of Python is in Machine Learning and Data Science. In order to visualize and plot a dataset, we use the Matplotlib library. To plot a matplotlib graph in a Tkinter application, we have to import the library by initializing \"from matplotlib.pyplot as plt\". The plot can be drawn either by defining a range value or importing the dataset in the notebook." }, { "code": null, "e": 1935, "s": 1447, "text": "#Import the required Libraries\nfrom tkinter import *\nfrom tkinter import ttk\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n#Create an instance of Tkinter frame\nwin= Tk()\n\n#Set the geometry of the window\nwin.geometry(\"700x250\")\n\ndef graph():\n car_prices= np.random.normal(50000,4000,2000)\n plt.figure(figsize=(7,3))\n plt.hist(car_prices, 25)\n plt.show()\n\n#Create a Button to plot the graph\nbutton= ttk.Button(win, text= \"Graph\", command= graph)\nbutton.pack()\n\nwin.mainloop()" }, { "code": null, "e": 2004, "s": 1935, "text": "Running the above code will display a window that contains a button." }, { "code": null, "e": 2082, "s": 2004, "text": "When we click the \"Graph\" button, it will display a graph on the main window." } ]
colorsys module in Python
This module allows bidirectional conversions of color values between colors expressed in the RGB (Red Green Blue) and other color spaces. The three other color spaces it uses are YIQ (Luminance (Y) In-phase Quadrature), HLS (Hue Lightness Saturation) and HSV (Hue Saturation Value). All the coordinates can be between 0 and 1 except the I and Q values in the YIQ color space. The below tables shows the functions and their purpose. import colorsys as csys # "Electric Blue" r, g, b = 0.47, 0.91, 1.00 print("The RGB Values for Electric Blue: ", (r, g, b)) # y, i, q = csys.rgb_to_yiq(r, g, b) print("YIQ", (y, i, q), "becomes", csys.yiq_to_rgb(y, i, q)) h, s, v = csys.rgb_to_hsv(r, g, b) print("HSV", (h, s, v), "becomes", csys.hsv_to_rgb(h, s, v)) h, l, s = csys.rgb_to_hls(r, g, b) print("HLS", (h, l, s), "becomes", csys.hls_to_rgb(h, l, s)) Running the above code gives us the following result: The RGB Values for Electric Blue: (0.47, 0.91, 1.0) YIQ (0.7879, -0.292513, -0.06563100000000005) becomes (0.47, 0.9100000000000001, 1.0) HSV (0.5283018867924528, 0.53, 1.0) becomes (0.47, 0.9099999999999999, 1.0) HLS (0.5283018867924528, 0.735, 1.0) becomes (0.4700000000000001, 0.9099999999999998, 0.9999999999999999)
[ { "code": null, "e": 1438, "s": 1062, "text": "This module allows bidirectional conversions of color values between colors expressed in the RGB (Red Green Blue) and other color spaces. The three other color spaces it uses are YIQ (Luminance (Y) In-phase Quadrature), HLS (Hue Lightness Saturation) and HSV (Hue Saturation Value). All the coordinates can be between 0 and 1 except the I and Q values in the YIQ color space." }, { "code": null, "e": 1494, "s": 1438, "text": "The below tables shows the functions and their purpose." }, { "code": null, "e": 1909, "s": 1494, "text": "import colorsys as csys\n# \"Electric Blue\"\nr, g, b = 0.47, 0.91, 1.00\nprint(\"The RGB Values for Electric Blue: \", (r, g, b))\n#\ny, i, q = csys.rgb_to_yiq(r, g, b)\nprint(\"YIQ\", (y, i, q), \"becomes\", csys.yiq_to_rgb(y, i, q))\nh, s, v = csys.rgb_to_hsv(r, g, b)\nprint(\"HSV\", (h, s, v), \"becomes\", csys.hsv_to_rgb(h, s, v))\nh, l, s = csys.rgb_to_hls(r, g, b)\nprint(\"HLS\", (h, l, s), \"becomes\", csys.hls_to_rgb(h, l, s))\n" }, { "code": null, "e": 1963, "s": 1909, "text": "Running the above code gives us the following result:" }, { "code": null, "e": 2283, "s": 1963, "text": "The RGB Values for Electric Blue: (0.47, 0.91, 1.0)\nYIQ (0.7879, -0.292513, -0.06563100000000005) becomes (0.47, 0.9100000000000001, 1.0)\nHSV (0.5283018867924528, 0.53, 1.0) becomes (0.47, 0.9099999999999999, 1.0)\nHLS (0.5283018867924528, 0.735, 1.0) becomes (0.4700000000000001, 0.9099999999999998, 0.9999999999999999)" } ]
Write a C# program to check if a number is divisible by 2
To check if a number is divisible by2 or not, you need to first find the remainder. If the remainder of the number when it is divided by 2 is 0, then it would be divisible by 2. Let’s say our number is 10, we will check it using the following if-else − // checking if the number is divisible by 2 or not if (num % 2 == 0) { Console.WriteLine("Divisible by 2 "); } else { Console.WriteLine("Not divisible by 2"); } The following is an example to find whether the number is divisible by 2 or not − Live Demo using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Demo { class MyApplication { static void Main(string[] args) { int num; num = 10; // checking if the number is divisible by 2 or not if (num % 2 == 0) { Console.WriteLine("Divisible by 2 "); } else { Console.WriteLine("Not divisible by 2"); } Console.ReadLine(); } } } Divisible by 2
[ { "code": null, "e": 1146, "s": 1062, "text": "To check if a number is divisible by2 or not, you need to first find the remainder." }, { "code": null, "e": 1240, "s": 1146, "text": "If the remainder of the number when it is divided by 2 is 0, then it would be divisible by 2." }, { "code": null, "e": 1315, "s": 1240, "text": "Let’s say our number is 10, we will check it using the following if-else −" }, { "code": null, "e": 1482, "s": 1315, "text": "// checking if the number is divisible by 2 or not\nif (num % 2 == 0) {\n Console.WriteLine(\"Divisible by 2 \");\n} else {\n Console.WriteLine(\"Not divisible by 2\");\n}" }, { "code": null, "e": 1564, "s": 1482, "text": "The following is an example to find whether the number is divisible by 2 or not −" }, { "code": null, "e": 1575, "s": 1564, "text": " Live Demo" }, { "code": null, "e": 2050, "s": 1575, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace Demo {\n class MyApplication {\n static void Main(string[] args) {\n int num;\n num = 10;\n\n // checking if the number is divisible by 2 or not\n if (num % 2 == 0) {\n Console.WriteLine(\"Divisible by 2 \");\n } else {\n Console.WriteLine(\"Not divisible by 2\");\n }\n Console.ReadLine();\n }\n }\n}" }, { "code": null, "e": 2065, "s": 2050, "text": "Divisible by 2" } ]
How to show two figures using Matplotlib?
We can use the method, plt.figure(), to create the figures, and then, set their titles by passing strings as arguments. Create a new figure, or activate an existing figure, with the window title “Welcome to figure 1”. Create a new figure, or activate an existing figure, with the window title “Welcome to figure 1”. Draw a line using plot() method, over the current figure. Draw a line using plot() method, over the current figure. Create a new figure, or activate an existing figure, with the window title “Welcome to figure 2”. Create a new figure, or activate an existing figure, with the window title “Welcome to figure 2”. Draw a line using plot() method, over the current figure. Draw a line using plot() method, over the current figure. Using plt.show(), show the figures. Using plt.show(), show the figures. from matplotlib import pyplot as plt plt.figure("Welcome to figure 1") plt.plot([1, 3, 4]) plt.figure("Welcome to figure 2") plt.plot([11, 13, 41]) plt.show()
[ { "code": null, "e": 1182, "s": 1062, "text": "We can use the method, plt.figure(), to create the figures, and then, set their titles by passing strings as arguments." }, { "code": null, "e": 1280, "s": 1182, "text": "Create a new figure, or activate an existing figure, with the window title “Welcome to figure 1”." }, { "code": null, "e": 1378, "s": 1280, "text": "Create a new figure, or activate an existing figure, with the window title “Welcome to figure 1”." }, { "code": null, "e": 1436, "s": 1378, "text": "Draw a line using plot() method, over the current figure." }, { "code": null, "e": 1494, "s": 1436, "text": "Draw a line using plot() method, over the current figure." }, { "code": null, "e": 1592, "s": 1494, "text": "Create a new figure, or activate an existing figure, with the window title “Welcome to figure 2”." }, { "code": null, "e": 1690, "s": 1592, "text": "Create a new figure, or activate an existing figure, with the window title “Welcome to figure 2”." }, { "code": null, "e": 1748, "s": 1690, "text": "Draw a line using plot() method, over the current figure." }, { "code": null, "e": 1806, "s": 1748, "text": "Draw a line using plot() method, over the current figure." }, { "code": null, "e": 1842, "s": 1806, "text": "Using plt.show(), show the figures." }, { "code": null, "e": 1878, "s": 1842, "text": "Using plt.show(), show the figures." }, { "code": null, "e": 2039, "s": 1878, "text": "from matplotlib import pyplot as plt\n\nplt.figure(\"Welcome to figure 1\")\nplt.plot([1, 3, 4])\nplt.figure(\"Welcome to figure 2\")\nplt.plot([11, 13, 41])\n\nplt.show()" } ]
Virtual Memory in Operating System - GeeksforGeeks
21 Sep, 2021 Virtual Memory is a storage allocation scheme in which secondary memory can be addressed as though it were part of the main memory. The addresses a program may use to reference memory are distinguished from the addresses the memory system uses to identify physical storage sites, and program-generated addresses are translated automatically to the corresponding machine addresses. The size of virtual storage is limited by the addressing scheme of the computer system and the amount of secondary memory is available not by the actual number of the main storage locations. It is a technique that is implemented using both hardware and software. It maps memory addresses used by a program, called virtual addresses, into physical addresses in computer memory. All memory references within a process are logical addresses that are dynamically translated into physical addresses at run time. This means that a process can be swapped in and out of the main memory such that it occupies different places in the main memory at different times during the course of execution.A process may be broken into a number of pieces and these pieces need not be continuously located in the main memory during execution. The combination of dynamic run-time address translation and use of page or segment table permits this. All memory references within a process are logical addresses that are dynamically translated into physical addresses at run time. This means that a process can be swapped in and out of the main memory such that it occupies different places in the main memory at different times during the course of execution. A process may be broken into a number of pieces and these pieces need not be continuously located in the main memory during execution. The combination of dynamic run-time address translation and use of page or segment table permits this. If these characteristics are present then, it is not necessary that all the pages or segments are present in the main memory during execution. This means that the required pages need to be loaded into memory whenever required. Virtual memory is implemented using Demand Paging or Demand Segmentation. Demand Paging : The process of loading the page into memory on demand (whenever page fault occurs) is known as demand paging. The process includes the following steps : If the CPU tries to refer to a page that is currently not available in the main memory, it generates an interrupt indicating a memory access fault.The OS puts the interrupted process in a blocking state. For the execution to proceed the OS must bring the required page into the memory.The OS will search for the required page in the logical address space.The required page will be brought from logical address space to physical address space. The page replacement algorithms are used for the decision-making of replacing the page in physical address space.The page table will be updated accordingly.The signal will be sent to the CPU to continue the program execution and it will place the process back into the ready state. If the CPU tries to refer to a page that is currently not available in the main memory, it generates an interrupt indicating a memory access fault. The OS puts the interrupted process in a blocking state. For the execution to proceed the OS must bring the required page into the memory. The OS will search for the required page in the logical address space. The required page will be brought from logical address space to physical address space. The page replacement algorithms are used for the decision-making of replacing the page in physical address space. The page table will be updated accordingly. The signal will be sent to the CPU to continue the program execution and it will place the process back into the ready state. Hence whenever a page fault occurs these steps are followed by the operating system and the required page is brought into memory. Advantages : More processes may be maintained in the main memory: Because we are going to load only some of the pages of any particular process, there is room for more processes. This leads to more efficient utilization of the processor because it is more likely that at least one of the more numerous processes will be in the ready state at any particular time. A process may be larger than all of the main memory: One of the most fundamental restrictions in programming is lifted. A process larger than the main memory can be executed because of demand paging. The OS itself loads pages of a process in the main memory as required. It allows greater multiprogramming levels by using less of the available (primary) memory for each process. Page Fault Service Time : The time taken to service the page fault is called page fault service time. The page fault service time includes the time taken to perform all the above six steps. Let Main memory access time is: m Page fault service time is: s Page fault rate is : p Then, Effective memory access time = (p*s) + (1-p)*m Swapping: Swapping a process out means removing all of its pages from memory, or marking them so that they will be removed by the normal page replacement process. Suspending a process ensures that it is not runnable while it is swapped out. At some later time, the system swaps back the process from the secondary storage to the main memory. When a process is busy swapping pages in and out then this situation is called thrashing. Thrashing : At any given time, only a few pages of any process are in the main memory and therefore more processes can be maintained in memory. Furthermore, time is saved because unused pages are not swapped in and out of memory. However, the OS must be clever about how it manages this scheme. In the steady-state practically, all of the main memory will be occupied with process pages, so that the processor and OS have direct access to as many processes as possible. Thus when the OS brings one page in, it must throw another out. If it throws out a page just before it is used, then it will just have to get that page again almost immediately. Too much of this leads to a condition called Thrashing. The system spends most of its time swapping pages rather than executing instructions. So a good page replacement algorithm is required. In the given diagram, the initial degree of multiprogramming up to some extent of point(lambda), the CPU utilization is very high and the system resources are utilized 100%. But if we further increase the degree of multiprogramming the CPU utilization will drastically fall down and the system will spend more time only on the page replacement and the time is taken to complete the execution of the process will increase. This situation in the system is called thrashing. Causes of Thrashing : High degree of multiprogramming : If the number of processes keeps on increasing in the memory then the number of frames allocated to each process will be decreased. So, fewer frames will be available for each process. Due to this, a page fault will occur more frequently and more CPU time will be wasted in just swapping in and out of pages and the utilization will keep on decreasing. For example: Let free frames = 400 Case 1: Number of process = 100 Then, each process will get 4 frames. Case 2: Number of processes = 400 Each process will get 1 frame. Case 2 is a condition of thrashing, as the number of processes is increased, frames per process are decreased. Hence CPU time will be consumed in just swapping pages. Lacks of Frames: If a process has fewer frames then fewer pages of that process will be able to reside in memory and hence more frequent swapping in and out will be required. This may lead to thrashing. Hence sufficient amount of frames must be allocated to each process in order to prevent thrashing. High degree of multiprogramming : If the number of processes keeps on increasing in the memory then the number of frames allocated to each process will be decreased. So, fewer frames will be available for each process. Due to this, a page fault will occur more frequently and more CPU time will be wasted in just swapping in and out of pages and the utilization will keep on decreasing. For example: Let free frames = 400 Case 1: Number of process = 100 Then, each process will get 4 frames. Case 2: Number of processes = 400 Each process will get 1 frame. Case 2 is a condition of thrashing, as the number of processes is increased, frames per process are decreased. Hence CPU time will be consumed in just swapping pages. For example: Let free frames = 400 Case 1: Number of process = 100 Then, each process will get 4 frames. Case 2: Number of processes = 400 Each process will get 1 frame. Case 2 is a condition of thrashing, as the number of processes is increased, frames per process are decreased. Hence CPU time will be consumed in just swapping pages. Lacks of Frames: If a process has fewer frames then fewer pages of that process will be able to reside in memory and hence more frequent swapping in and out will be required. This may lead to thrashing. Hence sufficient amount of frames must be allocated to each process in order to prevent thrashing. Recovery of Thrashing : Do not allow the system to go into thrashing by instructing the long-term scheduler not to bring the processes into memory after the threshold. If the system is already thrashing then instruct the mid-term schedular to suspend some of the processes so that we can recover the system from thrashing. nidhi_biet Pushpender007 memory-management Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Cache Memory in Computer Organization LRU Cache Implementation Difference between Internal and External fragmentation Named Pipe or FIFO with example C program Memory Management in Operating System Commonly Asked Operating Systems Interview Questions Random Access Memory (RAM) and Read Only Memory (ROM) Mutex lock for Linux Thread Synchronization Program for Least Recently Used (LRU) Page Replacement algorithm 'crontab' in Linux with Examples
[ { "code": null, "e": 28044, "s": 28016, "text": "\n21 Sep, 2021" }, { "code": null, "e": 28426, "s": 28044, "text": "Virtual Memory is a storage allocation scheme in which secondary memory can be addressed as though it were part of the main memory. The addresses a program may use to reference memory are distinguished from the addresses the memory system uses to identify physical storage sites, and program-generated addresses are translated automatically to the corresponding machine addresses. " }, { "code": null, "e": 28618, "s": 28426, "text": "The size of virtual storage is limited by the addressing scheme of the computer system and the amount of secondary memory is available not by the actual number of the main storage locations. " }, { "code": null, "e": 28805, "s": 28618, "text": "It is a technique that is implemented using both hardware and software. It maps memory addresses used by a program, called virtual addresses, into physical addresses in computer memory. " }, { "code": null, "e": 29352, "s": 28805, "text": "All memory references within a process are logical addresses that are dynamically translated into physical addresses at run time. This means that a process can be swapped in and out of the main memory such that it occupies different places in the main memory at different times during the course of execution.A process may be broken into a number of pieces and these pieces need not be continuously located in the main memory during execution. The combination of dynamic run-time address translation and use of page or segment table permits this." }, { "code": null, "e": 29662, "s": 29352, "text": "All memory references within a process are logical addresses that are dynamically translated into physical addresses at run time. This means that a process can be swapped in and out of the main memory such that it occupies different places in the main memory at different times during the course of execution." }, { "code": null, "e": 29900, "s": 29662, "text": "A process may be broken into a number of pieces and these pieces need not be continuously located in the main memory during execution. The combination of dynamic run-time address translation and use of page or segment table permits this." }, { "code": null, "e": 30202, "s": 29900, "text": "If these characteristics are present then, it is not necessary that all the pages or segments are present in the main memory during execution. This means that the required pages need to be loaded into memory whenever required. Virtual memory is implemented using Demand Paging or Demand Segmentation. " }, { "code": null, "e": 30372, "s": 30202, "text": "Demand Paging : The process of loading the page into memory on demand (whenever page fault occurs) is known as demand paging. The process includes the following steps : " }, { "code": null, "e": 31097, "s": 30372, "text": "If the CPU tries to refer to a page that is currently not available in the main memory, it generates an interrupt indicating a memory access fault.The OS puts the interrupted process in a blocking state. For the execution to proceed the OS must bring the required page into the memory.The OS will search for the required page in the logical address space.The required page will be brought from logical address space to physical address space. The page replacement algorithms are used for the decision-making of replacing the page in physical address space.The page table will be updated accordingly.The signal will be sent to the CPU to continue the program execution and it will place the process back into the ready state." }, { "code": null, "e": 31245, "s": 31097, "text": "If the CPU tries to refer to a page that is currently not available in the main memory, it generates an interrupt indicating a memory access fault." }, { "code": null, "e": 31384, "s": 31245, "text": "The OS puts the interrupted process in a blocking state. For the execution to proceed the OS must bring the required page into the memory." }, { "code": null, "e": 31455, "s": 31384, "text": "The OS will search for the required page in the logical address space." }, { "code": null, "e": 31657, "s": 31455, "text": "The required page will be brought from logical address space to physical address space. The page replacement algorithms are used for the decision-making of replacing the page in physical address space." }, { "code": null, "e": 31701, "s": 31657, "text": "The page table will be updated accordingly." }, { "code": null, "e": 31827, "s": 31701, "text": "The signal will be sent to the CPU to continue the program execution and it will place the process back into the ready state." }, { "code": null, "e": 31958, "s": 31827, "text": "Hence whenever a page fault occurs these steps are followed by the operating system and the required page is brought into memory. " }, { "code": null, "e": 31973, "s": 31958, "text": "Advantages : " }, { "code": null, "e": 32323, "s": 31973, "text": "More processes may be maintained in the main memory: Because we are going to load only some of the pages of any particular process, there is room for more processes. This leads to more efficient utilization of the processor because it is more likely that at least one of the more numerous processes will be in the ready state at any particular time." }, { "code": null, "e": 32594, "s": 32323, "text": "A process may be larger than all of the main memory: One of the most fundamental restrictions in programming is lifted. A process larger than the main memory can be executed because of demand paging. The OS itself loads pages of a process in the main memory as required." }, { "code": null, "e": 32702, "s": 32594, "text": "It allows greater multiprogramming levels by using less of the available (primary) memory for each process." }, { "code": null, "e": 32893, "s": 32702, "text": "Page Fault Service Time : The time taken to service the page fault is called page fault service time. The page fault service time includes the time taken to perform all the above six steps. " }, { "code": null, "e": 33033, "s": 32893, "text": "Let Main memory access time is: m\nPage fault service time is: s\nPage fault rate is : p\nThen, Effective memory access time = (p*s) + (1-p)*m" }, { "code": null, "e": 33044, "s": 33033, "text": "Swapping: " }, { "code": null, "e": 33467, "s": 33044, "text": "Swapping a process out means removing all of its pages from memory, or marking them so that they will be removed by the normal page replacement process. Suspending a process ensures that it is not runnable while it is swapped out. At some later time, the system swaps back the process from the secondary storage to the main memory. When a process is busy swapping pages in and out then this situation is called thrashing. " }, { "code": null, "e": 33481, "s": 33467, "text": "Thrashing : " }, { "code": null, "e": 34310, "s": 33481, "text": "At any given time, only a few pages of any process are in the main memory and therefore more processes can be maintained in memory. Furthermore, time is saved because unused pages are not swapped in and out of memory. However, the OS must be clever about how it manages this scheme. In the steady-state practically, all of the main memory will be occupied with process pages, so that the processor and OS have direct access to as many processes as possible. Thus when the OS brings one page in, it must throw another out. If it throws out a page just before it is used, then it will just have to get that page again almost immediately. Too much of this leads to a condition called Thrashing. The system spends most of its time swapping pages rather than executing instructions. So a good page replacement algorithm is required. " }, { "code": null, "e": 34783, "s": 34310, "text": "In the given diagram, the initial degree of multiprogramming up to some extent of point(lambda), the CPU utilization is very high and the system resources are utilized 100%. But if we further increase the degree of multiprogramming the CPU utilization will drastically fall down and the system will spend more time only on the page replacement and the time is taken to complete the execution of the process will increase. This situation in the system is called thrashing. " }, { "code": null, "e": 34807, "s": 34783, "text": "Causes of Thrashing : " }, { "code": null, "e": 35834, "s": 34807, "text": "High degree of multiprogramming : If the number of processes keeps on increasing in the memory then the number of frames allocated to each process will be decreased. So, fewer frames will be available for each process. Due to this, a page fault will occur more frequently and more CPU time will be wasted in just swapping in and out of pages and the utilization will keep on decreasing. For example: Let free frames = 400 Case 1: Number of process = 100 Then, each process will get 4 frames. Case 2: Number of processes = 400 Each process will get 1 frame. Case 2 is a condition of thrashing, as the number of processes is increased, frames per process are decreased. Hence CPU time will be consumed in just swapping pages. Lacks of Frames: If a process has fewer frames then fewer pages of that process will be able to reside in memory and hence more frequent swapping in and out will be required. This may lead to thrashing. Hence sufficient amount of frames must be allocated to each process in order to prevent thrashing." }, { "code": null, "e": 36560, "s": 35834, "text": "High degree of multiprogramming : If the number of processes keeps on increasing in the memory then the number of frames allocated to each process will be decreased. So, fewer frames will be available for each process. Due to this, a page fault will occur more frequently and more CPU time will be wasted in just swapping in and out of pages and the utilization will keep on decreasing. For example: Let free frames = 400 Case 1: Number of process = 100 Then, each process will get 4 frames. Case 2: Number of processes = 400 Each process will get 1 frame. Case 2 is a condition of thrashing, as the number of processes is increased, frames per process are decreased. Hence CPU time will be consumed in just swapping pages. " }, { "code": null, "e": 36666, "s": 36560, "text": "For example: Let free frames = 400 Case 1: Number of process = 100 Then, each process will get 4 frames. " }, { "code": null, "e": 36900, "s": 36666, "text": "Case 2: Number of processes = 400 Each process will get 1 frame. Case 2 is a condition of thrashing, as the number of processes is increased, frames per process are decreased. Hence CPU time will be consumed in just swapping pages. " }, { "code": null, "e": 37202, "s": 36900, "text": "Lacks of Frames: If a process has fewer frames then fewer pages of that process will be able to reside in memory and hence more frequent swapping in and out will be required. This may lead to thrashing. Hence sufficient amount of frames must be allocated to each process in order to prevent thrashing." }, { "code": null, "e": 37228, "s": 37202, "text": "Recovery of Thrashing : " }, { "code": null, "e": 37372, "s": 37228, "text": "Do not allow the system to go into thrashing by instructing the long-term scheduler not to bring the processes into memory after the threshold." }, { "code": null, "e": 37527, "s": 37372, "text": "If the system is already thrashing then instruct the mid-term schedular to suspend some of the processes so that we can recover the system from thrashing." }, { "code": null, "e": 37538, "s": 37527, "text": "nidhi_biet" }, { "code": null, "e": 37552, "s": 37538, "text": "Pushpender007" }, { "code": null, "e": 37570, "s": 37552, "text": "memory-management" }, { "code": null, "e": 37588, "s": 37570, "text": "Operating Systems" }, { "code": null, "e": 37606, "s": 37588, "text": "Operating Systems" }, { "code": null, "e": 37704, "s": 37606, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37713, "s": 37704, "text": "Comments" }, { "code": null, "e": 37726, "s": 37713, "text": "Old Comments" }, { "code": null, "e": 37764, "s": 37726, "text": "Cache Memory in Computer Organization" }, { "code": null, "e": 37789, "s": 37764, "text": "LRU Cache Implementation" }, { "code": null, "e": 37844, "s": 37789, "text": "Difference between Internal and External fragmentation" }, { "code": null, "e": 37886, "s": 37844, "text": "Named Pipe or FIFO with example C program" }, { "code": null, "e": 37924, "s": 37886, "text": "Memory Management in Operating System" }, { "code": null, "e": 37977, "s": 37924, "text": "Commonly Asked Operating Systems Interview Questions" }, { "code": null, "e": 38031, "s": 37977, "text": "Random Access Memory (RAM) and Read Only Memory (ROM)" }, { "code": null, "e": 38075, "s": 38031, "text": "Mutex lock for Linux Thread Synchronization" }, { "code": null, "e": 38140, "s": 38075, "text": "Program for Least Recently Used (LRU) Page Replacement algorithm" } ]
Bootstrap - Code
Bootstrap allows you to display code with two different key ways − The first is the <code> tag. If you are going to be displaying code inline, you should use the <code> tag. The first is the <code> tag. If you are going to be displaying code inline, you should use the <code> tag. Second is the <pre> tag. If the code needs to be displayed as a standalone block element or if it has multiple lines, then you should use the <pre> tag. Second is the <pre> tag. If the code needs to be displayed as a standalone block element or if it has multiple lines, then you should use the <pre> tag. Let us see an example below − <p><code>&lt;header&gt;</code> is wrapped as an inline element.</p> <p>To display code as a standalone block element use &lt;pre&gt; tag as:</p> <pre> &lt;article&gt; &lt;h1&gt;Article Heading&lt;/h1&gt; &lt;/article&gt; </pre> <header> is wrapped as an inline element. To display code as a standalone block element use <pre> tag as: <article> <h1>Article Heading</h1> </article> 26 Lectures 2 hours Anadi Sharma 54 Lectures 4.5 hours Frahaan Hussain 161 Lectures 14.5 hours Eduonix Learning Solutions 20 Lectures 4 hours Azaz Patel 15 Lectures 1.5 hours Muhammad Ismail 62 Lectures 8 hours Yossef Ayman Zedan Print Add Notes Bookmark this page
[ { "code": null, "e": 3398, "s": 3331, "text": "Bootstrap allows you to display code with two different key ways −" }, { "code": null, "e": 3505, "s": 3398, "text": "The first is the <code> tag. If you are going to be displaying code inline, you should use the <code> tag." }, { "code": null, "e": 3612, "s": 3505, "text": "The first is the <code> tag. If you are going to be displaying code inline, you should use the <code> tag." }, { "code": null, "e": 3765, "s": 3612, "text": "Second is the <pre> tag. If the code needs to be displayed as a standalone block element or if it has multiple lines, then you should use the <pre> tag." }, { "code": null, "e": 3918, "s": 3765, "text": "Second is the <pre> tag. If the code needs to be displayed as a standalone block element or if it has multiple lines, then you should use the <pre> tag." }, { "code": null, "e": 3948, "s": 3918, "text": "Let us see an example below −" }, { "code": null, "e": 4189, "s": 3948, "text": "<p><code>&lt;header&gt;</code> is wrapped as an inline element.</p>\n<p>To display code as a standalone block element use &lt;pre&gt; tag as:</p>\n\n<pre>\n &lt;article&gt;\n &lt;h1&gt;Article Heading&lt;/h1&gt;\n &lt;/article&gt;\n</pre>" }, { "code": null, "e": 4231, "s": 4189, "text": "<header> is wrapped as an inline element." }, { "code": null, "e": 4302, "s": 4231, "text": "To display code as a standalone block element use <pre> tag as:\n " }, { "code": null, "e": 4385, "s": 4302, "text": " <article>\n <h1>Article Heading</h1>\n </article>\n " }, { "code": null, "e": 4418, "s": 4385, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 4432, "s": 4418, "text": " Anadi Sharma" }, { "code": null, "e": 4467, "s": 4432, "text": "\n 54 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4484, "s": 4467, "text": " Frahaan Hussain" }, { "code": null, "e": 4521, "s": 4484, "text": "\n 161 Lectures \n 14.5 hours \n" }, { "code": null, "e": 4549, "s": 4521, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4582, "s": 4549, "text": "\n 20 Lectures \n 4 hours \n" }, { "code": null, "e": 4594, "s": 4582, "text": " Azaz Patel" }, { "code": null, "e": 4629, "s": 4594, "text": "\n 15 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4646, "s": 4629, "text": " Muhammad Ismail" }, { "code": null, "e": 4679, "s": 4646, "text": "\n 62 Lectures \n 8 hours \n" }, { "code": null, "e": 4699, "s": 4679, "text": " Yossef Ayman Zedan" }, { "code": null, "e": 4706, "s": 4699, "text": " Print" }, { "code": null, "e": 4717, "s": 4706, "text": " Add Notes" } ]
How to create a scrollable textView Android app?
This example demonstrates how do I create a scrollable textView in android app. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="5dp" tools:context=".MainActivity"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="match_parent" android:scrollbars="vertical" /> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.java package app.com.sample; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.method.ScrollingMovementMethod; import android.widget.TextView; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView textView = (TextView) findViewById(R.id.textView); String para = "Mohandas Karamchand Gandhi (/ˈɡɑːndi, ˈɡændi/;[2] Hindustani: [ˈmoːɦəndaːs ˈkərəmtʃənd ˈɡaːndɦi] (About this soundlisten); 2 October 1869 – 30 January 1948) was an Indian activist who was the leader of the Indian independence movement against British colonial rule.[3] Employing nonviolent civil disobedience, Gandhi led India to independence and inspired movements for civil rights and freedom across the world. The honorific Mahātmā (Sanskrit: \"high-souled\", \"venerable\")[4] was applied to him first in 1914 in South Africa[5] and is now used worldwide. In India, he was also called Bapu, a term that he preferred[6] (Gujarati: endearment for father,[7] papa[7][8]), and Gandhi ji, and is known as the Father of the Nation.[9][10]\n" + "\n" + "Born and raised in a Hindu family in coastal Gujarat, western India, and trained in law at the Inner Temple, London, Gandhi first employed nonviolent civil disobedience as an expatriate lawyer in South Africa, in the resident Indian community's struggle for civil rights. After his return to India in 1915, he set about organising peasants, farmers, and urban labourers to protest against excessive land-tax and discrimination. Assuming leadership of the Indian National Congress in 1921, Gandhi led nationwide campaigns for various social causes and for achieving Swaraj or self-rule.[11]\n" + "\n" + "Gandhi led Indians in challenging the British-imposed salt tax with the 400 km (250 mi) Dandi Salt March in 1930, and later in calling for the British to Quit India in 1942. He was imprisoned for many years, upon many occasions, in both South Africa and India. He lived modestly in a self-sufficient residential community and wore the traditional Indian dhoti and shawl, woven with yarn hand-spun on a charkha. He ate simple vegetarian food, and also undertook long fasts as a means of both self-purification and political protest.\n" + "\n" + "Gandhi's vision of an independent India based on religious pluralism was challenged in the early 1940s by a new Muslim nationalism which was demanding a separate Muslim homeland carved out of India.[12] In August 1947, Britain granted independence, but the British Indian Empire[12] was partitioned into two dominions, a Hindu-majority India and Muslim-majority Pakistan.[13] As many displaced Hindus, Muslims, and Sikhs made their way to their new lands, religious violence broke out, especially in the Punjab and Bengal. Eschewing the official celebration of independence in Delhi, Gandhi visited the affected areas, attempting to provide solace. In the months following, he undertook several fasts unto death to stop religious violence. The last of these, undertaken on 12 January 1948 when he was 78,[14] also had the indirect goal of pressuring India to pay out some cash assets owed to Pakistan.[14] Some Indians thought Gandhi was too accommodating.[14][15] Among them was Nathuram Godse, a Hindu nationalist, who assassinated Gandhi on 30 January 1948 by firing three bullets into his chest.[15"; textView.setText(para); textView.setMovementMethod(newScrollingMovementMethod()); } Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − Click here to download the project code.
[ { "code": null, "e": 1142, "s": 1062, "text": "This example demonstrates how do I create a scrollable textView in android app." }, { "code": null, "e": 1271, "s": 1142, "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": 1336, "s": 1271, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1864, "s": 1336, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:id=\"@+id/activity_main\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"5dp\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"match_parent\"\n android:scrollbars=\"vertical\" />\n</RelativeLayout>" }, { "code": null, "e": 1921, "s": 1864, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 5687, "s": 1921, "text": "package app.com.sample;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.text.method.ScrollingMovementMethod;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n TextView textView = (TextView) findViewById(R.id.textView);\n String para = \"Mohandas Karamchand Gandhi (/ˈɡɑːndi, ˈɡændi/;[2] Hindustani: [ˈmoːɦəndaːs ˈkərəmtʃənd ˈɡaːndɦi] (About this soundlisten);\n 2 October 1869 – 30 January 1948) was an Indian activist who was the leader of the Indian independence movement against British colonial rule.[3]\n Employing nonviolent civil disobedience, Gandhi led India to independence and inspired movements for civil rights and freedom across the world.\n The honorific Mahātmā (Sanskrit: \\\"high-souled\\\", \\\"venerable\\\")[4] was applied to him first in 1914 in South Africa[5] and is now used worldwide.\n In India, he was also called Bapu, a term that he preferred[6] (Gujarati: endearment for father,[7] papa[7][8]), and Gandhi ji, and is known as the Father of the\n Nation.[9][10]\\n\" + \"\\n\" + \"Born and raised in a Hindu family in coastal Gujarat, western India, and trained in law at the Inner Temple, London, Gandhi first\n employed nonviolent civil disobedience as an expatriate lawyer in South Africa, in the resident Indian community's struggle for civil rights. After his return\n to India in 1915, he set about organising peasants, farmers, and urban labourers to protest against excessive land-tax and discrimination.\n Assuming leadership of the Indian National Congress in 1921, Gandhi led nationwide campaigns for various social causes and for achieving Swaraj or\n self-rule.[11]\\n\" + \"\\n\" + \"Gandhi led Indians in challenging the British-imposed salt tax with the 400 km (250 mi) Dandi Salt March in 1930, and\n later in calling for the British to Quit India in 1942. He was imprisoned for many years, upon many occasions, in both South Africa and India.\n He lived modestly in a self-sufficient residential community and wore the traditional Indian dhoti\n and shawl, woven with yarn hand-spun on a charkha. He ate simple vegetarian food, and also undertook long fasts as a means of both\n self-purification and political protest.\\n\" + \"\\n\" + \"Gandhi's vision of an independent India based on religious pluralism was challenged in\n the early 1940s by a new Muslim nationalism which was demanding a separate Muslim homeland carved out of India.[12] In August 1947, Britain\n granted independence, but the British Indian Empire[12] was partitioned into two dominions, a Hindu-majority India and Muslim-majority Pakistan.[13]\n As many displaced Hindus, Muslims, and Sikhs made their way to their new lands, religious violence broke out, especially in the Punjab and Bengal.\n Eschewing the official celebration of independence in Delhi, Gandhi visited the affected areas, attempting to provide solace. In the months following,\n he undertook several fasts unto death to stop religious violence. The last of these, undertaken on 12 January 1948 when he was 78,[14] also had\n the indirect goal of pressuring India to pay out some cash assets owed to Pakistan.[14] Some Indians thought Gandhi was too accommodating.[14][15]\n Among them was Nathuram Godse, a Hindu nationalist, who assassinated Gandhi on 30 January 1948 by firing three bullets into his chest.[15\";\n textView.setText(para);\n textView.setMovementMethod(newScrollingMovementMethod());\n }" }, { "code": null, "e": 5742, "s": 5687, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 6412, "s": 5742, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 6759, "s": 6412, "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": 6800, "s": 6759, "text": "Click here to download the project code." } ]
Tryit Editor v3.7
Tryit: box-shadow with blur effect
[]
C++ Program for Cycle Sort - GeeksforGeeks
03 Sep, 2021 Cycle sort is an in-place sorting Algorithm, unstable sorting algorithm, a comparison sort that is theoretically optimal in terms of the total number of writes to the original array. It is optimal in terms of number of memory writes. It minimizes the number of memory writes to sort (Each value is either written zero times, if it’s already in its correct position, or written one time to its correct position.) It is based on the idea that array to be sorted can be divided into cycles. Cycles can be visualized as a graph. We have n nodes and an edge directed from node i to node j if the element at i-th index must be present at j-th index in the sorted array. Cycle in arr[] = {4, 5, 2, 1, 5} Cycle in arr[] = {4, 3, 2, 1} We one by one consider all cycles. We first consider the cycle that includes first element. We find correct position of first element, place it at its correct position, say j. We consider old value of arr[j] and find its correct position, we keep doing this till all elements of current cycle are placed at correct position, i.e., we don\’t come back to cycle starting point. C++ // C++ program to implement cycle sort#include <iostream>using namespace std; // Function sort the array using Cycle sortvoid cycleSort (int arr[], int n){ // count number of memory writes int writes = 0; // traverse array elements and put it to on // the right place for (int cycle_start=0; cycle_start<=n-2; cycle_start++) { // initialize item as starting point int item = arr[cycle_start]; // Find position where we put the item. We basically // count all smaller elements on right side of item. int pos = cycle_start; for (int i = cycle_start+1; i<n; i++) if (arr[i] < item) pos++; // If item is already in correct position if (pos == cycle_start) continue; // ignore all duplicate elements while (item == arr[pos]) pos += 1; // put the item to it\'s right position if (pos != cycle_start) { swap(item, arr[pos]); writes++; } // Rotate rest of the cycle while (pos != cycle_start) { pos = cycle_start; // Find position where we put the element for (int i = cycle_start+1; i<n; i++) if (arr[i] < item) pos += 1; // ignore all duplicate elements while (item == arr[pos]) pos += 1; // put the item to it\'s right position if (item != arr[pos]) { swap(item, arr[pos]); writes++; } } } // Number of memory writes or swaps // cout << writes << endl ;} // Driver program to test above functionint main(){ int arr[] = {1, 8, 3, 9, 10, 10, 2, 4 }; int n = sizeof(arr)/sizeof(arr[0]); cycleSort(arr, n) ; cout << "After sort : " <<endl; for (int i =0; i<n; i++) cout << arr[i] << " "; return 0;} Output: After sort : 1 2 3 4 8 9 10 10 Please refer complete article on Cycle Sort for more details! clintra C++ Programs Sorting Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Const keyword in C++ Passing a function as a parameter in C++ Student record management system using linked list Program to implement Singly Linked List in C++ using class C++ program to read file word by word
[ { "code": null, "e": 24241, "s": 24213, "text": "\n03 Sep, 2021" }, { "code": null, "e": 24425, "s": 24241, "text": "Cycle sort is an in-place sorting Algorithm, unstable sorting algorithm, a comparison sort that is theoretically optimal in terms of the total number of writes to the original array. " }, { "code": null, "e": 24654, "s": 24425, "text": "It is optimal in terms of number of memory writes. It minimizes the number of memory writes to sort (Each value is either written zero times, if it’s already in its correct position, or written one time to its correct position.)" }, { "code": null, "e": 24940, "s": 24654, "text": "It is based on the idea that array to be sorted can be divided into cycles. Cycles can be visualized as a graph. We have n nodes and an edge directed from node i to node j if the element at i-th index must be present at j-th index in the sorted array. Cycle in arr[] = {4, 5, 2, 1, 5} " }, { "code": null, "e": 24971, "s": 24940, "text": "Cycle in arr[] = {4, 3, 2, 1} " }, { "code": null, "e": 25348, "s": 24971, "text": "We one by one consider all cycles. We first consider the cycle that includes first element. We find correct position of first element, place it at its correct position, say j. We consider old value of arr[j] and find its correct position, we keep doing this till all elements of current cycle are placed at correct position, i.e., we don\\’t come back to cycle starting point. " }, { "code": null, "e": 25352, "s": 25348, "text": "C++" }, { "code": "// C++ program to implement cycle sort#include <iostream>using namespace std; // Function sort the array using Cycle sortvoid cycleSort (int arr[], int n){ // count number of memory writes int writes = 0; // traverse array elements and put it to on // the right place for (int cycle_start=0; cycle_start<=n-2; cycle_start++) { // initialize item as starting point int item = arr[cycle_start]; // Find position where we put the item. We basically // count all smaller elements on right side of item. int pos = cycle_start; for (int i = cycle_start+1; i<n; i++) if (arr[i] < item) pos++; // If item is already in correct position if (pos == cycle_start) continue; // ignore all duplicate elements while (item == arr[pos]) pos += 1; // put the item to it\\'s right position if (pos != cycle_start) { swap(item, arr[pos]); writes++; } // Rotate rest of the cycle while (pos != cycle_start) { pos = cycle_start; // Find position where we put the element for (int i = cycle_start+1; i<n; i++) if (arr[i] < item) pos += 1; // ignore all duplicate elements while (item == arr[pos]) pos += 1; // put the item to it\\'s right position if (item != arr[pos]) { swap(item, arr[pos]); writes++; } } } // Number of memory writes or swaps // cout << writes << endl ;} // Driver program to test above functionint main(){ int arr[] = {1, 8, 3, 9, 10, 10, 2, 4 }; int n = sizeof(arr)/sizeof(arr[0]); cycleSort(arr, n) ; cout << \"After sort : \" <<endl; for (int i =0; i<n; i++) cout << arr[i] << \" \"; return 0;}", "e": 27282, "s": 25352, "text": null }, { "code": null, "e": 27291, "s": 27282, "text": "Output: " }, { "code": null, "e": 27324, "s": 27291, "text": "After sort : \n1 2 3 4 8 9 10 10 " }, { "code": null, "e": 27387, "s": 27324, "text": "Please refer complete article on Cycle Sort for more details! " }, { "code": null, "e": 27395, "s": 27387, "text": "clintra" }, { "code": null, "e": 27408, "s": 27395, "text": "C++ Programs" }, { "code": null, "e": 27416, "s": 27408, "text": "Sorting" }, { "code": null, "e": 27424, "s": 27416, "text": "Sorting" }, { "code": null, "e": 27522, "s": 27424, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27531, "s": 27522, "text": "Comments" }, { "code": null, "e": 27544, "s": 27531, "text": "Old Comments" }, { "code": null, "e": 27565, "s": 27544, "text": "Const keyword in C++" }, { "code": null, "e": 27606, "s": 27565, "text": "Passing a function as a parameter in C++" }, { "code": null, "e": 27657, "s": 27606, "text": "Student record management system using linked list" }, { "code": null, "e": 27716, "s": 27657, "text": "Program to implement Singly Linked List in C++ using class" } ]
Command line arguments example in C
It is possible to pass some values from the command line to your C programs when they are executed. These values are called command line arguments and many times they are important for your program especially when you want to control your program from outside instead of hard-coding those values inside the code. The command line arguments are handled using main() function arguments where argc refers to the number of arguments passed, and argv[] is a pointer array which points to each argument passed to the program. Following is a simple example which checks if there is any argument supplied from the command line and take action accordingly − #include <stdio.h> int main( int argc, char *argv[] ) { if( argc == 2 ) { printf("The argument supplied is %s\n", argv[1]); } else if( argc > 2 ) { printf("Too many arguments supplied.\n"); } else { printf("One argument expected.\n"); } } $./a.out testing The argument supplied is testing $./a.out testing1 testing2 Too many arguments supplied. $./a.out One argument expected
[ { "code": null, "e": 1375, "s": 1062, "text": "It is possible to pass some values from the command line to your C programs when they are executed. These values are called command line arguments and many times they are important for your program especially when you want to control your program from outside instead of hard-coding those values inside the code." }, { "code": null, "e": 1711, "s": 1375, "text": "The command line arguments are handled using main() function arguments where argc refers to the number of arguments passed, and argv[] is a pointer array which points to each argument passed to the program. Following is a simple example which checks if there is any argument supplied from the command line and take action accordingly −" }, { "code": null, "e": 1980, "s": 1711, "text": "#include <stdio.h>\nint main( int argc, char *argv[] ) {\n if( argc == 2 ) {\n printf(\"The argument supplied is %s\\n\", argv[1]);\n } else if( argc > 2 ) {\n printf(\"Too many arguments supplied.\\n\");\n } else {\n printf(\"One argument expected.\\n\");\n }\n}" }, { "code": null, "e": 2030, "s": 1980, "text": "$./a.out testing\nThe argument supplied is testing" }, { "code": null, "e": 2086, "s": 2030, "text": "$./a.out testing1 testing2\nToo many arguments supplied." }, { "code": null, "e": 2117, "s": 2086, "text": "$./a.out\nOne argument expected" } ]
Program to find Nth term of the Van Eck's Sequence - GeeksforGeeks
13 May, 2022 Given a positive integer N, the task is to print Nth term of the Van Eck’s sequence.In mathematics, Van Eck’s sequence is an integer sequence which is defined recursively as follows: Let the first term be 0 i.e a0 = 0. Then for n >= 0, if there exists an m < n such that am = an take the largest such m and set an+1 = n − m; Otherwise an+1 = 0. Start with a(1)=0. First few terms of Van Eck’s Sequence are as follows: 0, 0, 1, 0, 2, 0, 2, 2, 1, 6, 0, 5, 0, 2, 6, 5, 4, 0, 5 ... Example: Input: N = 5 Output: 2 Input: N = 10 Output: 6 Approach: As described above we can follow the below steps to generate Van Eck’s sequence: Set the first term of the sequence as 0. Then Repeatedly apply: If the last term has not occurred yet and is new to the sequence so far then, set the next term as zero.Otherwise, the next term is how far back this last term has occurred previously. If the last term has not occurred yet and is new to the sequence so far then, set the next term as zero. Otherwise, the next term is how far back this last term has occurred previously. Once the sequence is generated we can get our nth term easily. Below is the implementation of above approach: C++ Java Python3 C# Javascript // C++ program to print Nth// term of Van Eck's sequence #include <bits/stdc++.h>using namespace std; #define MAX 1000int sequence[MAX]; // Utility function to compute// Van Eck's sequencevoid vanEckSequence(){ // Initialize sequence array for (int i = 0; i < MAX; i++) { sequence[i] = 0; } // Loop to generate sequence for (int i = 0; i < MAX; i++) { // Check if sequence[i] has occurred // previously or is new to sequence for (int j = i - 1; j >= 0; j--) { if (sequence[j] == sequence[i]) { // If occurrence found // then the next term will be // how far back this last term // occurred previously sequence[i + 1] = i - j; break; } } }} // Utility function to return// Nth term of sequenceint getNthTerm(int n){ return sequence[n];} // Driver codeint main(){ // Pre-compute Van Eck's sequence vanEckSequence(); int n = 6; // Print nth term of the sequence cout << getNthTerm(n) << endl; n = 100; // Print nth term of the sequence cout << getNthTerm(n) << endl; return 0;} // Java program to print Nth// term of Van Eck's sequence class GFG { static int MAX = 1000; // Array to store terms of sequence static int sequence[] = new int[MAX]; // Utility function to compute // Van Eck's sequence static void vanEckSequence() { // Initialize sequence array for (int i = 0; i < MAX - 1; i++) { sequence[i] = 0; } // Loop to generate sequence for (int i = 0; i < MAX - 1; i++) { // Check if sequence[i] has occurred // previously or is new to sequence for (int j = i - 1; j >= 0; j--) { if (sequence[j] == sequence[i]) { // If occurrence found // then the next term will be // how far back this last term // occurred previously sequence[i + 1] = i - j; break; } } } } // Utility function to return // Nth term of sequence static int getNthTerm(int n) { return sequence[n]; } // Driver code public static void main(String[] args) { // Pre-compute Van Eck's sequence vanEckSequence(); int n = 6; // Print nth term of the sequence System.out.println(getNthTerm(n)); n = 100; // Print nth term of the sequence System.out.println(getNthTerm(n)); }} # Python3 program to print Nth# term of Van Eck's sequenceMAX = 1000sequence = [0] * (MAX + 1); # Utility function to compute# Van Eck's sequencedef vanEckSequence() : # Initialize sequence array for i in range(MAX) : sequence[i] = 0; # Loop to generate sequence for i in range(MAX) : # Check if sequence[i] has occurred # previously or is new to sequence for j in range(i - 1 , -1, -1) : if (sequence[j] == sequence[i]) : # If occurrence found # then the next term will be # how far back this last term # occurred previously sequence[i + 1] = i - j; break; # Utility function to return# Nth term of sequencedef getNthTerm(n) : return sequence[n]; # Driver codeif __name__ == "__main__" : # Pre-compute Van Eck's sequence vanEckSequence(); n = 6; # Print nth term of the sequence print(getNthTerm(n)); n = 100; # Print nth term of the sequence print(getNthTerm(n)); # This code is contributed by kanugargng // C# program to print Nth// term of Van Eck's sequence using System;class GFG { static int MAX = 1000; // Array to store terms of sequence static int[] sequence = new int[MAX]; // Utility function to compute // Van Eck's sequence static void vanEckSequence() { // Initialize sequence array for (int i = 0; i < MAX - 1; i++) { sequence[i] = 0; } // Loop to generate sequence for (int i = 0; i < MAX - 1; i++) { // Check if sequence[i] has occurred // previously or is new to sequence for (int j = i - 1; j >= 0; j--) { if (sequence[j] == sequence[i]) { // If occurrence found // then the next term will be // how far back this last term // occurred previously sequence[i + 1] = i - j; break; } } } } // Utility function to return // Nth term of sequence static int getNthTerm(int n) { return sequence[n]; } // Driver code public static void Main() { // Pre-compute Van Eck's sequence vanEckSequence(); int n = 6; // Print nth term of the sequence Console.WriteLine(getNthTerm(n)); n = 100; // Print nth term of the sequence Console.WriteLine(getNthTerm(n)); }} <script> function getVanEckSequence(n) { let result = [0]; let dir = {}; for( let i = 0 ; i < n ; i++) { const currentData = result[i]; const currentPosition = i + 1; // If number is already there, then insert the difference of positions. if (dir[currentData]) { result.push(currentPosition - dir[currentData]); } else { result.push(0); } // Update with the latest position dir[currentData] = currentPosition; } return result;} console.log(getVanEckSequence(100)); // This code is contributed by Devesh</script> 2 23 Time Complexity: O(MAX2) Auxiliary Space: O(MAX) Method 2: Using lambda functions There is no need to store the entire sequence to get the value of nth term. We can recursively build the series upto nth term and find only the value of nth term using the lambda expression.Below is the implementation of the above approach using lambda function: Python3 # Python3 program to find# Nth term of Van Eck's sequence# using the lambda expression # Lambda function f = lambda n, l = 0, *s : f(n-1, l in s and ~s.index(l), l, *s) \if n else -l # The above lambda function recursively# build the sequence and store it in tuple s # The expression l in s and ~s.index(l)# returns False if l is not present in tuple s# otherwise, returns the negation of the value of# the index of l in tuple s# and is appended to tuple s# Thus, tuple s store negation of all the elements# of the sequence in reverse order # At the end, when n reaches 0, function converts# the nth term back to its actual value# and returns it. # Driver coden = 6 # Get Nth term of the sequenceprint(f(n)) n = 100# Get Nth term of the sequenceprint(f(n)) 2 23 Reference: https://codegolf.stackexchange.com/questions/186654/nth-term-of-van-eck-sequence kanugargng nidhi_biet itsok gabaa406 subhammahato348 devesh ballani series Mathematical Mathematical series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program to print prime numbers from 1 to N. Segment Tree | Set 1 (Sum of given range) Modular multiplicative inverse Count all possible paths from top left to bottom right of a mXn matrix Fizz Buzz Implementation Check if a number is Palindrome Program to multiply two matrices Merge two sorted arrays with O(1) extra space Generate all permutation of a set in Python Count ways to reach the n'th stair
[ { "code": null, "e": 25963, "s": 25935, "text": "\n13 May, 2022" }, { "code": null, "e": 26148, "s": 25963, "text": "Given a positive integer N, the task is to print Nth term of the Van Eck’s sequence.In mathematics, Van Eck’s sequence is an integer sequence which is defined recursively as follows: " }, { "code": null, "e": 26184, "s": 26148, "text": "Let the first term be 0 i.e a0 = 0." }, { "code": null, "e": 26236, "s": 26184, "text": "Then for n >= 0, if there exists an m < n such that" }, { "code": null, "e": 26244, "s": 26236, "text": "am = an" }, { "code": null, "e": 26290, "s": 26244, "text": "take the largest such m and set an+1 = n − m;" }, { "code": null, "e": 26310, "s": 26290, "text": "Otherwise an+1 = 0." }, { "code": null, "e": 26329, "s": 26310, "text": "Start with a(1)=0." }, { "code": null, "e": 26385, "s": 26329, "text": "First few terms of Van Eck’s Sequence are as follows: " }, { "code": null, "e": 26447, "s": 26385, "text": "0, 0, 1, 0, 2, 0, 2, 2, 1, 6, 0, 5, 0, 2, 6, 5, 4, 0, 5 ... " }, { "code": null, "e": 26458, "s": 26447, "text": "Example: " }, { "code": null, "e": 26507, "s": 26458, "text": "Input: N = 5\nOutput: 2\n\nInput: N = 10\nOutput: 6 " }, { "code": null, "e": 26600, "s": 26507, "text": "Approach: As described above we can follow the below steps to generate Van Eck’s sequence: " }, { "code": null, "e": 26641, "s": 26600, "text": "Set the first term of the sequence as 0." }, { "code": null, "e": 26849, "s": 26641, "text": "Then Repeatedly apply: If the last term has not occurred yet and is new to the sequence so far then, set the next term as zero.Otherwise, the next term is how far back this last term has occurred previously." }, { "code": null, "e": 26954, "s": 26849, "text": "If the last term has not occurred yet and is new to the sequence so far then, set the next term as zero." }, { "code": null, "e": 27035, "s": 26954, "text": "Otherwise, the next term is how far back this last term has occurred previously." }, { "code": null, "e": 27098, "s": 27035, "text": "Once the sequence is generated we can get our nth term easily." }, { "code": null, "e": 27146, "s": 27098, "text": "Below is the implementation of above approach: " }, { "code": null, "e": 27150, "s": 27146, "text": "C++" }, { "code": null, "e": 27155, "s": 27150, "text": "Java" }, { "code": null, "e": 27163, "s": 27155, "text": "Python3" }, { "code": null, "e": 27166, "s": 27163, "text": "C#" }, { "code": null, "e": 27177, "s": 27166, "text": "Javascript" }, { "code": "// C++ program to print Nth// term of Van Eck's sequence #include <bits/stdc++.h>using namespace std; #define MAX 1000int sequence[MAX]; // Utility function to compute// Van Eck's sequencevoid vanEckSequence(){ // Initialize sequence array for (int i = 0; i < MAX; i++) { sequence[i] = 0; } // Loop to generate sequence for (int i = 0; i < MAX; i++) { // Check if sequence[i] has occurred // previously or is new to sequence for (int j = i - 1; j >= 0; j--) { if (sequence[j] == sequence[i]) { // If occurrence found // then the next term will be // how far back this last term // occurred previously sequence[i + 1] = i - j; break; } } }} // Utility function to return// Nth term of sequenceint getNthTerm(int n){ return sequence[n];} // Driver codeint main(){ // Pre-compute Van Eck's sequence vanEckSequence(); int n = 6; // Print nth term of the sequence cout << getNthTerm(n) << endl; n = 100; // Print nth term of the sequence cout << getNthTerm(n) << endl; return 0;}", "e": 28358, "s": 27177, "text": null }, { "code": "// Java program to print Nth// term of Van Eck's sequence class GFG { static int MAX = 1000; // Array to store terms of sequence static int sequence[] = new int[MAX]; // Utility function to compute // Van Eck's sequence static void vanEckSequence() { // Initialize sequence array for (int i = 0; i < MAX - 1; i++) { sequence[i] = 0; } // Loop to generate sequence for (int i = 0; i < MAX - 1; i++) { // Check if sequence[i] has occurred // previously or is new to sequence for (int j = i - 1; j >= 0; j--) { if (sequence[j] == sequence[i]) { // If occurrence found // then the next term will be // how far back this last term // occurred previously sequence[i + 1] = i - j; break; } } } } // Utility function to return // Nth term of sequence static int getNthTerm(int n) { return sequence[n]; } // Driver code public static void main(String[] args) { // Pre-compute Van Eck's sequence vanEckSequence(); int n = 6; // Print nth term of the sequence System.out.println(getNthTerm(n)); n = 100; // Print nth term of the sequence System.out.println(getNthTerm(n)); }}", "e": 29793, "s": 28358, "text": null }, { "code": "# Python3 program to print Nth# term of Van Eck's sequenceMAX = 1000sequence = [0] * (MAX + 1); # Utility function to compute# Van Eck's sequencedef vanEckSequence() : # Initialize sequence array for i in range(MAX) : sequence[i] = 0; # Loop to generate sequence for i in range(MAX) : # Check if sequence[i] has occurred # previously or is new to sequence for j in range(i - 1 , -1, -1) : if (sequence[j] == sequence[i]) : # If occurrence found # then the next term will be # how far back this last term # occurred previously sequence[i + 1] = i - j; break; # Utility function to return# Nth term of sequencedef getNthTerm(n) : return sequence[n]; # Driver codeif __name__ == \"__main__\" : # Pre-compute Van Eck's sequence vanEckSequence(); n = 6; # Print nth term of the sequence print(getNthTerm(n)); n = 100; # Print nth term of the sequence print(getNthTerm(n)); # This code is contributed by kanugargng", "e": 30886, "s": 29793, "text": null }, { "code": "// C# program to print Nth// term of Van Eck's sequence using System;class GFG { static int MAX = 1000; // Array to store terms of sequence static int[] sequence = new int[MAX]; // Utility function to compute // Van Eck's sequence static void vanEckSequence() { // Initialize sequence array for (int i = 0; i < MAX - 1; i++) { sequence[i] = 0; } // Loop to generate sequence for (int i = 0; i < MAX - 1; i++) { // Check if sequence[i] has occurred // previously or is new to sequence for (int j = i - 1; j >= 0; j--) { if (sequence[j] == sequence[i]) { // If occurrence found // then the next term will be // how far back this last term // occurred previously sequence[i + 1] = i - j; break; } } } } // Utility function to return // Nth term of sequence static int getNthTerm(int n) { return sequence[n]; } // Driver code public static void Main() { // Pre-compute Van Eck's sequence vanEckSequence(); int n = 6; // Print nth term of the sequence Console.WriteLine(getNthTerm(n)); n = 100; // Print nth term of the sequence Console.WriteLine(getNthTerm(n)); }}", "e": 32317, "s": 30886, "text": null }, { "code": "<script> function getVanEckSequence(n) { let result = [0]; let dir = {}; for( let i = 0 ; i < n ; i++) { const currentData = result[i]; const currentPosition = i + 1; // If number is already there, then insert the difference of positions. if (dir[currentData]) { result.push(currentPosition - dir[currentData]); } else { result.push(0); } // Update with the latest position dir[currentData] = currentPosition; } return result;} console.log(getVanEckSequence(100)); // This code is contributed by Devesh</script>", "e": 32956, "s": 32317, "text": null }, { "code": null, "e": 32961, "s": 32956, "text": "2\n23" }, { "code": null, "e": 32988, "s": 32963, "text": "Time Complexity: O(MAX2)" }, { "code": null, "e": 33012, "s": 32988, "text": "Auxiliary Space: O(MAX)" }, { "code": null, "e": 33310, "s": 33012, "text": "Method 2: Using lambda functions There is no need to store the entire sequence to get the value of nth term. We can recursively build the series upto nth term and find only the value of nth term using the lambda expression.Below is the implementation of the above approach using lambda function: " }, { "code": null, "e": 33318, "s": 33310, "text": "Python3" }, { "code": "# Python3 program to find# Nth term of Van Eck's sequence# using the lambda expression # Lambda function f = lambda n, l = 0, *s : f(n-1, l in s and ~s.index(l), l, *s) \\if n else -l # The above lambda function recursively# build the sequence and store it in tuple s # The expression l in s and ~s.index(l)# returns False if l is not present in tuple s# otherwise, returns the negation of the value of# the index of l in tuple s# and is appended to tuple s# Thus, tuple s store negation of all the elements# of the sequence in reverse order # At the end, when n reaches 0, function converts# the nth term back to its actual value# and returns it. # Driver coden = 6 # Get Nth term of the sequenceprint(f(n)) n = 100# Get Nth term of the sequenceprint(f(n))", "e": 34078, "s": 33318, "text": null }, { "code": null, "e": 34083, "s": 34078, "text": "2\n23" }, { "code": null, "e": 34178, "s": 34085, "text": "Reference: https://codegolf.stackexchange.com/questions/186654/nth-term-of-van-eck-sequence " }, { "code": null, "e": 34189, "s": 34178, "text": "kanugargng" }, { "code": null, "e": 34200, "s": 34189, "text": "nidhi_biet" }, { "code": null, "e": 34206, "s": 34200, "text": "itsok" }, { "code": null, "e": 34215, "s": 34206, "text": "gabaa406" }, { "code": null, "e": 34231, "s": 34215, "text": "subhammahato348" }, { "code": null, "e": 34246, "s": 34231, "text": "devesh ballani" }, { "code": null, "e": 34253, "s": 34246, "text": "series" }, { "code": null, "e": 34266, "s": 34253, "text": "Mathematical" }, { "code": null, "e": 34279, "s": 34266, "text": "Mathematical" }, { "code": null, "e": 34286, "s": 34279, "text": "series" }, { "code": null, "e": 34384, "s": 34286, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34428, "s": 34384, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 34470, "s": 34428, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 34501, "s": 34470, "text": "Modular multiplicative inverse" }, { "code": null, "e": 34572, "s": 34501, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 34597, "s": 34572, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 34629, "s": 34597, "text": "Check if a number is Palindrome" }, { "code": null, "e": 34662, "s": 34629, "text": "Program to multiply two matrices" }, { "code": null, "e": 34708, "s": 34662, "text": "Merge two sorted arrays with O(1) extra space" }, { "code": null, "e": 34752, "s": 34708, "text": "Generate all permutation of a set in Python" } ]
turtle.distance() function in Python - GeeksforGeeks
26 Nov, 2021 The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses tkinter for the underlying graphics, it needs a version of Python installed with Tk support. This method is used to return the distance from the turtle to (x,y) in turtle step units. Syntax : turtle.distance(x, y=None) Parameters: x: x coordinate of Vector 2DVec. y: y coordinate of Vector 2DVec. This method can be called in different formats as given below : distance(x, y) # two coordinates distance((x, y)) # a pair (tuple) of coordinates distance(vec) # e.g. as returned by pos() distance(mypen) # where mypen is another turtle Below is the implementation of the above method with some examples : Example 1 : Python3 # importing packageimport turtle # print the distance# before any motionprint(turtle.distance()) # forward turtle by 100turtle.forward(100) # print the distance# after a motionprint(turtle.distance()) Output : 0.0 100.0 Example 2 : Python3 # importing packageimport turtle # print distance (default)print(turtle.distance()) for i in range(4): # draw one quadrant turtle.circle(50,90) # print distance print(turtle.distance()) Output : 0.0 70.7106781187 100.0 70.7106781187 1.41063873243e-14 Example 3: Python3 # importing packageimport turtle # print distance with arguments# in different formatsprint(turtle.distance(3,4))print(turtle.distance((3,4)))print(turtle.distance((30.0,40.0))) Output : 5.0 5.0 50.0 sagar0719kumar clintra Python-turtle Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Defaultdict in Python Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n26 Nov, 2021" }, { "code": null, "e": 25754, "s": 25537, "text": "The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses tkinter for the underlying graphics, it needs a version of Python installed with Tk support." }, { "code": null, "e": 25845, "s": 25754, "text": "This method is used to return the distance from the turtle to (x,y) in turtle step units. " }, { "code": null, "e": 25883, "s": 25845, "text": "Syntax : turtle.distance(x, y=None) " }, { "code": null, "e": 25895, "s": 25883, "text": "Parameters:" }, { "code": null, "e": 25929, "s": 25895, "text": "x: x coordinate of Vector 2DVec. " }, { "code": null, "e": 25962, "s": 25929, "text": "y: y coordinate of Vector 2DVec." }, { "code": null, "e": 26026, "s": 25962, "text": "This method can be called in different formats as given below :" }, { "code": null, "e": 26201, "s": 26026, "text": "distance(x, y) # two coordinates\n\ndistance((x, y)) # a pair (tuple) of coordinates\n\ndistance(vec) # e.g. as returned by pos()\n\ndistance(mypen) # where mypen is another turtle" }, { "code": null, "e": 26270, "s": 26201, "text": "Below is the implementation of the above method with some examples :" }, { "code": null, "e": 26282, "s": 26270, "text": "Example 1 :" }, { "code": null, "e": 26290, "s": 26282, "text": "Python3" }, { "code": "# importing packageimport turtle # print the distance# before any motionprint(turtle.distance()) # forward turtle by 100turtle.forward(100) # print the distance# after a motionprint(turtle.distance())", "e": 26491, "s": 26290, "text": null }, { "code": null, "e": 26500, "s": 26491, "text": "Output :" }, { "code": null, "e": 26510, "s": 26500, "text": "0.0\n100.0" }, { "code": null, "e": 26522, "s": 26510, "text": "Example 2 :" }, { "code": null, "e": 26530, "s": 26522, "text": "Python3" }, { "code": "# importing packageimport turtle # print distance (default)print(turtle.distance()) for i in range(4): # draw one quadrant turtle.circle(50,90) # print distance print(turtle.distance())", "e": 26738, "s": 26530, "text": null }, { "code": null, "e": 26747, "s": 26738, "text": "Output :" }, { "code": null, "e": 26804, "s": 26747, "text": "0.0\n70.7106781187\n100.0\n70.7106781187\n1.41063873243e-14 " }, { "code": null, "e": 26816, "s": 26804, "text": "Example 3: " }, { "code": null, "e": 26824, "s": 26816, "text": "Python3" }, { "code": "# importing packageimport turtle # print distance with arguments# in different formatsprint(turtle.distance(3,4))print(turtle.distance((3,4)))print(turtle.distance((30.0,40.0)))", "e": 27002, "s": 26824, "text": null }, { "code": null, "e": 27011, "s": 27002, "text": "Output :" }, { "code": null, "e": 27024, "s": 27011, "text": "5.0\n5.0\n50.0" }, { "code": null, "e": 27039, "s": 27024, "text": "sagar0719kumar" }, { "code": null, "e": 27047, "s": 27039, "text": "clintra" }, { "code": null, "e": 27061, "s": 27047, "text": "Python-turtle" }, { "code": null, "e": 27068, "s": 27061, "text": "Python" }, { "code": null, "e": 27166, "s": 27068, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27198, "s": 27166, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27240, "s": 27198, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27282, "s": 27240, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27338, "s": 27282, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27365, "s": 27338, "text": "Python Classes and Objects" }, { "code": null, "e": 27404, "s": 27365, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27435, "s": 27404, "text": "Python | os.path.join() method" }, { "code": null, "e": 27457, "s": 27435, "text": "Defaultdict in Python" }, { "code": null, "e": 27486, "s": 27457, "text": "Create a directory in Python" } ]
Python - Change Datatype of Tuple Values - GeeksforGeeks
26 May, 2020 Sometimes, while working with set of records, we can have a problem in which we need to perform a data type change of values of tuples, which are in its 2nd position, i.e value position. This kind of problem can occur in all domains that include data manipulations. Let’s discuss certain ways in which this task can be performed. Input : test_list = [(44, 5.6), (16, 10)] Output : [(44, '5.6'), (16, '10')] Input : test_list = [(44, 5.8)] Output : [(44, '5.8')] Method #1 : Using enumerate() + loopThis is brute force way in which this problem can be solved. In this, we reassign the tuple values, by changing required index of tuple to type cast using appropriate datatype conversion functions. # Python3 code to demonstrate working of # Change Datatype of Tuple Values# Using enumerate() + loop # initializing listtest_list = [(4, 5), (6, 7), (1, 4), (8, 10)] # printing original listprint("The original list is : " + str(test_list)) # Change Datatype of Tuple Values# Using enumerate() + loop# converting to string using str()for idx, (x, y) in enumerate(test_list): test_list[idx] = (x, str(y)) # printing result print("The converted records : " + str(test_list)) The original list is : [(4, 5), (6, 7), (1, 4), (8, 10)] The converted records : [(4, '5'), (6, '7'), (1, '4'), (8, '10')] Method #2 : Using list comprehensionThe above functionality can also be used to solve this problem. In this, we perform similar task as above method, just in one liner way using list comprehension. # Python3 code to demonstrate working of # Change Datatype of Tuple Values# Using list comprehension # initializing listtest_list = [(4, 5), (6, 7), (1, 4), (8, 10)] # printing original listprint("The original list is : " + str(test_list)) # Change Datatype of Tuple Values# Using list comprehension# converting to string using str()res = [(x, str(y)) for x, y in test_list] # printing result print("The converted records : " + str(res)) The original list is : [(4, 5), (6, 7), (1, 4), (8, 10)] The converted records : [(4, '5'), (6, '7'), (1, '4'), (8, '10')] 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 ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25537, "s": 25509, "text": "\n26 May, 2020" }, { "code": null, "e": 25867, "s": 25537, "text": "Sometimes, while working with set of records, we can have a problem in which we need to perform a data type change of values of tuples, which are in its 2nd position, i.e value position. This kind of problem can occur in all domains that include data manipulations. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 26001, "s": 25867, "text": "Input : test_list = [(44, 5.6), (16, 10)]\nOutput : [(44, '5.6'), (16, '10')]\n\nInput : test_list = [(44, 5.8)]\nOutput : [(44, '5.8')]\n" }, { "code": null, "e": 26235, "s": 26001, "text": "Method #1 : Using enumerate() + loopThis is brute force way in which this problem can be solved. In this, we reassign the tuple values, by changing required index of tuple to type cast using appropriate datatype conversion functions." }, { "code": "# Python3 code to demonstrate working of # Change Datatype of Tuple Values# Using enumerate() + loop # initializing listtest_list = [(4, 5), (6, 7), (1, 4), (8, 10)] # printing original listprint(\"The original list is : \" + str(test_list)) # Change Datatype of Tuple Values# Using enumerate() + loop# converting to string using str()for idx, (x, y) in enumerate(test_list): test_list[idx] = (x, str(y)) # printing result print(\"The converted records : \" + str(test_list)) ", "e": 26715, "s": 26235, "text": null }, { "code": null, "e": 26839, "s": 26715, "text": "The original list is : [(4, 5), (6, 7), (1, 4), (8, 10)]\nThe converted records : [(4, '5'), (6, '7'), (1, '4'), (8, '10')]\n" }, { "code": null, "e": 27039, "s": 26841, "text": "Method #2 : Using list comprehensionThe above functionality can also be used to solve this problem. In this, we perform similar task as above method, just in one liner way using list comprehension." }, { "code": "# Python3 code to demonstrate working of # Change Datatype of Tuple Values# Using list comprehension # initializing listtest_list = [(4, 5), (6, 7), (1, 4), (8, 10)] # printing original listprint(\"The original list is : \" + str(test_list)) # Change Datatype of Tuple Values# Using list comprehension# converting to string using str()res = [(x, str(y)) for x, y in test_list] # printing result print(\"The converted records : \" + str(res)) ", "e": 27482, "s": 27039, "text": null }, { "code": null, "e": 27606, "s": 27482, "text": "The original list is : [(4, 5), (6, 7), (1, 4), (8, 10)]\nThe converted records : [(4, '5'), (6, '7'), (1, '4'), (8, '10')]\n" }, { "code": null, "e": 27627, "s": 27606, "text": "Python list-programs" }, { "code": null, "e": 27634, "s": 27627, "text": "Python" }, { "code": null, "e": 27650, "s": 27634, "text": "Python Programs" }, { "code": null, "e": 27748, "s": 27650, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27780, "s": 27748, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27822, "s": 27780, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27864, "s": 27822, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27891, "s": 27864, "text": "Python Classes and Objects" }, { "code": null, "e": 27947, "s": 27891, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27969, "s": 27947, "text": "Defaultdict in Python" }, { "code": null, "e": 28008, "s": 27969, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 28054, "s": 28008, "text": "Python | Split string into list of characters" }, { "code": null, "e": 28092, "s": 28054, "text": "Python | Convert a list to dictionary" } ]
Strings in Dart - GeeksforGeeks
10 Jun, 2021 A Dart string is a sequence of UTF-16 code units. With the same rule as that of Python, you can use either single or double quotes to create a string. The string starts with the datatype Var : var string = "I love GeeksforGeeks"; var string1 = 'GeeksforGeeks is a great platform for upgrading skills'; Both the strings above when running on a Dart editor will work perfectly. You can put the value of an expression inside a string by using ${expression}. It will help the strings to concatenate very easily. If the expression is an identifier, you can skip the {}. Dart void main () {var string = 'I do coding';var string1 = '$string on Geeks for Geeks';print (string1);} Output : I do coding on Geeks for Geeks. Dart also allows us to concatenate the string by + operator as well as we can just separate the two strings by Quotes. The concatenation also works over line breaks which is itself a very useful feature. Dart var string = 'Geeks''for''Geeks';var str = 'Coding is ';var str1 = 'Fun';print (string);print (str + str1); Output : GeeksforGeeks Coding is Fun We can also check whether two strings are equal by == operator. It compares every element of the first string with every element of the second string. Dart void main(){var str = 'Geeks';var str1 = 'Geeks';if (str == str1){print (True);}} Output : True Raw strings are useful when you want to define a String that has a lot of special characters. We can create a raw string by prefixing it with r . Dart void main() { var gfg = r'This is a raw string'; print(gfg);} Output: This is a raw string almostsagar Dart-String strings Dart Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flutter - Custom Bottom Navigation Bar ListView Class in Flutter Flutter - Flexible Widget Flutter - Stack Widget Flutter - Dialogs Android Studio Setup for Flutter Development Flutter - Positioned Widget Format Dates in Flutter Flutter - Managing the MediaQuery Object What is widgets in Flutter?
[ { "code": null, "e": 25285, "s": 25257, "text": "\n10 Jun, 2021" }, { "code": null, "e": 25479, "s": 25285, "text": "A Dart string is a sequence of UTF-16 code units. With the same rule as that of Python, you can use either single or double quotes to create a string. The string starts with the datatype Var : " }, { "code": null, "e": 25588, "s": 25479, "text": "var string = \"I love GeeksforGeeks\";\nvar string1 = 'GeeksforGeeks is a great platform for upgrading skills';" }, { "code": null, "e": 25662, "s": 25588, "text": "Both the strings above when running on a Dart editor will work perfectly." }, { "code": null, "e": 25852, "s": 25662, "text": "You can put the value of an expression inside a string by using ${expression}. It will help the strings to concatenate very easily. If the expression is an identifier, you can skip the {}. " }, { "code": null, "e": 25857, "s": 25852, "text": "Dart" }, { "code": "void main () {var string = 'I do coding';var string1 = '$string on Geeks for Geeks';print (string1);}", "e": 25959, "s": 25857, "text": null }, { "code": null, "e": 25969, "s": 25959, "text": " Output :" }, { "code": null, "e": 26001, "s": 25969, "text": "I do coding on Geeks for Geeks." }, { "code": null, "e": 26205, "s": 26001, "text": "Dart also allows us to concatenate the string by + operator as well as we can just separate the two strings by Quotes. The concatenation also works over line breaks which is itself a very useful feature." }, { "code": null, "e": 26210, "s": 26205, "text": "Dart" }, { "code": "var string = 'Geeks''for''Geeks';var str = 'Coding is ';var str1 = 'Fun';print (string);print (str + str1);", "e": 26318, "s": 26210, "text": null }, { "code": null, "e": 26327, "s": 26318, "text": "Output :" }, { "code": null, "e": 26355, "s": 26327, "text": "GeeksforGeeks\nCoding is Fun" }, { "code": null, "e": 26506, "s": 26355, "text": "We can also check whether two strings are equal by == operator. It compares every element of the first string with every element of the second string." }, { "code": null, "e": 26511, "s": 26506, "text": "Dart" }, { "code": "void main(){var str = 'Geeks';var str1 = 'Geeks';if (str == str1){print (True);}}", "e": 26593, "s": 26511, "text": null }, { "code": null, "e": 26603, "s": 26593, "text": "Output : " }, { "code": null, "e": 26608, "s": 26603, "text": "True" }, { "code": null, "e": 26755, "s": 26608, "text": "Raw strings are useful when you want to define a String that has a lot of special characters. We can create a raw string by prefixing it with r . " }, { "code": null, "e": 26760, "s": 26755, "text": "Dart" }, { "code": "void main() { var gfg = r'This is a raw string'; print(gfg);}", "e": 26827, "s": 26760, "text": null }, { "code": null, "e": 26835, "s": 26827, "text": "Output:" }, { "code": null, "e": 26856, "s": 26835, "text": "This is a raw string" }, { "code": null, "e": 26868, "s": 26856, "text": "almostsagar" }, { "code": null, "e": 26880, "s": 26868, "text": "Dart-String" }, { "code": null, "e": 26888, "s": 26880, "text": "strings" }, { "code": null, "e": 26893, "s": 26888, "text": "Dart" }, { "code": null, "e": 26991, "s": 26893, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27030, "s": 26991, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 27056, "s": 27030, "text": "ListView Class in Flutter" }, { "code": null, "e": 27082, "s": 27056, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 27105, "s": 27082, "text": "Flutter - Stack Widget" }, { "code": null, "e": 27123, "s": 27105, "text": "Flutter - Dialogs" }, { "code": null, "e": 27168, "s": 27123, "text": "Android Studio Setup for Flutter Development" }, { "code": null, "e": 27196, "s": 27168, "text": "Flutter - Positioned Widget" }, { "code": null, "e": 27220, "s": 27196, "text": "Format Dates in Flutter" }, { "code": null, "e": 27261, "s": 27220, "text": "Flutter - Managing the MediaQuery Object" } ]
Get Bank details from IFSC Code Using Python - GeeksforGeeks
11 Oct, 2020 The Indian Financial System Code (IFSC) is an 11-digit alpha-numeric code used to uniquely classify bank branches within the National Electronic Fund Transfer (NEFT) network by the Central Bank. In this article, we are going to write python scripts to get details of the Bank from the given IFSC code. Module Used: ifscapi: The IfscApi Module will help to collect the details of the bank. The IFSC API was designed to easily get the specifics of the BANK from the IFSC code. Installation: pip install ifscApi Step-by-step Approach: Import module. Parse the IFSC code into getdata() function (object of FetchData). Above step returns a dictionary approach along with timeto fetch the details. Display bank details Below is complete program of the above approach: Python3 # Import required modulefrom ifscApi.getDetails import FetchData # Assign IFSC codeifsc = 'KKBK0005652' # Parse the ifsc codedata = FetchData().getdata(ifsc) # Display detailsprint(data) Output: Note: The dbFilePath parameter of getdata() function can be overwritten with IFSC code Database which has a table named data and consists of three columns Ifsc, bank, address. In this method, we are going to use Razorpay IFSC Toolkit to fetch IFSC code. Modules: requests: This module allows you to send HTTP/1.1 requests extremely easily. The get() method of this module is used to get bank details from IFSC code. Installation: pip install requests Below is working of Razorpay IFSC Toolkit to fetch bank details from IFSC code. Step-by-step Approach: Import module. Pass URL and IFSC code into requests.get() function. Fetch this JSON response. And it returns bank details in a Dict data-type. Below is complete program of the above approach: Python3 # Import required modulesimport requests # Assign IFSC code and URLIFSC_Code = 'KKBK0005652'URL = "https://ifsc.razorpay.com/" # Use get() methoddata = requests.get(URL+IFSC_Code).json() # Display bank detailsprint(data) Output: python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Defaultdict in Python Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n11 Oct, 2020" }, { "code": null, "e": 25732, "s": 25537, "text": "The Indian Financial System Code (IFSC) is an 11-digit alpha-numeric code used to uniquely classify bank branches within the National Electronic Fund Transfer (NEFT) network by the Central Bank." }, { "code": null, "e": 25839, "s": 25732, "text": "In this article, we are going to write python scripts to get details of the Bank from the given IFSC code." }, { "code": null, "e": 25852, "s": 25839, "text": "Module Used:" }, { "code": null, "e": 26012, "s": 25852, "text": "ifscapi: The IfscApi Module will help to collect the details of the bank. The IFSC API was designed to easily get the specifics of the BANK from the IFSC code." }, { "code": null, "e": 26026, "s": 26012, "text": "Installation:" }, { "code": null, "e": 26047, "s": 26026, "text": "pip install ifscApi\n" }, { "code": null, "e": 26070, "s": 26047, "text": "Step-by-step Approach:" }, { "code": null, "e": 26085, "s": 26070, "text": "Import module." }, { "code": null, "e": 26152, "s": 26085, "text": "Parse the IFSC code into getdata() function (object of FetchData)." }, { "code": null, "e": 26230, "s": 26152, "text": "Above step returns a dictionary approach along with timeto fetch the details." }, { "code": null, "e": 26251, "s": 26230, "text": "Display bank details" }, { "code": null, "e": 26300, "s": 26251, "text": "Below is complete program of the above approach:" }, { "code": null, "e": 26308, "s": 26300, "text": "Python3" }, { "code": "# Import required modulefrom ifscApi.getDetails import FetchData # Assign IFSC codeifsc = 'KKBK0005652' # Parse the ifsc codedata = FetchData().getdata(ifsc) # Display detailsprint(data)", "e": 26498, "s": 26308, "text": null }, { "code": null, "e": 26506, "s": 26498, "text": "Output:" }, { "code": null, "e": 26682, "s": 26506, "text": "Note: The dbFilePath parameter of getdata() function can be overwritten with IFSC code Database which has a table named data and consists of three columns Ifsc, bank, address." }, { "code": null, "e": 26761, "s": 26682, "text": "In this method, we are going to use Razorpay IFSC Toolkit to fetch IFSC code. " }, { "code": null, "e": 26770, "s": 26761, "text": "Modules:" }, { "code": null, "e": 26923, "s": 26770, "text": "requests: This module allows you to send HTTP/1.1 requests extremely easily. The get() method of this module is used to get bank details from IFSC code." }, { "code": null, "e": 26937, "s": 26923, "text": "Installation:" }, { "code": null, "e": 26959, "s": 26937, "text": "pip install requests\n" }, { "code": null, "e": 27039, "s": 26959, "text": "Below is working of Razorpay IFSC Toolkit to fetch bank details from IFSC code." }, { "code": null, "e": 27062, "s": 27039, "text": "Step-by-step Approach:" }, { "code": null, "e": 27077, "s": 27062, "text": "Import module." }, { "code": null, "e": 27130, "s": 27077, "text": "Pass URL and IFSC code into requests.get() function." }, { "code": null, "e": 27156, "s": 27130, "text": "Fetch this JSON response." }, { "code": null, "e": 27205, "s": 27156, "text": "And it returns bank details in a Dict data-type." }, { "code": null, "e": 27254, "s": 27205, "text": "Below is complete program of the above approach:" }, { "code": null, "e": 27262, "s": 27254, "text": "Python3" }, { "code": "# Import required modulesimport requests # Assign IFSC code and URLIFSC_Code = 'KKBK0005652'URL = \"https://ifsc.razorpay.com/\" # Use get() methoddata = requests.get(URL+IFSC_Code).json() # Display bank detailsprint(data)", "e": 27486, "s": 27262, "text": null }, { "code": null, "e": 27494, "s": 27486, "text": "Output:" }, { "code": null, "e": 27509, "s": 27494, "text": "python-utility" }, { "code": null, "e": 27516, "s": 27509, "text": "Python" }, { "code": null, "e": 27614, "s": 27516, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27646, "s": 27614, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27688, "s": 27646, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27730, "s": 27688, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27786, "s": 27730, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27813, "s": 27786, "text": "Python Classes and Objects" }, { "code": null, "e": 27852, "s": 27813, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27883, "s": 27852, "text": "Python | os.path.join() method" }, { "code": null, "e": 27905, "s": 27883, "text": "Defaultdict in Python" }, { "code": null, "e": 27934, "s": 27905, "text": "Create a directory in Python" } ]
Remove a character from a string to make it a palindrome - GeeksforGeeks
07 Mar, 2022 Given a string, we need to check whether it is possible to make this string a palindrome after removing exactly one character from this. Examples: Input : str = “abcba” Output : Yes we can remove character ‘c’ to make string palindrome Input : str = “abcbea” Output : Yes we can remove character ‘e’ to make string palindrome Input : str = “abecbea” It is not possible to make this string palindrome just by removing one character We can solve this problem by finding the position of mismatch. We start looping in the string by keeping two pointers at both the ends which traverse towards mid position after each iteration, this iteration will stop when we find a mismatch, as it is allowed to remove just one character we have two choices here, At mismatch, either remove character pointed by left pointer or remove character pointed by right pointer.We will check both the cases, remember as we have traversed equal number of steps from both sides, this mid string should also be a palindrome after removing one character, so we check two substrings, one by removing left character and one by removing right character and if one of them is palindrome then we can make complete string palindrome by removing corresponding character, and if both substrings are not palindrome then it is not possible to make complete string a palindrome under given constraint. C++ Java Python3 C# Javascript // C/C++ program to check whether it is possible to make// string palindrome by removing one character#include <bits/stdc++.h>using namespace std; // Utility method to check if substring from low to high is// palindrome or not.bool isPalindrome(string::iterator low, string::iterator high){ while (low < high) { if (*low != *high) return false; low++; high--; } return true;} // This method returns -1 if it is not possible to make string// a palindrome. It returns -2 if string is already a palindrome.// Otherwise it returns index of character whose removal can// make the whole string palindrome.int possiblePalinByRemovingOneChar(string str){ // Initialize low and right by both the ends of the string int low = 0, high = str.length() - 1; // loop until low and high cross each other while (low < high) { // If both characters are equal then move both pointer // towards end if (str[low] == str[high]) { low++; high--; } else { /* If removing str[low] makes the whole string palindrome. We basically check if substring str[low+1..high] is palindrome or not. */ if (isPalindrome(str.begin() + low + 1, str.begin() + high)) return low; /* If removing str[high] makes the whole string palindrome We basically check if substring str[low+1..high] is palindrome or not. */ if (isPalindrome(str.begin() + low, str.begin() + high - 1)) return high; return -1; } } // We reach here when complete string will be palindrome // if complete string is palindrome then return mid character return -2;} // Driver code to test above methodsint main(){ string str = "abecbea"; int idx = possiblePalinByRemovingOneChar(str); if (idx == -1) cout << "Not Possible \n"; else if (idx == -2) cout << "Possible without removing any character"; else cout << "Possible by removing character" << " at index " << idx << "\n"; return 0;} // Java program to check whether// it is possible to make string// palindrome by removing one characterimport java.util.*; class GFG{ // Utility method to check if // substring from low to high is // palindrome or not. static boolean isPalindrome(String str, int low, int high) { while (low < high) { if (str.charAt(low) != str.charAt(high)) return false; low++; high--; } return true; } // This method returns -1 if it is // not possible to make string a palindrome. // It returns -2 if string is already // a palindrome. Otherwise it returns // index of character whose removal can // make the whole string palindrome. static int possiblePalinByRemovingOneChar(String str) { // Initialize low and right // by both the ends of the string int low = 0, high = str.length() - 1; // loop until low and // high cross each other while (low < high) { // If both characters are equal then // move both pointer towards end if (str.charAt(low) == str.charAt(high)) { low++; high--; } else { /* * If removing str[low] makes the * whole string palindrome. We basically * check if substring str[low+1..high] * is palindrome or not. */ if (isPalindrome(str, low + 1, high)) return low; /* * If removing str[high] makes the whole string * palindrome. We basically check if substring * str[low+1..high] is palindrome or not. */ if (isPalindrome(str, low, high - 1)) return high; return -1; } } // We reach here when complete string // will be palindrome if complete string // is palindrome then return mid character return -2; } // Driver Code public static void main(String[] args) { String str = "abecbea"; int idx = possiblePalinByRemovingOneChar(str); if (idx == -1) System.out.println("Not Possible"); else if (idx == -2) System.out.println("Possible without " + "removing any character"); else System.out.println("Possible by removing" + " character at index " + idx); }} // This code is contributed by// sanjeev2552 # Python program to check whether it is possible to make# string palindrome by removing one character # Utility method to check if substring from# low to high is palindrome or not.def isPalindrome(string: str, low: int, high: int) -> bool: while low < high: if string[low] != string[high]: return False low += 1 high -= 1 return True # This method returns -1 if it# is not possible to make string# a palindrome. It returns -2 if# string is already a palindrome.# Otherwise it returns index of# character whose removal can# make the whole string palindrome.def possiblepalinByRemovingOneChar(string: str) -> int: # Initialize low and right by # both the ends of the string low = 0 high = len(string) - 1 # loop until low and high cross each other while low < high: # If both characters are equal then # move both pointer towards end if string[low] == string[high]: low += 1 high -= 1 else: # If removing str[low] makes the whole string palindrome. # We basically check if substring str[low+1..high] is # palindrome or not. if isPalindrome(string, low + 1, high): return low # If removing str[high] makes the whole string palindrome # We basically check if substring str[low+1..high] is # palindrome or not if isPalindrome(string, low, high - 1): return high return -1 # We reach here when complete string will be palindrome # if complete string is palindrome then return mid character return -2 # Driver Codeif __name__ == "__main__": string = "abecbea" idx = possiblepalinByRemovingOneChar(string) if idx == -1: print("Not possible") else if idx == -2: print("Possible without removing any character") else: print("Possible by removing character at index", idx) # This code is contributed by# sanjeev2552 // C# program to check whether// it is possible to make string// palindrome by removing one characterusing System;class GFG{ // Utility method to check if // substring from low to high is // palindrome or not. static bool isPalindrome(string str, int low, int high) { while (low < high) { if (str[low] != str[high]) return false; low++; high--; } return true; } // This method returns -1 if it is // not possible to make string a palindrome. // It returns -2 if string is already // a palindrome. Otherwise it returns // index of character whose removal can // make the whole string palindrome. static int possiblePalinByRemovingOneChar(string str) { // Initialize low and right // by both the ends of the string int low = 0, high = str.Length - 1; // loop until low and // high cross each other while (low < high) { // If both characters are equal then // move both pointer towards end if (str[low] == str[high]) { low++; high--; } else { /* * If removing str[low] makes the * whole string palindrome. We basically * check if substring str[low+1..high] * is palindrome or not. */ if (isPalindrome(str, low + 1, high)) return low; /* * If removing str[high] makes the whole string * palindrome. We basically check if substring * str[low+1..high] is palindrome or not. */ if (isPalindrome(str, low, high - 1)) return high; return -1; } } // We reach here when complete string // will be palindrome if complete string // is palindrome then return mid character return -2; } // Driver Code public static void Main(String[] args) { string str = "abecbea"; int idx = possiblePalinByRemovingOneChar(str); if (idx == -1) Console.Write("Not Possible"); else if (idx == -2) Console.Write("Possible without " + "removing any character"); else Console.Write("Possible by removing" + " character at index " + idx); }} // This code is contributed by shivanisinghss2110 <script>// JavaScript program to check whether// it is possible to make string// palindrome by removing one character// Utility method to check if// substring from low to high is// palindrome or not.function isPalindrome(str, low, high) { while (low < high) { if (str.charAt(low) != str.charAt(high)) return false; low++; high--; } return true; } // This method returns -1 if it is // not possible to make string a palindrome. // It returns -2 if string is already // a palindrome. Otherwise it returns // index of character whose removal can // make the whole string palindrome. function possiblePalinByRemovingOneChar(str) { // Initialize low and right // by both the ends of the string var low = 0, high = str.length - 1; // loop until low and // high cross each other while (low < high) { // If both characters are equal then // move both pointer towards end if (str.charAt(low) == str.charAt(high)) { low++; high--; } else { /* * If removing str[low] makes the * whole string palindrome. We basically * check if substring str[low+1..high] * is palindrome or not. */ if (isPalindrome(str, low + 1, high)) return low; /* * If removing str[high] makes the whole string * palindrome. We basically check if substring * str[low+1..high] is palindrome or not. */ if (isPalindrome(str, low, high - 1)) return high; return -1; } } // We reach here when complete string // will be palindrome if complete string // is palindrome then return mid character return -2; } // Driver Code var str = "abecbea"; var idx = possiblePalinByRemovingOneChar(str); if (idx == -1) document.write("Not Possible"); else if (idx == -2) document.write("Possible without " + "removing any character"); else document.write("Possible by removing" + " character at index " + idx); // this code is contributed by shivanisinghss2110</script> Output: Not Possible Time complexity : O(N) Space Complexity: O(1) This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. sanjeev2552 divyanshukla777 sooda367 anikaseth98 shivanisinghss2110 simmytarika5 Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Check for Balanced Brackets in an expression (well-formedness) using Stack Python program to check if a string is palindrome or not KMP Algorithm for Pattern Searching Different methods to reverse a string in C/C++ Array of Strings in C++ (5 Different Ways to Create) Convert string to char array in C++ Caesar Cipher in Cryptography Check whether two strings are anagram of each other Top 50 String Coding Problems for Interviews Length of the longest substring without repeating characters
[ { "code": null, "e": 26109, "s": 26081, "text": "\n07 Mar, 2022" }, { "code": null, "e": 26247, "s": 26109, "text": "Given a string, we need to check whether it is possible to make this string a palindrome after removing exactly one character from this. " }, { "code": null, "e": 26259, "s": 26247, "text": "Examples: " }, { "code": null, "e": 26549, "s": 26259, "text": "Input : str = “abcba”\nOutput : Yes\nwe can remove character ‘c’ to make string palindrome\n\nInput : str = “abcbea”\nOutput : Yes\nwe can remove character ‘e’ to make string palindrome\n\nInput : str = “abecbea”\nIt is not possible to make this string palindrome \njust by removing one character " }, { "code": null, "e": 26864, "s": 26549, "text": "We can solve this problem by finding the position of mismatch. We start looping in the string by keeping two pointers at both the ends which traverse towards mid position after each iteration, this iteration will stop when we find a mismatch, as it is allowed to remove just one character we have two choices here," }, { "code": null, "e": 27480, "s": 26864, "text": "At mismatch, either remove character pointed by left pointer or remove character pointed by right pointer.We will check both the cases, remember as we have traversed equal number of steps from both sides, this mid string should also be a palindrome after removing one character, so we check two substrings, one by removing left character and one by removing right character and if one of them is palindrome then we can make complete string palindrome by removing corresponding character, and if both substrings are not palindrome then it is not possible to make complete string a palindrome under given constraint. " }, { "code": null, "e": 27484, "s": 27480, "text": "C++" }, { "code": null, "e": 27489, "s": 27484, "text": "Java" }, { "code": null, "e": 27497, "s": 27489, "text": "Python3" }, { "code": null, "e": 27500, "s": 27497, "text": "C#" }, { "code": null, "e": 27511, "s": 27500, "text": "Javascript" }, { "code": "// C/C++ program to check whether it is possible to make// string palindrome by removing one character#include <bits/stdc++.h>using namespace std; // Utility method to check if substring from low to high is// palindrome or not.bool isPalindrome(string::iterator low, string::iterator high){ while (low < high) { if (*low != *high) return false; low++; high--; } return true;} // This method returns -1 if it is not possible to make string// a palindrome. It returns -2 if string is already a palindrome.// Otherwise it returns index of character whose removal can// make the whole string palindrome.int possiblePalinByRemovingOneChar(string str){ // Initialize low and right by both the ends of the string int low = 0, high = str.length() - 1; // loop until low and high cross each other while (low < high) { // If both characters are equal then move both pointer // towards end if (str[low] == str[high]) { low++; high--; } else { /* If removing str[low] makes the whole string palindrome. We basically check if substring str[low+1..high] is palindrome or not. */ if (isPalindrome(str.begin() + low + 1, str.begin() + high)) return low; /* If removing str[high] makes the whole string palindrome We basically check if substring str[low+1..high] is palindrome or not. */ if (isPalindrome(str.begin() + low, str.begin() + high - 1)) return high; return -1; } } // We reach here when complete string will be palindrome // if complete string is palindrome then return mid character return -2;} // Driver code to test above methodsint main(){ string str = \"abecbea\"; int idx = possiblePalinByRemovingOneChar(str); if (idx == -1) cout << \"Not Possible \\n\"; else if (idx == -2) cout << \"Possible without removing any character\"; else cout << \"Possible by removing character\" << \" at index \" << idx << \"\\n\"; return 0;}", "e": 29673, "s": 27511, "text": null }, { "code": "// Java program to check whether// it is possible to make string// palindrome by removing one characterimport java.util.*; class GFG{ // Utility method to check if // substring from low to high is // palindrome or not. static boolean isPalindrome(String str, int low, int high) { while (low < high) { if (str.charAt(low) != str.charAt(high)) return false; low++; high--; } return true; } // This method returns -1 if it is // not possible to make string a palindrome. // It returns -2 if string is already // a palindrome. Otherwise it returns // index of character whose removal can // make the whole string palindrome. static int possiblePalinByRemovingOneChar(String str) { // Initialize low and right // by both the ends of the string int low = 0, high = str.length() - 1; // loop until low and // high cross each other while (low < high) { // If both characters are equal then // move both pointer towards end if (str.charAt(low) == str.charAt(high)) { low++; high--; } else { /* * If removing str[low] makes the * whole string palindrome. We basically * check if substring str[low+1..high] * is palindrome or not. */ if (isPalindrome(str, low + 1, high)) return low; /* * If removing str[high] makes the whole string * palindrome. We basically check if substring * str[low+1..high] is palindrome or not. */ if (isPalindrome(str, low, high - 1)) return high; return -1; } } // We reach here when complete string // will be palindrome if complete string // is palindrome then return mid character return -2; } // Driver Code public static void main(String[] args) { String str = \"abecbea\"; int idx = possiblePalinByRemovingOneChar(str); if (idx == -1) System.out.println(\"Not Possible\"); else if (idx == -2) System.out.println(\"Possible without \" + \"removing any character\"); else System.out.println(\"Possible by removing\" + \" character at index \" + idx); }} // This code is contributed by// sanjeev2552", "e": 32311, "s": 29673, "text": null }, { "code": "# Python program to check whether it is possible to make# string palindrome by removing one character # Utility method to check if substring from# low to high is palindrome or not.def isPalindrome(string: str, low: int, high: int) -> bool: while low < high: if string[low] != string[high]: return False low += 1 high -= 1 return True # This method returns -1 if it# is not possible to make string# a palindrome. It returns -2 if# string is already a palindrome.# Otherwise it returns index of# character whose removal can# make the whole string palindrome.def possiblepalinByRemovingOneChar(string: str) -> int: # Initialize low and right by # both the ends of the string low = 0 high = len(string) - 1 # loop until low and high cross each other while low < high: # If both characters are equal then # move both pointer towards end if string[low] == string[high]: low += 1 high -= 1 else: # If removing str[low] makes the whole string palindrome. # We basically check if substring str[low+1..high] is # palindrome or not. if isPalindrome(string, low + 1, high): return low # If removing str[high] makes the whole string palindrome # We basically check if substring str[low+1..high] is # palindrome or not if isPalindrome(string, low, high - 1): return high return -1 # We reach here when complete string will be palindrome # if complete string is palindrome then return mid character return -2 # Driver Codeif __name__ == \"__main__\": string = \"abecbea\" idx = possiblepalinByRemovingOneChar(string) if idx == -1: print(\"Not possible\") else if idx == -2: print(\"Possible without removing any character\") else: print(\"Possible by removing character at index\", idx) # This code is contributed by# sanjeev2552", "e": 34304, "s": 32311, "text": null }, { "code": "// C# program to check whether// it is possible to make string// palindrome by removing one characterusing System;class GFG{ // Utility method to check if // substring from low to high is // palindrome or not. static bool isPalindrome(string str, int low, int high) { while (low < high) { if (str[low] != str[high]) return false; low++; high--; } return true; } // This method returns -1 if it is // not possible to make string a palindrome. // It returns -2 if string is already // a palindrome. Otherwise it returns // index of character whose removal can // make the whole string palindrome. static int possiblePalinByRemovingOneChar(string str) { // Initialize low and right // by both the ends of the string int low = 0, high = str.Length - 1; // loop until low and // high cross each other while (low < high) { // If both characters are equal then // move both pointer towards end if (str[low] == str[high]) { low++; high--; } else { /* * If removing str[low] makes the * whole string palindrome. We basically * check if substring str[low+1..high] * is palindrome or not. */ if (isPalindrome(str, low + 1, high)) return low; /* * If removing str[high] makes the whole string * palindrome. We basically check if substring * str[low+1..high] is palindrome or not. */ if (isPalindrome(str, low, high - 1)) return high; return -1; } } // We reach here when complete string // will be palindrome if complete string // is palindrome then return mid character return -2; } // Driver Code public static void Main(String[] args) { string str = \"abecbea\"; int idx = possiblePalinByRemovingOneChar(str); if (idx == -1) Console.Write(\"Not Possible\"); else if (idx == -2) Console.Write(\"Possible without \" + \"removing any character\"); else Console.Write(\"Possible by removing\" + \" character at index \" + idx); }} // This code is contributed by shivanisinghss2110", "e": 36871, "s": 34304, "text": null }, { "code": "<script>// JavaScript program to check whether// it is possible to make string// palindrome by removing one character// Utility method to check if// substring from low to high is// palindrome or not.function isPalindrome(str, low, high) { while (low < high) { if (str.charAt(low) != str.charAt(high)) return false; low++; high--; } return true; } // This method returns -1 if it is // not possible to make string a palindrome. // It returns -2 if string is already // a palindrome. Otherwise it returns // index of character whose removal can // make the whole string palindrome. function possiblePalinByRemovingOneChar(str) { // Initialize low and right // by both the ends of the string var low = 0, high = str.length - 1; // loop until low and // high cross each other while (low < high) { // If both characters are equal then // move both pointer towards end if (str.charAt(low) == str.charAt(high)) { low++; high--; } else { /* * If removing str[low] makes the * whole string palindrome. We basically * check if substring str[low+1..high] * is palindrome or not. */ if (isPalindrome(str, low + 1, high)) return low; /* * If removing str[high] makes the whole string * palindrome. We basically check if substring * str[low+1..high] is palindrome or not. */ if (isPalindrome(str, low, high - 1)) return high; return -1; } } // We reach here when complete string // will be palindrome if complete string // is palindrome then return mid character return -2; } // Driver Code var str = \"abecbea\"; var idx = possiblePalinByRemovingOneChar(str); if (idx == -1) document.write(\"Not Possible\"); else if (idx == -2) document.write(\"Possible without \" + \"removing any character\"); else document.write(\"Possible by removing\" + \" character at index \" + idx); // this code is contributed by shivanisinghss2110</script>", "e": 39371, "s": 36871, "text": null }, { "code": null, "e": 39380, "s": 39371, "text": "Output: " }, { "code": null, "e": 39394, "s": 39380, "text": "Not Possible " }, { "code": null, "e": 39417, "s": 39394, "text": "Time complexity : O(N)" }, { "code": null, "e": 39440, "s": 39417, "text": "Space Complexity: O(1)" }, { "code": null, "e": 39864, "s": 39440, "text": "This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 39876, "s": 39864, "text": "sanjeev2552" }, { "code": null, "e": 39892, "s": 39876, "text": "divyanshukla777" }, { "code": null, "e": 39901, "s": 39892, "text": "sooda367" }, { "code": null, "e": 39913, "s": 39901, "text": "anikaseth98" }, { "code": null, "e": 39932, "s": 39913, "text": "shivanisinghss2110" }, { "code": null, "e": 39945, "s": 39932, "text": "simmytarika5" }, { "code": null, "e": 39953, "s": 39945, "text": "Strings" }, { "code": null, "e": 39961, "s": 39953, "text": "Strings" }, { "code": null, "e": 40059, "s": 39961, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40134, "s": 40059, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" }, { "code": null, "e": 40191, "s": 40134, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 40227, "s": 40191, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 40274, "s": 40227, "text": "Different methods to reverse a string in C/C++" }, { "code": null, "e": 40327, "s": 40274, "text": "Array of Strings in C++ (5 Different Ways to Create)" }, { "code": null, "e": 40363, "s": 40327, "text": "Convert string to char array in C++" }, { "code": null, "e": 40393, "s": 40363, "text": "Caesar Cipher in Cryptography" }, { "code": null, "e": 40445, "s": 40393, "text": "Check whether two strings are anagram of each other" }, { "code": null, "e": 40490, "s": 40445, "text": "Top 50 String Coding Problems for Interviews" } ]
C# | String.ToUpperInvariant Method - GeeksforGeeks
21 Jun, 2021 String.ToUpperInvariant Method is used to get a copy of this String object converted to uppercase using the casing rules of the invariant culture. Here “invariant culture” represents a culture that is culture-insensitive.Syntax: public string ToUpperInvariant (); Return Value: The return type of this method is System.String. This method will return a string which is the uppercase equivalent of the current string.Below given are some examples to understand the implementation in a better way: Example 1: CSharp // C# program to illustrate// ToUpperInvariant() methodusing System; public class GFG { // Main method static public void Main() { // variables string strA = "WelCome tO GeeKSfOrGeeKs"; string strB; // Convert strA into lowercase // using ToLowerInvariant() method strB = strA.ToUpperInvariant(); // Display string before ToUpperInvariant() method Console.WriteLine("String before ToUpperInvariant:"); Console.WriteLine(strA); Console.WriteLine(); // Display string after ToUpperInvariant() method Console.WriteLine("String after ToUpperInvariant:"); Console.WriteLine(strB); }} String before ToUpperInvariant: WelCome tO GeeKSfOrGeeKs String after ToUpperInvariant: WELCOME TO GEEKSFORGEEKS Example 2: CSharp // C# program to illustrate// ToUpperInvariant() Methodusing System; public class GFG { // Main method static public void Main() { // Calling function Convert("GEeks"); Convert("geeks"); Convert("GEEKS"); } static void Convert(String value) { // Display strings Console.WriteLine("string 1: {0}", value); // Convert sting into Uppercase // using ToUpperInvariant() method value = value.ToUpperInvariant(); // Display the Lowercase strings Console.WriteLine("string 2: {0}", value); }} string 1: GEeks string 2: GEEKS string 1: geeks string 2: GEEKS string 1: GEEKS string 2: GEEKS Note: The invariant culture represents a culture that is culture-insensitive. It is associated with the English language but not with a specific country or region. ToUpperInvariant() method does not modify the value of the current instance. Instead, it returns a new string in which all characters in the current instance are converted to uppercase. This method can’t be overloaded if you try to overload this method, it will give you compile time error. Reference: https://docs.microsoft.com/en-us/dotnet/api/system.string.toupperinvariant?view=netframework-4.7.2 akshaysingh98088 CSharp-method CSharp-string C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# | Delegates C# | Abstract Classes Extension Method in C# C# | String.IndexOf( ) Method | Set - 1 C# | Replace() Method Introduction to .NET Framework C# | Data Types C# | Arrays HashSet in C# with Examples Common Language Runtime (CLR) in C#
[ { "code": null, "e": 25507, "s": 25479, "text": "\n21 Jun, 2021" }, { "code": null, "e": 25737, "s": 25507, "text": "String.ToUpperInvariant Method is used to get a copy of this String object converted to uppercase using the casing rules of the invariant culture. Here “invariant culture” represents a culture that is culture-insensitive.Syntax: " }, { "code": null, "e": 25772, "s": 25737, "text": "public string ToUpperInvariant ();" }, { "code": null, "e": 26016, "s": 25772, "text": "Return Value: The return type of this method is System.String. This method will return a string which is the uppercase equivalent of the current string.Below given are some examples to understand the implementation in a better way: Example 1: " }, { "code": null, "e": 26023, "s": 26016, "text": "CSharp" }, { "code": "// C# program to illustrate// ToUpperInvariant() methodusing System; public class GFG { // Main method static public void Main() { // variables string strA = \"WelCome tO GeeKSfOrGeeKs\"; string strB; // Convert strA into lowercase // using ToLowerInvariant() method strB = strA.ToUpperInvariant(); // Display string before ToUpperInvariant() method Console.WriteLine(\"String before ToUpperInvariant:\"); Console.WriteLine(strA); Console.WriteLine(); // Display string after ToUpperInvariant() method Console.WriteLine(\"String after ToUpperInvariant:\"); Console.WriteLine(strB); }}", "e": 26710, "s": 26023, "text": null }, { "code": null, "e": 26824, "s": 26710, "text": "String before ToUpperInvariant:\nWelCome tO GeeKSfOrGeeKs\n\nString after ToUpperInvariant:\nWELCOME TO GEEKSFORGEEKS" }, { "code": null, "e": 26838, "s": 26826, "text": "Example 2: " }, { "code": null, "e": 26845, "s": 26838, "text": "CSharp" }, { "code": "// C# program to illustrate// ToUpperInvariant() Methodusing System; public class GFG { // Main method static public void Main() { // Calling function Convert(\"GEeks\"); Convert(\"geeks\"); Convert(\"GEEKS\"); } static void Convert(String value) { // Display strings Console.WriteLine(\"string 1: {0}\", value); // Convert sting into Uppercase // using ToUpperInvariant() method value = value.ToUpperInvariant(); // Display the Lowercase strings Console.WriteLine(\"string 2: {0}\", value); }}", "e": 27437, "s": 26845, "text": null }, { "code": null, "e": 27539, "s": 27437, "text": "string 1: GEeks\nstring 2: GEEKS\nstring 1: geeks\nstring 2: GEEKS\nstring 1: GEEKS\nstring 2: GEEKS" }, { "code": null, "e": 27549, "s": 27541, "text": "Note: " }, { "code": null, "e": 27707, "s": 27549, "text": "The invariant culture represents a culture that is culture-insensitive. It is associated with the English language but not with a specific country or region." }, { "code": null, "e": 27893, "s": 27707, "text": "ToUpperInvariant() method does not modify the value of the current instance. Instead, it returns a new string in which all characters in the current instance are converted to uppercase." }, { "code": null, "e": 27998, "s": 27893, "text": "This method can’t be overloaded if you try to overload this method, it will give you compile time error." }, { "code": null, "e": 28109, "s": 27998, "text": "Reference: https://docs.microsoft.com/en-us/dotnet/api/system.string.toupperinvariant?view=netframework-4.7.2 " }, { "code": null, "e": 28126, "s": 28109, "text": "akshaysingh98088" }, { "code": null, "e": 28140, "s": 28126, "text": "CSharp-method" }, { "code": null, "e": 28154, "s": 28140, "text": "CSharp-string" }, { "code": null, "e": 28157, "s": 28154, "text": "C#" }, { "code": null, "e": 28255, "s": 28157, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28270, "s": 28255, "text": "C# | Delegates" }, { "code": null, "e": 28292, "s": 28270, "text": "C# | Abstract Classes" }, { "code": null, "e": 28315, "s": 28292, "text": "Extension Method in C#" }, { "code": null, "e": 28355, "s": 28315, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 28377, "s": 28355, "text": "C# | Replace() Method" }, { "code": null, "e": 28408, "s": 28377, "text": "Introduction to .NET Framework" }, { "code": null, "e": 28424, "s": 28408, "text": "C# | Data Types" }, { "code": null, "e": 28436, "s": 28424, "text": "C# | Arrays" }, { "code": null, "e": 28464, "s": 28436, "text": "HashSet in C# with Examples" } ]
HTML | <video> src Attribute - GeeksforGeeks
28 Jun, 2019 The HTML <video> src Attribute is used to specify the URL of the video file. This attribute uses Ogg file on Firefox, Opera and Chrome browsers and MPEG4 file on Internet Explorer and Safari browsers. This attribute is new in HTML5. Syntax: <video src="URL"> Attribute Values: It contains a single value URL which specifies the link of source video. There are two types of URL link which are listed below: Absolute URL: It points to another webpage. Relative URL: It points to other files of the same web page. Example: <!DOCTYPE html><html> <head> <title>HTML video srcsrc Attribute</title></head> <body> <center> <h1 style="color:green;">GeeksforGeeks</h1> <h3>HTML video src Attribute</h3> <video width="400" height="200" controls src="https://media.geeksforgeeks.org/wp-content/uploads/20190616234019/Canvas.move_.mp4"> Browser not supported </video> </center></body> </html> Output: Note: Always specify the width and the height of the video else web page will be confused that how much space that video will be required due to that reason web page become slow down. Supported Browsers: The browser supported by HTML <video> src Attribute are listed below: Google Chrome 4.0 Internet Explorer 9.0 Firefox 3.5 Safari 4.0 Opera 10.5 Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. 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) HTML Cheat Sheet - A Basic Guide to HTML Design a web page using HTML and CSS Form validation using jQuery Angular File Upload Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26139, "s": 26111, "text": "\n28 Jun, 2019" }, { "code": null, "e": 26372, "s": 26139, "text": "The HTML <video> src Attribute is used to specify the URL of the video file. This attribute uses Ogg file on Firefox, Opera and Chrome browsers and MPEG4 file on Internet Explorer and Safari browsers. This attribute is new in HTML5." }, { "code": null, "e": 26380, "s": 26372, "text": "Syntax:" }, { "code": null, "e": 26398, "s": 26380, "text": "<video src=\"URL\">" }, { "code": null, "e": 26545, "s": 26398, "text": "Attribute Values: It contains a single value URL which specifies the link of source video. There are two types of URL link which are listed below:" }, { "code": null, "e": 26589, "s": 26545, "text": "Absolute URL: It points to another webpage." }, { "code": null, "e": 26650, "s": 26589, "text": "Relative URL: It points to other files of the same web page." }, { "code": null, "e": 26659, "s": 26650, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title>HTML video srcsrc Attribute</title></head> <body> <center> <h1 style=\"color:green;\">GeeksforGeeks</h1> <h3>HTML video src Attribute</h3> <video width=\"400\" height=\"200\" controls src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190616234019/Canvas.move_.mp4\"> Browser not supported </video> </center></body> </html>", "e": 27071, "s": 26659, "text": null }, { "code": null, "e": 27079, "s": 27071, "text": "Output:" }, { "code": null, "e": 27263, "s": 27079, "text": "Note: Always specify the width and the height of the video else web page will be confused that how much space that video will be required due to that reason web page become slow down." }, { "code": null, "e": 27353, "s": 27263, "text": "Supported Browsers: The browser supported by HTML <video> src Attribute are listed below:" }, { "code": null, "e": 27371, "s": 27353, "text": "Google Chrome 4.0" }, { "code": null, "e": 27393, "s": 27371, "text": "Internet Explorer 9.0" }, { "code": null, "e": 27405, "s": 27393, "text": "Firefox 3.5" }, { "code": null, "e": 27416, "s": 27405, "text": "Safari 4.0" }, { "code": null, "e": 27427, "s": 27416, "text": "Opera 10.5" }, { "code": null, "e": 27564, "s": 27427, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 27580, "s": 27564, "text": "HTML-Attributes" }, { "code": null, "e": 27585, "s": 27580, "text": "HTML" }, { "code": null, "e": 27602, "s": 27585, "text": "Web Technologies" }, { "code": null, "e": 27607, "s": 27602, "text": "HTML" }, { "code": null, "e": 27705, "s": 27607, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27729, "s": 27705, "text": "REST API (Introduction)" }, { "code": null, "e": 27770, "s": 27729, "text": "HTML Cheat Sheet - A Basic Guide to HTML" }, { "code": null, "e": 27807, "s": 27770, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 27836, "s": 27807, "text": "Form validation using jQuery" }, { "code": null, "e": 27856, "s": 27836, "text": "Angular File Upload" }, { "code": null, "e": 27896, "s": 27856, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27929, "s": 27896, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27974, "s": 27929, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28017, "s": 27974, "text": "How to fetch data from an API in ReactJS ?" } ]
Find substrings that contain all vowels - GeeksforGeeks
19 Mar, 2022 We have been given a string in lowercase alphabets. We need to print substrings that contain all the vowels at least one time and there are no consonants (non-vowel characters) present in the substrings. Examples: Input : str = aeoibddaeoiud Output : aeoiu Input : str = aeoibsddaeiouudb Output : aeiou, aeiouu Reference:- Samsung Interview Questions. We use a hashing based technique and start traversing the string from the start. For every character, we consider all substrings starting from it. If we encounter a consonant, we move to the next starting character. Else, we insert the current character in a hash. If all vowels are included, we print the current substring. C++ Java Python3 C# Javascript // CPP program to find all substring that// contain all vowels#include <bits/stdc++.h> using namespace std; // Returns true if x is vowel.bool isVowel(char x){ // Function to check whether a character is // vowel or not return (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u');} void FindSubstring(string str){ set<char> hash; // To store vowels // Outer loop picks starting character and // inner loop picks ending character. int n = str.length(); for (int i = 0; i < n; i++) { for (int j = i; j < n; j++) { // If current character is not vowel, // then no more result substrings // possible starting from str[i]. if (isVowel(str[j]) == false) break; // If vowel, then we insert it in hash hash.insert(str[j]); // If all vowels are present in current // substring if (hash.size() == 5) cout << str.substr(i, j-i+1) << " "; } hash.clear(); }} // Driver codeint main(){ string str = "aeoibsddaeiouudb"; FindSubstring(str); return 0;} // Java program to find all substring that // contain all vowelsimport java.util.HashSet; public class GFG { // Returns true if x is vowel. static boolean isVowel(char x) { // Function to check whether a character is // vowel or not return (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u'); } static void findSubstring(String str) { HashSet<Character> hash = new HashSet<Character>(); // To store vowels // Outer loop picks starting character and // inner loop picks ending character. int n = str.length(); for (int i = 0; i < n; i++) { for (int j = i; j < n; j++) { // If current character is not vowel, // then no more result substrings // possible starting from str[i]. if (isVowel(str.charAt(j)) == false) break; // If vowel, then we insert it in hash hash.add(str.charAt(j)); // If all vowels are present in current // substring if (hash.size() == 5) System.out.print(str.substring(i, j + 1) + " "); } hash.clear(); } } // Driver code public static void main(String[] args) { String str = "aeoibsddaeiouudb"; findSubstring(str); }} # Python3 program to find all substring that# contain all vowels # Returns true if x is vowel.def isVowel(x): # Function to check whether a character is # vowel or not if (x == 'a' or x == 'e' or x == 'i' or x == 'o' or x == 'u'): return True return False def FindSubstring(str1): # To store vowels # Outer loop picks starting character and # inner loop picks ending character. n = len(str1) for i in range(n): hash = dict() for j in range(i, n): # If current character is not vowel, # then no more result substrings # possible starting from str1[i]. if (isVowel(str1[j]) == False): break # If vowel, then we insert it in hash hash[str1[j]] = 1 # If all vowels are present in current # substring if (len(hash) == 5): print(str1[i:j + 1], end = " ") # Driver codestr1 = "aeoibsddaeiouudb"FindSubstring(str1) # This code is contributed by Mohit Kumar // C# program to find all substring that// contain all vowelsusing System;using System.Collections.Generic; public class GFG{ // Returns true if x is vowel.public static bool isVowel(char x){ // Function to check whether a // character is vowel or not return (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u');} public static void findSubstring(string str){ HashSet<char> hash = new HashSet<char>(); // To store vowels // Outer loop picks starting character and // inner loop picks ending character. int n = str.Length; for (int i = 0; i < n; i++) { for (int j = i; j < n; j++) { // If current character is not vowel, // then no more result substrings // possible starting from str[i]. if (isVowel(str[j]) == false) { break; } // If vowel, then we insert it in hash hash.Add(str[j]); // If all vowels are present in current // substring if (hash.Count == 5) { Console.Write(str.Substring(i, (j + 1) - i) + " "); } } hash.Clear(); }} // Driver codepublic static void Main(string[] args){ string str = "aeoibsddaeiouudb"; findSubstring(str);}} // This code is contributed by Shrikant13 <script>// Javascript program to find all substring that // contain all vowels // Returns true if x is vowel. function isVowel(x) { // Function to check whether a character is // vowel or not return (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u'); } function findSubstring(str) { let hash = new Set(); // To store vowels // Outer loop picks starting character and // inner loop picks ending character. let n = str.length; for (let i = 0; i < n; i++) { for (let j = i; j < n; j++) { // If current character is not vowel, // then no more result substrings // possible starting from str[i]. if (isVowel(str[j]) == false) break; // If vowel, then we insert it in hash hash.add(str[j]); // If all vowels are present in current // substring if (hash.size == 5) document.write(str.substring(i, j + 1) + " "); } hash.clear(); } } // Driver code let str = "aeoibsddaeiouudb"; findSubstring(str); // This code is contributed by patel2127</script> Output: aeiou aeiouu Time Complexity : O(n2) Optimized Solution : For every character, If current character is vowel then insert into hash. Else set flag Start to next substring start from i+1th index. If all vowels are included, we print the current substring. C++ Java Python3 C# Javascript // C++ program to find all substring that// contain all vowels#include<bits/stdc++.h> using namespace std; // Returns true if x is vowel.bool isVowel(char x){ // Function to check whether a character is // vowel or not return (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u');} // Function to FindSubstrings of stringvoid FindSubstring(string str){ set<char> hash; // To store vowels int start = 0; for (int i=0; i<str.length(); i++) { // If current character is vowel then // insert into hash , if (isVowel(str[i]) == true) { hash.insert(str[i]); // If all vowels are present in current // substring if (hash.size()==5) cout << str.substr(start, i-start+1) << " "; } else { start = i+1; hash.clear(); } }} // Driver Codeint main(){ string str = "aeoibsddaeiouudb"; FindSubstring(str); return 0;} // Java program to find all substring that // contain all vowelsimport java.util.HashSet; public class GFG { // Returns true if x is vowel. static boolean isVowel(char x) { // Function to check whether a character is // vowel or not return (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u'); } // Function to FindSubstrings of string static void findSubstring(String str) { HashSet<Character> hash = new HashSet<Character>(); // To store vowels int start = 0; for (int i = 0; i < str.length(); i++) { // If current character is vowel then // insert into hash , if (isVowel(str.charAt(i)) == true) { hash.add(str.charAt(i)); // If all vowels are present in current // substring if (hash.size() == 5) System.out.print(str.substring(start, i + 1) + " "); } else { start = i + 1; hash.clear(); } } } // Driver Code public static void main(String[] args) { String str = "aeoibsddaeiouudb"; findSubstring(str); } } # Python3 program to find all substring# that contain all vowels # Returns true if x is vowel.def isVowel(x): # Function to check whether # a character is vowel or not return (x == 'a' or x == 'e' or x == 'i' or x == 'o' or x == 'u'); # Function to FindSubstrings of stringdef FindSubstring(str): hash = set(); # To store vowels start = 0; for i in range(len(str)): # If current character is vowel # then insert into hash if (isVowel(str[i]) == True): hash.add(str[i]); # If all vowels are present # in current substring if (len(hash) == 5): print(str[start : i + 1], end = " "); else: start = i + 1; hash.clear(); # Driver Codestr = "aeoibsddaeiouudb";FindSubstring(str); # This code is contributed by 29AjayKumar using System;using System.Collections.Generic; // c# program to find all substring that // contain all vowels public class GFG{ // Returns true if x is vowel. public static bool isVowel(char x) { // Function to check whether a character is // vowel or not return (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u'); } // Function to FindSubstrings of string public static void findSubstring(string str) { HashSet<char> hash = new HashSet<char>(); // To store vowels int start = 0; for (int i = 0; i < str.Length; i++) { // If current character is vowel then // insert into hash , if (isVowel(str[i]) == true) { hash.Add(str[i]); // If all vowels are present in current // substring if (hash.Count == 5) { Console.Write(str.Substring(start, (i + 1) - start) + " "); } } else { start = i + 1; hash.Clear(); } } } // Driver Code public static void Main(string[] args) { string str = "aeoibsddaeiouudb"; findSubstring(str); } } // This code is contributed by Shrikant13 <script> // Javascript program to find all substring that// contain all vowels // Returns true if x is vowel.function isVowel(x){ // Function to check whether a character is // vowel or not return (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u');} // Function to FindSubstrings of stringfunction findSubstring(str){ let hash = new Set(); // To store vowels let start = 0; for(let i = 0; i < str.length; i++) { // If current character is vowel then // insert into hash , if (isVowel(str[i]) == true) { hash.add(str[i]); // If all vowels are present in current // substring if (hash.size == 5) document.write( str.substring(start, i + 1) + " "); } else { start = i + 1; hash.clear(); } }} // Driver Codelet str = "aeoibsddaeiouudb";findSubstring(str); // This code is contributed by unknown2108 </script> Output: aeiou aeiouu Time Complexity: O(n) Auxiliary Space: O(n)Thanks to Kriti Shukla for suggesting this optimized solution.This article is contributed by Ashish Madaan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. bilal-hungund shrikanth13 mohit kumar 29 29AjayKumar patel2127 unknown2108 simmytarika5 surinderdawra388 rishavnitro Samsung vowel-consonant Hash Strings Samsung Hash Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Hashing | Set 2 (Separate Chaining) Counting frequencies of array elements Most frequent element in an array Sorting a Map by value in C++ STL Longest Consecutive Subsequence Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Check for Balanced Brackets in an expression (well-formedness) using Stack
[ { "code": null, "e": 26439, "s": 26411, "text": "\n19 Mar, 2022" }, { "code": null, "e": 26643, "s": 26439, "text": "We have been given a string in lowercase alphabets. We need to print substrings that contain all the vowels at least one time and there are no consonants (non-vowel characters) present in the substrings." }, { "code": null, "e": 26655, "s": 26643, "text": "Examples: " }, { "code": null, "e": 26753, "s": 26655, "text": "Input : str = aeoibddaeoiud\nOutput : aeoiu\n\nInput : str = aeoibsddaeiouudb\nOutput : aeiou, aeiouu" }, { "code": null, "e": 26795, "s": 26753, "text": "Reference:- Samsung Interview Questions. " }, { "code": null, "e": 27121, "s": 26795, "text": "We use a hashing based technique and start traversing the string from the start. For every character, we consider all substrings starting from it. If we encounter a consonant, we move to the next starting character. Else, we insert the current character in a hash. If all vowels are included, we print the current substring. " }, { "code": null, "e": 27125, "s": 27121, "text": "C++" }, { "code": null, "e": 27130, "s": 27125, "text": "Java" }, { "code": null, "e": 27138, "s": 27130, "text": "Python3" }, { "code": null, "e": 27141, "s": 27138, "text": "C#" }, { "code": null, "e": 27152, "s": 27141, "text": "Javascript" }, { "code": "// CPP program to find all substring that// contain all vowels#include <bits/stdc++.h> using namespace std; // Returns true if x is vowel.bool isVowel(char x){ // Function to check whether a character is // vowel or not return (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u');} void FindSubstring(string str){ set<char> hash; // To store vowels // Outer loop picks starting character and // inner loop picks ending character. int n = str.length(); for (int i = 0; i < n; i++) { for (int j = i; j < n; j++) { // If current character is not vowel, // then no more result substrings // possible starting from str[i]. if (isVowel(str[j]) == false) break; // If vowel, then we insert it in hash hash.insert(str[j]); // If all vowels are present in current // substring if (hash.size() == 5) cout << str.substr(i, j-i+1) << \" \"; } hash.clear(); }} // Driver codeint main(){ string str = \"aeoibsddaeiouudb\"; FindSubstring(str); return 0;}", "e": 28318, "s": 27152, "text": null }, { "code": "// Java program to find all substring that // contain all vowelsimport java.util.HashSet; public class GFG { // Returns true if x is vowel. static boolean isVowel(char x) { // Function to check whether a character is // vowel or not return (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u'); } static void findSubstring(String str) { HashSet<Character> hash = new HashSet<Character>(); // To store vowels // Outer loop picks starting character and // inner loop picks ending character. int n = str.length(); for (int i = 0; i < n; i++) { for (int j = i; j < n; j++) { // If current character is not vowel, // then no more result substrings // possible starting from str[i]. if (isVowel(str.charAt(j)) == false) break; // If vowel, then we insert it in hash hash.add(str.charAt(j)); // If all vowels are present in current // substring if (hash.size() == 5) System.out.print(str.substring(i, j + 1) + \" \"); } hash.clear(); } } // Driver code public static void main(String[] args) { String str = \"aeoibsddaeiouudb\"; findSubstring(str); }}", "e": 29704, "s": 28318, "text": null }, { "code": "# Python3 program to find all substring that# contain all vowels # Returns true if x is vowel.def isVowel(x): # Function to check whether a character is # vowel or not if (x == 'a' or x == 'e' or x == 'i' or x == 'o' or x == 'u'): return True return False def FindSubstring(str1): # To store vowels # Outer loop picks starting character and # inner loop picks ending character. n = len(str1) for i in range(n): hash = dict() for j in range(i, n): # If current character is not vowel, # then no more result substrings # possible starting from str1[i]. if (isVowel(str1[j]) == False): break # If vowel, then we insert it in hash hash[str1[j]] = 1 # If all vowels are present in current # substring if (len(hash) == 5): print(str1[i:j + 1], end = \" \") # Driver codestr1 = \"aeoibsddaeiouudb\"FindSubstring(str1) # This code is contributed by Mohit Kumar", "e": 30747, "s": 29704, "text": null }, { "code": "// C# program to find all substring that// contain all vowelsusing System;using System.Collections.Generic; public class GFG{ // Returns true if x is vowel.public static bool isVowel(char x){ // Function to check whether a // character is vowel or not return (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u');} public static void findSubstring(string str){ HashSet<char> hash = new HashSet<char>(); // To store vowels // Outer loop picks starting character and // inner loop picks ending character. int n = str.Length; for (int i = 0; i < n; i++) { for (int j = i; j < n; j++) { // If current character is not vowel, // then no more result substrings // possible starting from str[i]. if (isVowel(str[j]) == false) { break; } // If vowel, then we insert it in hash hash.Add(str[j]); // If all vowels are present in current // substring if (hash.Count == 5) { Console.Write(str.Substring(i, (j + 1) - i) + \" \"); } } hash.Clear(); }} // Driver codepublic static void Main(string[] args){ string str = \"aeoibsddaeiouudb\"; findSubstring(str);}} // This code is contributed by Shrikant13", "e": 32135, "s": 30747, "text": null }, { "code": "<script>// Javascript program to find all substring that // contain all vowels // Returns true if x is vowel. function isVowel(x) { // Function to check whether a character is // vowel or not return (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u'); } function findSubstring(str) { let hash = new Set(); // To store vowels // Outer loop picks starting character and // inner loop picks ending character. let n = str.length; for (let i = 0; i < n; i++) { for (let j = i; j < n; j++) { // If current character is not vowel, // then no more result substrings // possible starting from str[i]. if (isVowel(str[j]) == false) break; // If vowel, then we insert it in hash hash.add(str[j]); // If all vowels are present in current // substring if (hash.size == 5) document.write(str.substring(i, j + 1) + \" \"); } hash.clear(); } } // Driver code let str = \"aeoibsddaeiouudb\"; findSubstring(str); // This code is contributed by patel2127</script>", "e": 33443, "s": 32135, "text": null }, { "code": null, "e": 33453, "s": 33443, "text": "Output: " }, { "code": null, "e": 33466, "s": 33453, "text": "aeiou aeiouu" }, { "code": null, "e": 33490, "s": 33466, "text": "Time Complexity : O(n2)" }, { "code": null, "e": 33708, "s": 33490, "text": "Optimized Solution : For every character, If current character is vowel then insert into hash. Else set flag Start to next substring start from i+1th index. If all vowels are included, we print the current substring. " }, { "code": null, "e": 33712, "s": 33708, "text": "C++" }, { "code": null, "e": 33717, "s": 33712, "text": "Java" }, { "code": null, "e": 33725, "s": 33717, "text": "Python3" }, { "code": null, "e": 33728, "s": 33725, "text": "C#" }, { "code": null, "e": 33739, "s": 33728, "text": "Javascript" }, { "code": "// C++ program to find all substring that// contain all vowels#include<bits/stdc++.h> using namespace std; // Returns true if x is vowel.bool isVowel(char x){ // Function to check whether a character is // vowel or not return (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u');} // Function to FindSubstrings of stringvoid FindSubstring(string str){ set<char> hash; // To store vowels int start = 0; for (int i=0; i<str.length(); i++) { // If current character is vowel then // insert into hash , if (isVowel(str[i]) == true) { hash.insert(str[i]); // If all vowels are present in current // substring if (hash.size()==5) cout << str.substr(start, i-start+1) << \" \"; } else { start = i+1; hash.clear(); } }} // Driver Codeint main(){ string str = \"aeoibsddaeiouudb\"; FindSubstring(str); return 0;}", "e": 34761, "s": 33739, "text": null }, { "code": "// Java program to find all substring that // contain all vowelsimport java.util.HashSet; public class GFG { // Returns true if x is vowel. static boolean isVowel(char x) { // Function to check whether a character is // vowel or not return (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u'); } // Function to FindSubstrings of string static void findSubstring(String str) { HashSet<Character> hash = new HashSet<Character>(); // To store vowels int start = 0; for (int i = 0; i < str.length(); i++) { // If current character is vowel then // insert into hash , if (isVowel(str.charAt(i)) == true) { hash.add(str.charAt(i)); // If all vowels are present in current // substring if (hash.size() == 5) System.out.print(str.substring(start, i + 1) + \" \"); } else { start = i + 1; hash.clear(); } } } // Driver Code public static void main(String[] args) { String str = \"aeoibsddaeiouudb\"; findSubstring(str); } }", "e": 35959, "s": 34761, "text": null }, { "code": "# Python3 program to find all substring# that contain all vowels # Returns true if x is vowel.def isVowel(x): # Function to check whether # a character is vowel or not return (x == 'a' or x == 'e' or x == 'i' or x == 'o' or x == 'u'); # Function to FindSubstrings of stringdef FindSubstring(str): hash = set(); # To store vowels start = 0; for i in range(len(str)): # If current character is vowel # then insert into hash if (isVowel(str[i]) == True): hash.add(str[i]); # If all vowels are present # in current substring if (len(hash) == 5): print(str[start : i + 1], end = \" \"); else: start = i + 1; hash.clear(); # Driver Codestr = \"aeoibsddaeiouudb\";FindSubstring(str); # This code is contributed by 29AjayKumar", "e": 36869, "s": 35959, "text": null }, { "code": "using System;using System.Collections.Generic; // c# program to find all substring that // contain all vowels public class GFG{ // Returns true if x is vowel. public static bool isVowel(char x) { // Function to check whether a character is // vowel or not return (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u'); } // Function to FindSubstrings of string public static void findSubstring(string str) { HashSet<char> hash = new HashSet<char>(); // To store vowels int start = 0; for (int i = 0; i < str.Length; i++) { // If current character is vowel then // insert into hash , if (isVowel(str[i]) == true) { hash.Add(str[i]); // If all vowels are present in current // substring if (hash.Count == 5) { Console.Write(str.Substring(start, (i + 1) - start) + \" \"); } } else { start = i + 1; hash.Clear(); } } } // Driver Code public static void Main(string[] args) { string str = \"aeoibsddaeiouudb\"; findSubstring(str); } } // This code is contributed by Shrikant13", "e": 38189, "s": 36869, "text": null }, { "code": "<script> // Javascript program to find all substring that// contain all vowels // Returns true if x is vowel.function isVowel(x){ // Function to check whether a character is // vowel or not return (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u');} // Function to FindSubstrings of stringfunction findSubstring(str){ let hash = new Set(); // To store vowels let start = 0; for(let i = 0; i < str.length; i++) { // If current character is vowel then // insert into hash , if (isVowel(str[i]) == true) { hash.add(str[i]); // If all vowels are present in current // substring if (hash.size == 5) document.write( str.substring(start, i + 1) + \" \"); } else { start = i + 1; hash.clear(); } }} // Driver Codelet str = \"aeoibsddaeiouudb\";findSubstring(str); // This code is contributed by unknown2108 </script>", "e": 39220, "s": 38189, "text": null }, { "code": null, "e": 39230, "s": 39220, "text": "Output: " }, { "code": null, "e": 39243, "s": 39230, "text": "aeiou aeiouu" }, { "code": null, "e": 39265, "s": 39243, "text": "Time Complexity: O(n)" }, { "code": null, "e": 39770, "s": 39265, "text": "Auxiliary Space: O(n)Thanks to Kriti Shukla for suggesting this optimized solution.This article is contributed by Ashish Madaan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 39784, "s": 39770, "text": "bilal-hungund" }, { "code": null, "e": 39796, "s": 39784, "text": "shrikanth13" }, { "code": null, "e": 39811, "s": 39796, "text": "mohit kumar 29" }, { "code": null, "e": 39823, "s": 39811, "text": "29AjayKumar" }, { "code": null, "e": 39833, "s": 39823, "text": "patel2127" }, { "code": null, "e": 39845, "s": 39833, "text": "unknown2108" }, { "code": null, "e": 39858, "s": 39845, "text": "simmytarika5" }, { "code": null, "e": 39875, "s": 39858, "text": "surinderdawra388" }, { "code": null, "e": 39887, "s": 39875, "text": "rishavnitro" }, { "code": null, "e": 39895, "s": 39887, "text": "Samsung" }, { "code": null, "e": 39911, "s": 39895, "text": "vowel-consonant" }, { "code": null, "e": 39916, "s": 39911, "text": "Hash" }, { "code": null, "e": 39924, "s": 39916, "text": "Strings" }, { "code": null, "e": 39932, "s": 39924, "text": "Samsung" }, { "code": null, "e": 39937, "s": 39932, "text": "Hash" }, { "code": null, "e": 39945, "s": 39937, "text": "Strings" }, { "code": null, "e": 40043, "s": 39945, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40079, "s": 40043, "text": "Hashing | Set 2 (Separate Chaining)" }, { "code": null, "e": 40118, "s": 40079, "text": "Counting frequencies of array elements" }, { "code": null, "e": 40152, "s": 40118, "text": "Most frequent element in an array" }, { "code": null, "e": 40186, "s": 40152, "text": "Sorting a Map by value in C++ STL" }, { "code": null, "e": 40218, "s": 40186, "text": "Longest Consecutive Subsequence" }, { "code": null, "e": 40264, "s": 40218, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 40289, "s": 40264, "text": "Reverse a string in Java" }, { "code": null, "e": 40349, "s": 40289, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 40364, "s": 40349, "text": "C++ Data Types" } ]
Python - Copy Files From Subfolders to the Main folder - GeeksforGeeks
15 Oct, 2021 In this article, we will discuss how to copy a file from the subfolder to the main folder. The directory tree that will be used for explanation in this article is as shown below: D:\projects\base | |__subfolder: | \__file.txt | |__main.py | Here we have a folder named “base” in which we have a folder named “subfolder” which contains a file name file.txt. We are going to copy the file.txt in the base folder from the subfolder. Python comes with various modules that offer variety of ways to perform input/output operation and we will discuss them here. The various methods that we will discuss includes:- Using shutil.copyfile()Using shutil.copy()Using shutil.copy2()Using shutil.copyfileobj() Using shutil.copyfile() Using shutil.copy() Using shutil.copy2() Using shutil.copyfileobj() Using copyfile() method of shutil library we can easily copy a file from one location to other location. It takes 2 arguments the source path where the file that needs to be copied exist and the destination path where file is needed to be copied. Below is the code for implementation of this method: Python # importing the shutil moduleimport shutil # storing the current path of file.txt# in the source variablesource = 'D:/projects/base/subfolder/file.txt' # storing the destination path in the# destination variabledestination = 'D:/projects/base/file.txt' # calling the shutil.copyfile() methodshutil.copyfile(source,destination) After running this code we will notice that the file named file.txt has been copied to base folder. Some points to be noted about shutil.copyfile() method:- The destination location must be writable otherwise, an IOError exception will be raised. If destination already exists, it will be replaced. Special files such as character or block devices and pipes cannot be copied with this function. It does not copy the metadata. Using the shutil.copy() method also we can copy the file the only change in syntax we can say is that the destination string that we pass can also be directory instead of full file path. For example see the code below: Python # importing the shutil moduleimport shutil # storing the current file path of file.txt# in the source variablesource = 'D:/projects/base/subfolder/file.txt' # storing the destination directory in the# destination variabledestination = 'D:/projects/base' # calling the shutil.copy() methodshutil.copy(source,destination) After running this code we will notice that the file named file.txt has been copied to base folder. The main difference in copyfile() and copy() method are: The copy() method also copies the information about permission but the copyfile() method does not. The destination string can be a directory or full file path in copy() method but in copyfile() method it should be full file path. The shutil.copy2() method is also like shutil.copy() method but the extra thing it does is it copies the metadata like time stamps.The code will be similar to above: Python # importing the shutil moduleimport shutil # storing the current path of file.txt# in the source variablesource = 'D:/projects/base/subfolder/file.txt' # storing the destination path in the# destination variabledestination = 'D:/projects/base' # calling the shutil.copy2 methodshutil.copy2(source,destination) After running this code we will notice that the file named file.txt has been copied to base folder. The shutil.copyfileobj() is also similar to above discussed method but the things different are firstly it takes file object instead of file paths and secondly is it takes an extra option argument which is the number of bytes kept in memory during the copy process. The default value is 16KB. The code to copy using above method will be: Python # importing shutil moduleimport shutil # Source filesource = 'D:/projects/base/subfolder/file.txt' # Open the source file# in read mode and# get the file objectfsrc = open(source, 'r') # destination filedest = 'D:/projects/base/file.txt' # Open the destination file# in write mode and# get the file objectfdst = open(dest, 'w') # Now, copy the contents of# file object f1 to f2# using shutil.copyfileobj() methodshutil.copyfileobj(fsrc, fdst) # We can also specify# the buffer size by passing# optional length parameter# like shutil.copyfileobj(fsrc, fdst, 1024) # Close file objectsfdst.close()fsrc.close() After running this code we will notice that the file named file.txt has been copied to base folder. We can also remember the difference between the above methods using the given table: sagartomar9927 Picked Python directory-program Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Python | Get unique values from a list Defaultdict in Python Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n15 Oct, 2021" }, { "code": null, "e": 25716, "s": 25537, "text": "In this article, we will discuss how to copy a file from the subfolder to the main folder. The directory tree that will be used for explanation in this article is as shown below:" }, { "code": null, "e": 25788, "s": 25716, "text": "D:\\projects\\base\n|\n|__subfolder:\n| \\__file.txt\n| \n|__main.py\n| " }, { "code": null, "e": 25977, "s": 25788, "text": "Here we have a folder named “base” in which we have a folder named “subfolder” which contains a file name file.txt. We are going to copy the file.txt in the base folder from the subfolder." }, { "code": null, "e": 26103, "s": 25977, "text": "Python comes with various modules that offer variety of ways to perform input/output operation and we will discuss them here." }, { "code": null, "e": 26155, "s": 26103, "text": "The various methods that we will discuss includes:-" }, { "code": null, "e": 26244, "s": 26155, "text": "Using shutil.copyfile()Using shutil.copy()Using shutil.copy2()Using shutil.copyfileobj()" }, { "code": null, "e": 26268, "s": 26244, "text": "Using shutil.copyfile()" }, { "code": null, "e": 26288, "s": 26268, "text": "Using shutil.copy()" }, { "code": null, "e": 26309, "s": 26288, "text": "Using shutil.copy2()" }, { "code": null, "e": 26336, "s": 26309, "text": "Using shutil.copyfileobj()" }, { "code": null, "e": 26636, "s": 26336, "text": "Using copyfile() method of shutil library we can easily copy a file from one location to other location. It takes 2 arguments the source path where the file that needs to be copied exist and the destination path where file is needed to be copied. Below is the code for implementation of this method:" }, { "code": null, "e": 26643, "s": 26636, "text": "Python" }, { "code": "# importing the shutil moduleimport shutil # storing the current path of file.txt# in the source variablesource = 'D:/projects/base/subfolder/file.txt' # storing the destination path in the# destination variabledestination = 'D:/projects/base/file.txt' # calling the shutil.copyfile() methodshutil.copyfile(source,destination)", "e": 26970, "s": 26643, "text": null }, { "code": null, "e": 27074, "s": 26974, "text": "After running this code we will notice that the file named file.txt has been copied to base folder." }, { "code": null, "e": 27135, "s": 27078, "text": "Some points to be noted about shutil.copyfile() method:-" }, { "code": null, "e": 27227, "s": 27137, "text": "The destination location must be writable otherwise, an IOError exception will be raised." }, { "code": null, "e": 27279, "s": 27227, "text": "If destination already exists, it will be replaced." }, { "code": null, "e": 27375, "s": 27279, "text": "Special files such as character or block devices and pipes cannot be copied with this function." }, { "code": null, "e": 27406, "s": 27375, "text": "It does not copy the metadata." }, { "code": null, "e": 27627, "s": 27408, "text": "Using the shutil.copy() method also we can copy the file the only change in syntax we can say is that the destination string that we pass can also be directory instead of full file path. For example see the code below:" }, { "code": null, "e": 27636, "s": 27629, "text": "Python" }, { "code": "# importing the shutil moduleimport shutil # storing the current file path of file.txt# in the source variablesource = 'D:/projects/base/subfolder/file.txt' # storing the destination directory in the# destination variabledestination = 'D:/projects/base' # calling the shutil.copy() methodshutil.copy(source,destination)", "e": 27956, "s": 27636, "text": null }, { "code": null, "e": 28060, "s": 27960, "text": "After running this code we will notice that the file named file.txt has been copied to base folder." }, { "code": null, "e": 28121, "s": 28064, "text": "The main difference in copyfile() and copy() method are:" }, { "code": null, "e": 28222, "s": 28123, "text": "The copy() method also copies the information about permission but the copyfile() method does not." }, { "code": null, "e": 28353, "s": 28222, "text": "The destination string can be a directory or full file path in copy() method but in copyfile() method it should be full file path." }, { "code": null, "e": 28521, "s": 28355, "text": "The shutil.copy2() method is also like shutil.copy() method but the extra thing it does is it copies the metadata like time stamps.The code will be similar to above:" }, { "code": null, "e": 28530, "s": 28523, "text": "Python" }, { "code": "# importing the shutil moduleimport shutil # storing the current path of file.txt# in the source variablesource = 'D:/projects/base/subfolder/file.txt' # storing the destination path in the# destination variabledestination = 'D:/projects/base' # calling the shutil.copy2 methodshutil.copy2(source,destination)", "e": 28840, "s": 28530, "text": null }, { "code": null, "e": 28944, "s": 28844, "text": "After running this code we will notice that the file named file.txt has been copied to base folder." }, { "code": null, "e": 29241, "s": 28948, "text": "The shutil.copyfileobj() is also similar to above discussed method but the things different are firstly it takes file object instead of file paths and secondly is it takes an extra option argument which is the number of bytes kept in memory during the copy process. The default value is 16KB." }, { "code": null, "e": 29288, "s": 29243, "text": "The code to copy using above method will be:" }, { "code": null, "e": 29297, "s": 29290, "text": "Python" }, { "code": "# importing shutil moduleimport shutil # Source filesource = 'D:/projects/base/subfolder/file.txt' # Open the source file# in read mode and# get the file objectfsrc = open(source, 'r') # destination filedest = 'D:/projects/base/file.txt' # Open the destination file# in write mode and# get the file objectfdst = open(dest, 'w') # Now, copy the contents of# file object f1 to f2# using shutil.copyfileobj() methodshutil.copyfileobj(fsrc, fdst) # We can also specify# the buffer size by passing# optional length parameter# like shutil.copyfileobj(fsrc, fdst, 1024) # Close file objectsfdst.close()fsrc.close()", "e": 29926, "s": 29297, "text": null }, { "code": null, "e": 30030, "s": 29930, "text": "After running this code we will notice that the file named file.txt has been copied to base folder." }, { "code": null, "e": 30119, "s": 30034, "text": "We can also remember the difference between the above methods using the given table:" }, { "code": null, "e": 30138, "s": 30123, "text": "sagartomar9927" }, { "code": null, "e": 30145, "s": 30138, "text": "Picked" }, { "code": null, "e": 30170, "s": 30145, "text": "Python directory-program" }, { "code": null, "e": 30177, "s": 30170, "text": "Python" }, { "code": null, "e": 30275, "s": 30177, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30307, "s": 30275, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30349, "s": 30307, "text": "Check if element exists in list in Python" }, { "code": null, "e": 30391, "s": 30349, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 30418, "s": 30391, "text": "Python Classes and Objects" }, { "code": null, "e": 30474, "s": 30418, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 30513, "s": 30474, "text": "Python | Get unique values from a list" }, { "code": null, "e": 30535, "s": 30513, "text": "Defaultdict in Python" }, { "code": null, "e": 30566, "s": 30535, "text": "Python | os.path.join() method" }, { "code": null, "e": 30595, "s": 30566, "text": "Create a directory in Python" } ]
PHP | Strings - GeeksforGeeks
05 May, 2021 Strings can be seen as a stream of characters. For example, ‘G’ is a character and ‘GeeksforGeeks’ is a string. We have learned about the basics of string data type in PHP in PHP | Data types and Variables. In this article, we will discuss strings in detail. Everything inside quotes, single (‘ ‘) and double (” “) in PHP is treated as a string. Creating Strings:There are four ways of creating strings in PHP: 1. Single-quote strings: This type of string does not process special characters inside quotes. PHP <?php // single-quote strings $site = 'Welcome to GeeksforGeeks'; echo $site; ?> Output: Welcome to GeeksforGeeks The above program compiles correctly. We have created a string ‘Welcome to GeeksforGeeks’ and stored it in variable and printing it using echo statement. Let us now look at the below program: PHP <?php // single-quote strings $site = 'GeeksforGeeks'; echo 'Welcome to $site'; ?> Output: Welcome to $site In the above program the echo statement prints the variable name rather than printing the contents of the variables. This is because single-quotes strings in PHP do not process special characters. Hence, the string is unable to identify the ‘$’ sign as the start of a variable name. 2.Double-quote strings : Unlike single-quote strings, double-quote strings in PHP are capable of processing special characters. PHP <?php // double-quote strings echo "Welcome to GeeksforGeeks \n"; $site = "GeeksforGeeks"; echo "Welcome to $site"; ?> Output: Welcome to GeeksforGeeks Welcome to GeeksforGeeks In the above program, we can see that the double-quote strings are processing the special characters according to their properties. The ‘\n’ character is not printed and is considered as a new line. Also instead of the variable name $site, “GeeksforGeeks” is printed. PHP treats everything inside double quotes(” “) as Strings. In this article, we will learn about the working of the various string functions and how to implement them along with some special properties of strings. Unlike other data types like integers, doubles, etc. Strings do not have any fixed limits or ranges. It can extend to any length as long as it is within the quotes. It has been discussed earlier that string with single and double quotes are treated differently. Strings within a single quote ignore the special characters, but double-quoted strings recognize the special characters and treat them differently. Example: PHP <?php $name = "Krishna";echo "The name of the geek is $name \n";echo 'The name of the geek is $name'; ?> Output: The name of the geek is Krishna The name of the geek is $name Some important and frequently used special characters that are used with double-quoted strings are explained below: The character begins with a backslash(“\”) is treated as escape sequences and is replaced with special characters. Here are few important escape sequences. “\n” is replaced by a new line“\t” is replaced by a tab space“\$” is replaced by a dollar sign“\r” is replaced by a carriage return“\\” is replaced by a backslash“\”” is replaced by a double quote“\'” is replaced by a single quote “\n” is replaced by a new line “\t” is replaced by a tab space “\$” is replaced by a dollar sign “\r” is replaced by a carriage return “\\” is replaced by a backslash “\”” is replaced by a double quote “\'” is replaced by a single quote The string starting with a dollar sign(“$”) are treated as variables and are replaced with the content of the variables. 3. Heredoc: The syntax of Heredoc (<<<) is another way to delimit PHP strings. An identifier is given after the heredoc (<<< ) operator, after which any text can be written as a new line is started. To close the syntax, the same identifier is given without any tab or space. Note: Heredoc syntax is similar to the double-quoted string, without the quotes. Example: PHP <?php $input = <<<testHeredoc Welcome to GeeksforGeeks.Started content writing in GeeksforGeeks!.I am enjoying this. testHeredoc; echo $input; ?> Output: Welcome to GeeksforGeeks. Started content writing in GeeksforGeeks!. I am enjoying this. 4. Nowdoc: Nowdoc is very much similar to the heredoc other than the parsing done in heredoc. The syntax is similar to the heredoc syntax with symbol <<< followed by an identifier enclosed in single-quote. The rule for nowdoc is the same as heredoc. Note: Nowdoc syntax is similar to the single-quoted string. Example: PHP <?php $input = <<<'testNowdoc' Welcome to GeeksforGeeks.Started content writing in GeeksforGeeks!. testNowdoc; echo $input; // Directly printing string without any variableecho <<<'Nowdoc'<br/>Welcome to GFG .Learning PHP is fun in GFG. Nowdoc; ?> Output: Welcome to GeeksforGeeks. Started content writing in GeeksforGeeks!. Welcome to GFG . Learning PHP is fun in GFG. Built-in String functions Built-in functions in PHP are some existing library functions that can be used directly in our programs making an appropriate call to them. Below are some important built-in string functions that we use in our daily and regular programs: 1. strlen() function: This function is used to find the length of a string. This function accepts the string as an argument and returns the length or number of characters in the string. Example: PHP <?php echo strlen("Hello GeeksforGeeks!"); ?> Output: 20 2. strrev() function: This function is used to reverse a string. This function accepts a string as an argument and returns its reversed string. Example: PHP <?php echo strrev("Hello GeeksforGeeks!"); ?> Output: !skeeGrofskeeG olleH 3. str_replace() function: This function takes three strings as arguments. The third argument is the original string and the first argument is replaced by the second one. In other words, we can say that it replaces all occurrences of the first argument in the original string with the second argument. Example: PHP <?php echo str_replace("Geeks", "World", "Hello GeeksforGeeks!"), "\n";echo str_replace("for", "World", "Hello GeeksforGeeks!"), "\n"; ?> Output: Hello WorldforWorld! Hello GeeksWorldGeeks! In the first example, we can see that all occurrences of the word “Geeks” are replaced by “World” in “Hello GeeksforGeeks!”. 4. strpos() function: This function takes two string arguments and if the second string is present in the first one, it will return the starting position of the string otherwise returns FALSE. Example: PHP <?php echo strpos("Hello GeeksforGeeks!", "Geeks"), "\n"; echo strpos("Hello GeeksforGeeks!", "for"), "\n"; var_dump(strpos("Hello GeeksforGeeks!", "Peek")); ?> Output: 6 11 bool(false) We can see in the above program, in the third example the string “Peek” is not present in the first string, hence this function returns a boolean value false indicating that string is not present. 5. trim() function: This function allows us to remove whitespaces or strings from both sides of a string. Example: PHP <?php echo trim("Hello World!", "Hed!"); ?> Output: llo Worl 6. explode() function: This function converts a string into an array. Example: PHP <?php $input = "Welcome to geeksforgeeks"; print_r(explode(" ",$input)); ?> Output: Array ( [0] => Welcome [1] => to [2] => geeksforgeeks ) 7. strtolower() function: This function converts a string into the lowercase string. Example: PHP <?php $input = "WELCOME TO GEEKSFORGEEKS"; echo strtolower($input); ?> Output: welcome to geeksforgeeks 8. strtoupper() function: This function converts a string into the uppercase string. Example: PHP <?php $input = "Welcome to geeksforgeeks"; echo strtoupper($input); ?> Output: WELCOME TO GEEKSFORGEEKS 9. strwordcount() function: This function counts total words in a string. Example: PHP <?php $input = "Welcome to GeeksforGeeks"; echo str_word_count($input); ?> Output: 3 10. substr() function: This function gives the substring of a given string from a given index. Example: PHP <?php $input = "Welcome to geeksforgeeks"; echo(substr($input,3)); ?> Output: come to geeksforgeeks Recent articles on PHP Strings This article is contributed by Chinmoy Lenka. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. geetanjali16 mehulp1612 C-String-Question PHP-basics PHP-string PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to execute PHP code using command line ? How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? PHP in_array() Function How to pop an alert message box using PHP ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 42163, "s": 42135, "text": "\n05 May, 2021" }, { "code": null, "e": 42370, "s": 42163, "text": "Strings can be seen as a stream of characters. For example, ‘G’ is a character and ‘GeeksforGeeks’ is a string. We have learned about the basics of string data type in PHP in PHP | Data types and Variables." }, { "code": null, "e": 42512, "s": 42370, "text": " In this article, we will discuss strings in detail. Everything inside quotes, single (‘ ‘) and double (” “) in PHP is treated as a string. " }, { "code": null, "e": 42579, "s": 42512, "text": "Creating Strings:There are four ways of creating strings in PHP: " }, { "code": null, "e": 42676, "s": 42579, "text": "1. Single-quote strings: This type of string does not process special characters inside quotes. " }, { "code": null, "e": 42680, "s": 42676, "text": "PHP" }, { "code": "<?php // single-quote strings $site = 'Welcome to GeeksforGeeks'; echo $site; ?>", "e": 42763, "s": 42680, "text": null }, { "code": null, "e": 42772, "s": 42763, "text": "Output: " }, { "code": null, "e": 42797, "s": 42772, "text": "Welcome to GeeksforGeeks" }, { "code": null, "e": 42990, "s": 42797, "text": "The above program compiles correctly. We have created a string ‘Welcome to GeeksforGeeks’ and stored it in variable and printing it using echo statement. Let us now look at the below program: " }, { "code": null, "e": 42994, "s": 42990, "text": "PHP" }, { "code": "<?php // single-quote strings $site = 'GeeksforGeeks'; echo 'Welcome to $site'; ?>", "e": 43079, "s": 42994, "text": null }, { "code": null, "e": 43089, "s": 43079, "text": "Output: " }, { "code": null, "e": 43106, "s": 43089, "text": "Welcome to $site" }, { "code": null, "e": 43391, "s": 43106, "text": "In the above program the echo statement prints the variable name rather than printing the contents of the variables. This is because single-quotes strings in PHP do not process special characters. Hence, the string is unable to identify the ‘$’ sign as the start of a variable name. " }, { "code": null, "e": 43521, "s": 43391, "text": "2.Double-quote strings : Unlike single-quote strings, double-quote strings in PHP are capable of processing special characters. " }, { "code": null, "e": 43525, "s": 43521, "text": "PHP" }, { "code": "<?php // double-quote strings echo \"Welcome to GeeksforGeeks \\n\"; $site = \"GeeksforGeeks\"; echo \"Welcome to $site\"; ?>", "e": 43646, "s": 43525, "text": null }, { "code": null, "e": 43655, "s": 43646, "text": "Output: " }, { "code": null, "e": 43705, "s": 43655, "text": "Welcome to GeeksforGeeks\nWelcome to GeeksforGeeks" }, { "code": null, "e": 43975, "s": 43705, "text": "In the above program, we can see that the double-quote strings are processing the special characters according to their properties. The ‘\\n’ character is not printed and is considered as a new line. Also instead of the variable name $site, “GeeksforGeeks” is printed. " }, { "code": null, "e": 44035, "s": 43975, "text": "PHP treats everything inside double quotes(” “) as Strings." }, { "code": null, "e": 44601, "s": 44035, "text": " In this article, we will learn about the working of the various string functions and how to implement them along with some special properties of strings. Unlike other data types like integers, doubles, etc. Strings do not have any fixed limits or ranges. It can extend to any length as long as it is within the quotes. It has been discussed earlier that string with single and double quotes are treated differently. Strings within a single quote ignore the special characters, but double-quoted strings recognize the special characters and treat them differently. " }, { "code": null, "e": 44611, "s": 44601, "text": "Example: " }, { "code": null, "e": 44615, "s": 44611, "text": "PHP" }, { "code": "<?php $name = \"Krishna\";echo \"The name of the geek is $name \\n\";echo 'The name of the geek is $name'; ?>", "e": 44722, "s": 44615, "text": null }, { "code": null, "e": 44731, "s": 44722, "text": "Output: " }, { "code": null, "e": 44794, "s": 44731, "text": "The name of the geek is Krishna \nThe name of the geek is $name" }, { "code": null, "e": 44911, "s": 44794, "text": "Some important and frequently used special characters that are used with double-quoted strings are explained below: " }, { "code": null, "e": 45069, "s": 44911, "text": "The character begins with a backslash(“\\”) is treated as escape sequences and is replaced with special characters. Here are few important escape sequences. " }, { "code": null, "e": 45300, "s": 45069, "text": "“\\n” is replaced by a new line“\\t” is replaced by a tab space“\\$” is replaced by a dollar sign“\\r” is replaced by a carriage return“\\\\” is replaced by a backslash“\\”” is replaced by a double quote“\\'” is replaced by a single quote" }, { "code": null, "e": 45331, "s": 45300, "text": "“\\n” is replaced by a new line" }, { "code": null, "e": 45363, "s": 45331, "text": "“\\t” is replaced by a tab space" }, { "code": null, "e": 45397, "s": 45363, "text": "“\\$” is replaced by a dollar sign" }, { "code": null, "e": 45435, "s": 45397, "text": "“\\r” is replaced by a carriage return" }, { "code": null, "e": 45467, "s": 45435, "text": "“\\\\” is replaced by a backslash" }, { "code": null, "e": 45502, "s": 45467, "text": "“\\”” is replaced by a double quote" }, { "code": null, "e": 45537, "s": 45502, "text": "“\\'” is replaced by a single quote" }, { "code": null, "e": 45658, "s": 45537, "text": "The string starting with a dollar sign(“$”) are treated as variables and are replaced with the content of the variables." }, { "code": null, "e": 45935, "s": 45658, "text": "3. Heredoc: The syntax of Heredoc (<<<) is another way to delimit PHP strings. An identifier is given after the heredoc (<<< ) operator, after which any text can be written as a new line is started. To close the syntax, the same identifier is given without any tab or space. " }, { "code": null, "e": 46016, "s": 45935, "text": "Note: Heredoc syntax is similar to the double-quoted string, without the quotes." }, { "code": null, "e": 46025, "s": 46016, "text": "Example:" }, { "code": null, "e": 46029, "s": 46025, "text": "PHP" }, { "code": "<?php $input = <<<testHeredoc Welcome to GeeksforGeeks.Started content writing in GeeksforGeeks!.I am enjoying this. testHeredoc; echo $input; ?>", "e": 46184, "s": 46029, "text": null }, { "code": null, "e": 46192, "s": 46184, "text": "Output:" }, { "code": null, "e": 46281, "s": 46192, "text": "Welcome to GeeksforGeeks.\nStarted content writing in GeeksforGeeks!.\nI am enjoying this." }, { "code": null, "e": 46532, "s": 46281, "text": "4. Nowdoc: Nowdoc is very much similar to the heredoc other than the parsing done in heredoc. The syntax is similar to the heredoc syntax with symbol <<< followed by an identifier enclosed in single-quote. The rule for nowdoc is the same as heredoc." }, { "code": null, "e": 46592, "s": 46532, "text": "Note: Nowdoc syntax is similar to the single-quoted string." }, { "code": null, "e": 46601, "s": 46592, "text": "Example:" }, { "code": null, "e": 46605, "s": 46601, "text": "PHP" }, { "code": "<?php $input = <<<'testNowdoc' Welcome to GeeksforGeeks.Started content writing in GeeksforGeeks!. testNowdoc; echo $input; // Directly printing string without any variableecho <<<'Nowdoc'<br/>Welcome to GFG .Learning PHP is fun in GFG. Nowdoc; ?>", "e": 46861, "s": 46605, "text": null }, { "code": null, "e": 46869, "s": 46861, "text": "Output:" }, { "code": null, "e": 46985, "s": 46869, "text": "Welcome to GeeksforGeeks.\nStarted content writing in GeeksforGeeks!.\n\nWelcome to GFG .\nLearning PHP is fun in GFG. " }, { "code": null, "e": 47011, "s": 46985, "text": "Built-in String functions" }, { "code": null, "e": 47250, "s": 47011, "text": "Built-in functions in PHP are some existing library functions that can be used directly in our programs making an appropriate call to them. Below are some important built-in string functions that we use in our daily and regular programs: " }, { "code": null, "e": 47438, "s": 47250, "text": "1. strlen() function: This function is used to find the length of a string. This function accepts the string as an argument and returns the length or number of characters in the string. " }, { "code": null, "e": 47448, "s": 47438, "text": "Example: " }, { "code": null, "e": 47452, "s": 47448, "text": "PHP" }, { "code": "<?php echo strlen(\"Hello GeeksforGeeks!\"); ?>", "e": 47500, "s": 47452, "text": null }, { "code": null, "e": 47509, "s": 47500, "text": "Output: " }, { "code": null, "e": 47512, "s": 47509, "text": "20" }, { "code": null, "e": 47657, "s": 47512, "text": "2. strrev() function: This function is used to reverse a string. This function accepts a string as an argument and returns its reversed string. " }, { "code": null, "e": 47668, "s": 47657, "text": "Example: " }, { "code": null, "e": 47672, "s": 47668, "text": "PHP" }, { "code": "<?php echo strrev(\"Hello GeeksforGeeks!\"); ?>", "e": 47720, "s": 47672, "text": null }, { "code": null, "e": 47729, "s": 47720, "text": "Output: " }, { "code": null, "e": 47750, "s": 47729, "text": "!skeeGrofskeeG olleH" }, { "code": null, "e": 48053, "s": 47750, "text": "3. str_replace() function: This function takes three strings as arguments. The third argument is the original string and the first argument is replaced by the second one. In other words, we can say that it replaces all occurrences of the first argument in the original string with the second argument. " }, { "code": null, "e": 48063, "s": 48053, "text": "Example: " }, { "code": null, "e": 48067, "s": 48063, "text": "PHP" }, { "code": "<?php echo str_replace(\"Geeks\", \"World\", \"Hello GeeksforGeeks!\"), \"\\n\";echo str_replace(\"for\", \"World\", \"Hello GeeksforGeeks!\"), \"\\n\"; ?>", "e": 48206, "s": 48067, "text": null }, { "code": null, "e": 48215, "s": 48206, "text": "Output: " }, { "code": null, "e": 48259, "s": 48215, "text": "Hello WorldforWorld!\nHello GeeksWorldGeeks!" }, { "code": null, "e": 48385, "s": 48259, "text": "In the first example, we can see that all occurrences of the word “Geeks” are replaced by “World” in “Hello GeeksforGeeks!”. " }, { "code": null, "e": 48579, "s": 48385, "text": "4. strpos() function: This function takes two string arguments and if the second string is present in the first one, it will return the starting position of the string otherwise returns FALSE. " }, { "code": null, "e": 48589, "s": 48579, "text": "Example: " }, { "code": null, "e": 48593, "s": 48589, "text": "PHP" }, { "code": "<?php echo strpos(\"Hello GeeksforGeeks!\", \"Geeks\"), \"\\n\"; echo strpos(\"Hello GeeksforGeeks!\", \"for\"), \"\\n\"; var_dump(strpos(\"Hello GeeksforGeeks!\", \"Peek\")); ?>", "e": 48754, "s": 48593, "text": null }, { "code": null, "e": 48763, "s": 48754, "text": "Output: " }, { "code": null, "e": 48780, "s": 48763, "text": "6\n11\nbool(false)" }, { "code": null, "e": 48978, "s": 48780, "text": "We can see in the above program, in the third example the string “Peek” is not present in the first string, hence this function returns a boolean value false indicating that string is not present. " }, { "code": null, "e": 49085, "s": 48978, "text": "5. trim() function: This function allows us to remove whitespaces or strings from both sides of a string. " }, { "code": null, "e": 49095, "s": 49085, "text": "Example: " }, { "code": null, "e": 49099, "s": 49095, "text": "PHP" }, { "code": "<?php echo trim(\"Hello World!\", \"Hed!\"); ?>", "e": 49143, "s": 49099, "text": null }, { "code": null, "e": 49152, "s": 49143, "text": "Output: " }, { "code": null, "e": 49161, "s": 49152, "text": "llo Worl" }, { "code": null, "e": 49231, "s": 49161, "text": "6. explode() function: This function converts a string into an array." }, { "code": null, "e": 49241, "s": 49231, "text": "Example: " }, { "code": null, "e": 49245, "s": 49241, "text": "PHP" }, { "code": "<?php $input = \"Welcome to geeksforgeeks\"; print_r(explode(\" \",$input)); ?>", "e": 49330, "s": 49245, "text": null }, { "code": null, "e": 49338, "s": 49330, "text": "Output:" }, { "code": null, "e": 49394, "s": 49338, "text": "Array ( [0] => Welcome [1] => to [2] => geeksforgeeks )" }, { "code": null, "e": 49479, "s": 49394, "text": "7. strtolower() function: This function converts a string into the lowercase string." }, { "code": null, "e": 49489, "s": 49479, "text": "Example: " }, { "code": null, "e": 49493, "s": 49489, "text": "PHP" }, { "code": "<?php $input = \"WELCOME TO GEEKSFORGEEKS\"; echo strtolower($input); ?>", "e": 49572, "s": 49493, "text": null }, { "code": null, "e": 49580, "s": 49572, "text": "Output:" }, { "code": null, "e": 49605, "s": 49580, "text": "welcome to geeksforgeeks" }, { "code": null, "e": 49690, "s": 49605, "text": "8. strtoupper() function: This function converts a string into the uppercase string." }, { "code": null, "e": 49699, "s": 49690, "text": "Example:" }, { "code": null, "e": 49703, "s": 49699, "text": "PHP" }, { "code": "<?php $input = \"Welcome to geeksforgeeks\"; echo strtoupper($input); ?>", "e": 49782, "s": 49703, "text": null }, { "code": null, "e": 49790, "s": 49782, "text": "Output:" }, { "code": null, "e": 49815, "s": 49790, "text": "WELCOME TO GEEKSFORGEEKS" }, { "code": null, "e": 49889, "s": 49815, "text": "9. strwordcount() function: This function counts total words in a string." }, { "code": null, "e": 49898, "s": 49889, "text": "Example:" }, { "code": null, "e": 49902, "s": 49898, "text": "PHP" }, { "code": "<?php $input = \"Welcome to GeeksforGeeks\"; echo str_word_count($input); ?>", "e": 49986, "s": 49902, "text": null }, { "code": null, "e": 49994, "s": 49986, "text": "Output:" }, { "code": null, "e": 49996, "s": 49994, "text": "3" }, { "code": null, "e": 50091, "s": 49996, "text": "10. substr() function: This function gives the substring of a given string from a given index." }, { "code": null, "e": 50100, "s": 50091, "text": "Example:" }, { "code": null, "e": 50104, "s": 50100, "text": "PHP" }, { "code": "<?php $input = \"Welcome to geeksforgeeks\"; echo(substr($input,3)); ?>", "e": 50181, "s": 50104, "text": null }, { "code": null, "e": 50189, "s": 50181, "text": "Output:" }, { "code": null, "e": 50211, "s": 50189, "text": "come to geeksforgeeks" }, { "code": null, "e": 50242, "s": 50211, "text": "Recent articles on PHP Strings" }, { "code": null, "e": 50663, "s": 50242, "text": "This article is contributed by Chinmoy Lenka. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 50676, "s": 50663, "text": "geetanjali16" }, { "code": null, "e": 50687, "s": 50676, "text": "mehulp1612" }, { "code": null, "e": 50705, "s": 50687, "text": "C-String-Question" }, { "code": null, "e": 50716, "s": 50705, "text": "PHP-basics" }, { "code": null, "e": 50727, "s": 50716, "text": "PHP-string" }, { "code": null, "e": 50731, "s": 50727, "text": "PHP" }, { "code": null, "e": 50748, "s": 50731, "text": "Web Technologies" }, { "code": null, "e": 50752, "s": 50748, "text": "PHP" }, { "code": null, "e": 50850, "s": 50752, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 50895, "s": 50850, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 50945, "s": 50895, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 50985, "s": 50945, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 51009, "s": 50985, "text": "PHP in_array() Function" }, { "code": null, "e": 51053, "s": 51009, "text": "How to pop an alert message box using PHP ?" }, { "code": null, "e": 51093, "s": 51053, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 51126, "s": 51093, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 51171, "s": 51126, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 51214, "s": 51171, "text": "How to fetch data from an API in ReactJS ?" } ]
getpass() and getuser() in Python (Password without echo) - GeeksforGeeks
28 Jun, 2021 getpass() prompts the user for a password without echoing. The getpass module provides a secure way to handle the password prompts where programs interact with the users via the terminal.This module provides two functions : getpass() getpass() getpass.getpass(prompt='Password: ', stream=None) The getpass() function is used to prompt to users using the string prompt and reads the input from the user as Password. The input read defaults to “Password: ” is returned to the caller as a string.Let’s walk through some examples to understand its implementation.Example 1 : No Prompt provided by the caller The getpass() function is used to prompt to users using the string prompt and reads the input from the user as Password. The input read defaults to “Password: ” is returned to the caller as a string.Let’s walk through some examples to understand its implementation.Example 1 : No Prompt provided by the caller Python # A simple Python program to demonstrate# getpass.getpass() to read passwordimport getpass try: p = getpass.getpass()except Exception as error: print('ERROR', error)else: print('Password entered:', p) Here, no prompt is provided by the caller. So, it is set to the default prompt “Password”. Output : Here, no prompt is provided by the caller. So, it is set to the default prompt “Password”. Output : $ python3 getpass_example1.py Password: ('Password entered:', 'aditi') Example 2 : Security Question There are certain programs that ask for security questions rather than asking for passwords for better security. Here, the prompt can be changed to any value. Example 2 : Security Question There are certain programs that ask for security questions rather than asking for passwords for better security. Here, the prompt can be changed to any value. Python # A simple Python program to demonstrate# getpass.getpass() to read security questionimport getpass p = getpass.getpass(prompt='Your favorite flower? ') if p.lower() == 'rose': print('Welcome..!!!')else: print('The answer entered by you is incorrect..!!!') Output : Output : $ python3 getpass_example2.py Your favorite flower? Welcome..!!! $ python3 getpass_example2.py Your favorite flower? The answer entered by you is incorrect..!!! getuser() getpass.getuser()The getuser() function displays the login name of the user. This function checks the environment variables LOGNAME, USER, LNAME and USERNAME, in order, and returns the value of the first non-empty string. Example 3 : getuser() getpass.getuser()The getuser() function displays the login name of the user. This function checks the environment variables LOGNAME, USER, LNAME and USERNAME, in order, and returns the value of the first non-empty string. Example 3 : Python # Python program to demonstrate working of# getpass.getuser()import getpass user = getpass.getuser() while True: pwd = getpass.getpass("User Name : %s" % user) if pwd == 'abcd': print "Welcome!!!" break else: print "The password you entered is incorrect." Output : Output : $ python3 getpass_example3.py User Name : bot Welcome!!! $ python3 getpass_example3.py User Name : bot The password you entered is incorrect. This article is contributed by Aditi Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. ruhelaa48 Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists Convert integer to string in Python Check if element exists in list in Python
[ { "code": null, "e": 25985, "s": 25957, "text": "\n28 Jun, 2021" }, { "code": null, "e": 26211, "s": 25985, "text": "getpass() prompts the user for a password without echoing. The getpass module provides a secure way to handle the password prompts where programs interact with the users via the terminal.This module provides two functions : " }, { "code": null, "e": 26222, "s": 26211, "text": "getpass() " }, { "code": null, "e": 26233, "s": 26222, "text": "getpass() " }, { "code": null, "e": 26284, "s": 26233, "text": "getpass.getpass(prompt='Password: ', stream=None) " }, { "code": null, "e": 26596, "s": 26284, "text": "The getpass() function is used to prompt to users using the string prompt and reads the input from the user as Password. The input read defaults to “Password: ” is returned to the caller as a string.Let’s walk through some examples to understand its implementation.Example 1 : No Prompt provided by the caller " }, { "code": null, "e": 26908, "s": 26596, "text": "The getpass() function is used to prompt to users using the string prompt and reads the input from the user as Password. The input read defaults to “Password: ” is returned to the caller as a string.Let’s walk through some examples to understand its implementation.Example 1 : No Prompt provided by the caller " }, { "code": null, "e": 26915, "s": 26908, "text": "Python" }, { "code": "# A simple Python program to demonstrate# getpass.getpass() to read passwordimport getpass try: p = getpass.getpass()except Exception as error: print('ERROR', error)else: print('Password entered:', p)", "e": 27125, "s": 26915, "text": null }, { "code": null, "e": 27227, "s": 27125, "text": "Here, no prompt is provided by the caller. So, it is set to the default prompt “Password”. Output : " }, { "code": null, "e": 27329, "s": 27227, "text": "Here, no prompt is provided by the caller. So, it is set to the default prompt “Password”. Output : " }, { "code": null, "e": 27402, "s": 27329, "text": "$ python3 getpass_example1.py\n\nPassword: \n('Password entered:', 'aditi')" }, { "code": null, "e": 27593, "s": 27402, "text": "Example 2 : Security Question There are certain programs that ask for security questions rather than asking for passwords for better security. Here, the prompt can be changed to any value. " }, { "code": null, "e": 27784, "s": 27593, "text": "Example 2 : Security Question There are certain programs that ask for security questions rather than asking for passwords for better security. Here, the prompt can be changed to any value. " }, { "code": null, "e": 27791, "s": 27784, "text": "Python" }, { "code": "# A simple Python program to demonstrate# getpass.getpass() to read security questionimport getpass p = getpass.getpass(prompt='Your favorite flower? ') if p.lower() == 'rose': print('Welcome..!!!')else: print('The answer entered by you is incorrect..!!!')", "e": 28054, "s": 27791, "text": null }, { "code": null, "e": 28065, "s": 28054, "text": "Output : " }, { "code": null, "e": 28076, "s": 28065, "text": "Output : " }, { "code": null, "e": 28240, "s": 28076, "text": "$ python3 getpass_example2.py\n\nYour favorite flower?\nWelcome..!!!\n\n$ python3 getpass_example2.py\n\nYour favorite flower?\nThe answer entered by you is incorrect..!!!" }, { "code": null, "e": 28486, "s": 28240, "text": "getuser() getpass.getuser()The getuser() function displays the login name of the user. This function checks the environment variables LOGNAME, USER, LNAME and USERNAME, in order, and returns the value of the first non-empty string. Example 3 : " }, { "code": null, "e": 28732, "s": 28486, "text": "getuser() getpass.getuser()The getuser() function displays the login name of the user. This function checks the environment variables LOGNAME, USER, LNAME and USERNAME, in order, and returns the value of the first non-empty string. Example 3 : " }, { "code": null, "e": 28739, "s": 28732, "text": "Python" }, { "code": "# Python program to demonstrate working of# getpass.getuser()import getpass user = getpass.getuser() while True: pwd = getpass.getpass(\"User Name : %s\" % user) if pwd == 'abcd': print \"Welcome!!!\" break else: print \"The password you entered is incorrect.\"", "e": 29026, "s": 28739, "text": null }, { "code": null, "e": 29037, "s": 29026, "text": "Output : " }, { "code": null, "e": 29048, "s": 29037, "text": "Output : " }, { "code": null, "e": 29193, "s": 29048, "text": "$ python3 getpass_example3.py\n\nUser Name : bot\nWelcome!!!\n\n$ python3 getpass_example3.py\n\nUser Name : bot\nThe password you entered is incorrect." }, { "code": null, "e": 29617, "s": 29197, "text": "This article is contributed by Aditi Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 29627, "s": 29617, "text": "ruhelaa48" }, { "code": null, "e": 29634, "s": 29627, "text": "Python" }, { "code": null, "e": 29732, "s": 29634, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29750, "s": 29732, "text": "Python Dictionary" }, { "code": null, "e": 29782, "s": 29750, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29804, "s": 29782, "text": "Enumerate() in Python" }, { "code": null, "e": 29846, "s": 29804, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29872, "s": 29846, "text": "Python String | replace()" }, { "code": null, "e": 29901, "s": 29872, "text": "*args and **kwargs in Python" }, { "code": null, "e": 29945, "s": 29901, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 29982, "s": 29945, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 30018, "s": 29982, "text": "Convert integer to string in Python" } ]
Getting square root of a number in Julia - sqrt() and isqrt() Methods - GeeksforGeeks
26 Mar, 2020 The sqrt() is an inbuilt function in julia which is used to return the square root of the specified number and throws DomainError for negative Real parameter. It also accept complex negative parameter. Syntax: sqrt(x) Parameters: x: Specified values. Returns: It returns the square root of the specified number and throws DomainError for negative Real parameter. It also accept complex negative parameter. Example: # Julia program to illustrate # the use of sqrt() method # Getting the square root of the # specified number and throws DomainError# for negative Real parameterprintln(sqrt(9))println(sqrt(16))println(sqrt(complex(-25)))println(sqrt(-49)) Output: 3.0 4.0 0.0 + 5.0im ERROR: LoadError: DomainError: sqrt will only return a complex result if called with a complex argument. Try sqrt(complex(x)). Stacktrace: [1] sqrt(::Int64) at ./math.jl:434 while loading /home/cg/root/9093667/main.jl, in expression starting on line 10 The isqrt() is an inbuilt function in julia which is used to return integer square root of the specified value. The largest returned integer value m(say) such that Syntax:isqrt(n::Integer) Parameters: n::Integer: Specified values. Returns: It returns integer square root of the specified value. Example: # Julia program to illustrate # the use of isqrt() method # Getting integer square root of the specified value.println(isqrt(12))println(isqrt(17))println(isqrt(5))println(isqrt(227)) Output: 3 4 2 15 Julia Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder) Get array dimensions and size of a dimension in Julia - size() Method Exception handling in Julia Searching in Array for a given element in Julia Find maximum element along with its index in Julia - findmax() Method Get number of elements of array in Julia - length() Method Join an array of strings into a single string in Julia - join() Method File Handling in Julia Working with Excel Files in Julia Getting last element of an array in Julia - last() Method
[ { "code": null, "e": 25789, "s": 25761, "text": "\n26 Mar, 2020" }, { "code": null, "e": 25991, "s": 25789, "text": "The sqrt() is an inbuilt function in julia which is used to return the square root of the specified number and throws DomainError for negative Real parameter. It also accept complex negative parameter." }, { "code": null, "e": 26007, "s": 25991, "text": "Syntax: sqrt(x)" }, { "code": null, "e": 26019, "s": 26007, "text": "Parameters:" }, { "code": null, "e": 26040, "s": 26019, "text": "x: Specified values." }, { "code": null, "e": 26195, "s": 26040, "text": "Returns: It returns the square root of the specified number and throws DomainError for negative Real parameter. It also accept complex negative parameter." }, { "code": null, "e": 26204, "s": 26195, "text": "Example:" }, { "code": "# Julia program to illustrate # the use of sqrt() method # Getting the square root of the # specified number and throws DomainError# for negative Real parameterprintln(sqrt(9))println(sqrt(16))println(sqrt(complex(-25)))println(sqrt(-49))", "e": 26444, "s": 26204, "text": null }, { "code": null, "e": 26452, "s": 26444, "text": "Output:" }, { "code": null, "e": 26727, "s": 26452, "text": "3.0\n4.0\n0.0 + 5.0im\nERROR: LoadError: DomainError:\nsqrt will only return a complex result if called with a complex argument. Try sqrt(complex(x)).\nStacktrace:\n [1] sqrt(::Int64) at ./math.jl:434\nwhile loading /home/cg/root/9093667/main.jl, in expression starting on line 10\n" }, { "code": null, "e": 26892, "s": 26727, "text": "The isqrt() is an inbuilt function in julia which is used to return integer square root of the specified value. The largest returned integer value m(say) such that " }, { "code": null, "e": 26917, "s": 26892, "text": "Syntax:isqrt(n::Integer)" }, { "code": null, "e": 26929, "s": 26917, "text": "Parameters:" }, { "code": null, "e": 26959, "s": 26929, "text": "n::Integer: Specified values." }, { "code": null, "e": 27023, "s": 26959, "text": "Returns: It returns integer square root of the specified value." }, { "code": null, "e": 27032, "s": 27023, "text": "Example:" }, { "code": "# Julia program to illustrate # the use of isqrt() method # Getting integer square root of the specified value.println(isqrt(12))println(isqrt(17))println(isqrt(5))println(isqrt(227))", "e": 27217, "s": 27032, "text": null }, { "code": null, "e": 27225, "s": 27217, "text": "Output:" }, { "code": null, "e": 27235, "s": 27225, "text": "3\n4\n2\n15\n" }, { "code": null, "e": 27241, "s": 27235, "text": "Julia" }, { "code": null, "e": 27339, "s": 27241, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27412, "s": 27339, "text": "Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)" }, { "code": null, "e": 27482, "s": 27412, "text": "Get array dimensions and size of a dimension in Julia - size() Method" }, { "code": null, "e": 27510, "s": 27482, "text": "Exception handling in Julia" }, { "code": null, "e": 27558, "s": 27510, "text": "Searching in Array for a given element in Julia" }, { "code": null, "e": 27628, "s": 27558, "text": "Find maximum element along with its index in Julia - findmax() Method" }, { "code": null, "e": 27687, "s": 27628, "text": "Get number of elements of array in Julia - length() Method" }, { "code": null, "e": 27758, "s": 27687, "text": "Join an array of strings into a single string in Julia - join() Method" }, { "code": null, "e": 27781, "s": 27758, "text": "File Handling in Julia" }, { "code": null, "e": 27815, "s": 27781, "text": "Working with Excel Files in Julia" } ]
Python | Interconversion between Dictionary and Bytes
19 Jul, 2019 Interconversion between data is quite popular and this particular article discusses about how interconversion of dictionary into bytes and vice versa can be obtained. Let’s look at the method that can help us achieve this particular task. Method : Using encode() + dumps() + decode() + loads()The encode and dumps function together performs the task of converting the dictionary to string and then to corresponding byte value. This can be interconverted using the decode and loads function which returns the string from bytes and converts that to the dictionary again. # Python3 code to demonstrate working of# Interconversion between Dictionary and Bytes# Using encode() + dumps() + decode() + loads()import json # initializing dictionarytest_dict = {'Gfg' : 1, 'is' : 2, 'best' : 3} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # using encode() + dumps() to convert to bytesres_bytes = json.dumps(test_dict).encode('utf-8') # printing type and binary dict print("The type after conversion to bytes is : " + str(type(res_bytes)))print("The value after conversion to bytes is : " + str(res_bytes)) # using decode() + loads() to convert to dictionaryres_dict = json.loads(res_bytes.decode('utf-8')) # printing type and dict print("The type after conversion to dict is : " + str(type(res_dict)))print("The value after conversion to dict is : " + str(res_dict)) The original dictionary is : {'Gfg': 1, 'best': 3, 'is': 2} The type after conversion to bytes is : <class 'bytes'> The value after conversion to bytes is : b'{"Gfg": 1, "best": 3, "is": 2}' The type after conversion to dict is : <class 'dict'> The value after conversion to dict is : {'Gfg': 1, 'best': 3, 'is': 2} Python dictionary-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Jul, 2019" }, { "code": null, "e": 267, "s": 28, "text": "Interconversion between data is quite popular and this particular article discusses about how interconversion of dictionary into bytes and vice versa can be obtained. Let’s look at the method that can help us achieve this particular task." }, { "code": null, "e": 597, "s": 267, "text": "Method : Using encode() + dumps() + decode() + loads()The encode and dumps function together performs the task of converting the dictionary to string and then to corresponding byte value. This can be interconverted using the decode and loads function which returns the string from bytes and converts that to the dictionary again." }, { "code": "# Python3 code to demonstrate working of# Interconversion between Dictionary and Bytes# Using encode() + dumps() + decode() + loads()import json # initializing dictionarytest_dict = {'Gfg' : 1, 'is' : 2, 'best' : 3} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # using encode() + dumps() to convert to bytesres_bytes = json.dumps(test_dict).encode('utf-8') # printing type and binary dict print(\"The type after conversion to bytes is : \" + str(type(res_bytes)))print(\"The value after conversion to bytes is : \" + str(res_bytes)) # using decode() + loads() to convert to dictionaryres_dict = json.loads(res_bytes.decode('utf-8')) # printing type and dict print(\"The type after conversion to dict is : \" + str(type(res_dict)))print(\"The value after conversion to dict is : \" + str(res_dict))", "e": 1434, "s": 597, "text": null }, { "code": null, "e": 1751, "s": 1434, "text": "The original dictionary is : {'Gfg': 1, 'best': 3, 'is': 2}\nThe type after conversion to bytes is : <class 'bytes'>\nThe value after conversion to bytes is : b'{\"Gfg\": 1, \"best\": 3, \"is\": 2}'\nThe type after conversion to dict is : <class 'dict'>\nThe value after conversion to dict is : {'Gfg': 1, 'best': 3, 'is': 2}\n" }, { "code": null, "e": 1778, "s": 1751, "text": "Python dictionary-programs" }, { "code": null, "e": 1785, "s": 1778, "text": "Python" }, { "code": null, "e": 1801, "s": 1785, "text": "Python Programs" }, { "code": null, "e": 1899, "s": 1801, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1917, "s": 1899, "text": "Python Dictionary" }, { "code": null, "e": 1959, "s": 1917, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1981, "s": 1959, "text": "Enumerate() in Python" }, { "code": null, "e": 2016, "s": 1981, "text": "Read a file line by line in Python" }, { "code": null, "e": 2042, "s": 2016, "text": "Python String | replace()" }, { "code": null, "e": 2085, "s": 2042, "text": "Python program to convert a list to string" }, { "code": null, "e": 2107, "s": 2085, "text": "Defaultdict in Python" }, { "code": null, "e": 2146, "s": 2107, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2184, "s": 2146, "text": "Python | Convert a list to dictionary" } ]
Represent a given set of points by the best possible straight line
22 Apr, 2021 Find the value of m and c such that a straight line y = mx + c, best represents the equation of a given set of points (x, y), (x, y), (x, y), ......., (x, y), given n >=2. Examples: Input : n = 5 x = 1, x = 2, x = 3, x = 4, x = 5 y = 14, y = 27, y = 40, y = 55, y = 68 Output : m = 13.6 c = 0 If we take any pair of number ( x, y ) from the given data, these value of m and c should make it best fit into the equation for a straight line, y = mx + c. Take x = 1 and y = 14, then using values of m and c from the output, and putting it in the following equation, y = mx + c, L.H.S.: y = 14, R.H.S: mx + c = 13.6 x 1 + 0 = 13.6 So, they are approximately equal. Now, take x = 3 and y = 40, L.H.S.: y = 40, R.H.S: mx + c = 13.6 x 3 + 0 = 40.8 So, they are also approximately equal, and so on for all other values. Input : n = 6 x = 1, x = 2, x = 3, x = 4, x = 5, x = 6 y = 1200, y = 900, y = 600, y = 200, y = 110, y = 50 Output : m = -243.42 c = 1361.97 Approach To best fit a set of points in an equation for a straight line, we need to find the value of two variables, m and c. Now, since there are 2 unknown variables and depending upon the value of n, two cases are possible – Case 1 – When n = 2 : There will be two equations and two unknown variables to find, so, there will be a unique solution . Case 2 – When n > 2 : In this case, there may or may not exist values of m and c, which satisfy all the n equations, but we can find the best possible values of m and c which can fit a straight line in the given points . So, if we have n different pairs of x and y, then, we can form n no. of equations from them for a straight line, as follows f = mx + c, f = mx + c, f = mx + c, ......................................, ......................................, f = mx + c, where, f, is the value obtained by putting x in equation mx + c. Then, since ideally fshould be same as y, but still we can find the fclosest to yin all the cases, if we take a new quantity, U = ?(y– f), and make this quantity minimum for all value of i from 1 to n. Note:(y– f)is used in place of (y– f), as we want to consider both the cases when for when yis greater, and we want their difference to be minimum, so if we would not square the term, then situations in which fis greater and situation in which yis greater will ancel each other to an extent, and this is not what we want. So, we need to square the term. Now, for U to be minimum, it must satisfy the following two equations – = 0 and = 0. On solving the above two equations, we get two equations, as follows : ?y = nc + m?x, and ?xy = c?x + m?x, which can be rearranged as - m = (n * ?xy - ?x?y) / (n * ?x - (?x)), and c = (?y - m?x) / n, So, this is how values of m and c for both the cases are obtained, and we can represent a given set of points, by the best possible straight line. The following code implements the above given algorithm – C++ C Java Python3 C# PHP Javascript // C++ Program to find m and c for a straight line given,// x and y#include <cmath>#include <iostream>using namespace std; // function to calculate m and c that best fit points// represented by x[] and y[]void bestApproximate(int x[], int y[], int n){ float m, c, sum_x = 0, sum_y = 0, sum_xy = 0, sum_x2 = 0; for (int i = 0; i < n; i++) { sum_x += x[i]; sum_y += y[i]; sum_xy += x[i] * y[i]; sum_x2 += pow(x[i], 2); } m = (n * sum_xy - sum_x * sum_y) / (n * sum_x2 - pow(sum_x, 2)); c = (sum_y - m * sum_x) / n; cout << "m =" << m; cout << "\nc =" << c;} // Driver main functionint main(){ int x[] = { 1, 2, 3, 4, 5 }; int y[] = { 14, 27, 40, 55, 68 }; int n = sizeof(x) / sizeof(x[0]); bestApproximate(x, y, n); return 0;} // C Program to find m and c for a straight line given,// x and y#include <stdio.h> // function to calculate m and c that best fit points// represented by x[] and y[]void bestApproximate(int x[], int y[], int n){ int i, j; float m, c, sum_x = 0, sum_y = 0, sum_xy = 0, sum_x2 = 0; for (i = 0; i < n; i++) { sum_x += x[i]; sum_y += y[i]; sum_xy += x[i] * y[i]; sum_x2 += (x[i] * x[i]); } m = (n * sum_xy - sum_x * sum_y) / (n * sum_x2 - (sum_x * sum_x)); c = (sum_y - m * sum_x) / n; printf("m =% f", m); printf("\nc =% f", c);} // Driver main functionint main(){ int x[] = { 1, 2, 3, 4, 5 }; int y[] = { 14, 27, 40, 55, 68 }; int n = sizeof(x) / sizeof(x[0]); bestApproximate(x, y, n); return 0;} // Java Program to find m and c for a straight line given,// x and yimport java.io.*;import static java.lang.Math.pow; public class A { // function to calculate m and c that best fit points // represented by x[] and y[] static void bestApproximate(int x[], int y[]) { int n = x.length; double m, c, sum_x = 0, sum_y = 0, sum_xy = 0, sum_x2 = 0; for (int i = 0; i < n; i++) { sum_x += x[i]; sum_y += y[i]; sum_xy += x[i] * y[i]; sum_x2 += pow(x[i], 2); } m = (n * sum_xy - sum_x * sum_y) / (n * sum_x2 - pow(sum_x, 2)); c = (sum_y - m * sum_x) / n; System.out.println("m = " + m); System.out.println("c = " + c); } // Driver main function public static void main(String args[]) { int x[] = { 1, 2, 3, 4, 5 }; int y[] = { 14, 27, 40, 55, 68 }; bestApproximate(x, y); }} # python Program to find m and c for# a straight line given, x and y # function to calculate m and c that# best fit points represented by x[]# and y[]def bestApproximate(x, y, n): sum_x = 0 sum_y = 0 sum_xy = 0 sum_x2 = 0 for i in range (0, n): sum_x += x[i] sum_y += y[i] sum_xy += x[i] * y[i] sum_x2 += pow(x[i], 2) m = (float)((n * sum_xy - sum_x * sum_y) / (n * sum_x2 - pow(sum_x, 2))); c = (float)(sum_y - m * sum_x) / n; print("m = ", m); print("c = ", c); # Driver main functionx = [1, 2, 3, 4, 5 ]y = [ 14, 27, 40, 55, 68]n = len(x) bestApproximate(x, y, n) # This code is contributed by Sam007. // C# Program to find m and c for a// straight line given, x and yusing System; class GFG { // function to calculate m and c that // best fit points represented by x[] and y[] static void bestApproximate(int[] x, int[] y) { int n = x.Length; double m, c, sum_x = 0, sum_y = 0, sum_xy = 0, sum_x2 = 0; for (int i = 0; i < n; i++) { sum_x += x[i]; sum_y += y[i]; sum_xy += x[i] * y[i]; sum_x2 += Math.Pow(x[i], 2); } m = (n * sum_xy - sum_x * sum_y) / (n * sum_x2 - Math.Pow(sum_x, 2)); c = (sum_y - m * sum_x) / n; Console.WriteLine("m = " + m); Console.WriteLine("c = " + c); } // Driver main function public static void Main() { int[] x = { 1, 2, 3, 4, 5 }; int[] y = { 14, 27, 40, 55, 68 }; // Function calling bestApproximate(x, y); }} // This code is contributed by Sam007 <?php// PHP Program to find m and c// for a straight line given,// x and y // function to calculate m and// c that best fit points// represented by x[] and y[]function bestApproximate($x, $y, $n){ $i; $j; $m; $c; $sum_x = 0; $sum_y = 0; $sum_xy = 0; $sum_x2 = 0; for ($i = 0; $i < $n; $i++) { $sum_x += $x[$i]; $sum_y += $y[$i]; $sum_xy += $x[$i] * $y[$i]; $sum_x2 += ($x[$i] * $x[$i]); } $m = ($n * $sum_xy - $sum_x * $sum_y) / ($n * $sum_x2 - ($sum_x * $sum_x)); $c = ($sum_y - $m * $sum_x) / $n; echo "m =", $m; echo "\nc =", $c;} // Driver Code $x =array(1, 2, 3, 4, 5); $y =array (14, 27, 40, 55, 68); $n = sizeof($x); bestApproximate($x, $y, $n); // This code is contributed by ajit?> <script> // Javascript Program to find m and c// for a straight line given, x and y // function to calculate m and c that// best fit points represented by x[] and y[]function bestApproximate(x, y, n){ let m, c, sum_x = 0, sum_y = 0, sum_xy = 0, sum_x2 = 0; for(let i = 0; i < n; i++) { sum_x += x[i]; sum_y += y[i]; sum_xy += x[i] * y[i]; sum_x2 += Math.pow(x[i], 2); } m = (n * sum_xy - sum_x * sum_y) / (n * sum_x2 - Math.pow(sum_x, 2)); c = (sum_y - m * sum_x) / n; document.write("m =" + m); document.write("<br>c =" + c);} // Driver codelet x = [ 1, 2, 3, 4, 5 ];let y = [ 14, 27, 40, 55, 68 ];let n = x.length; bestApproximate(x, y, n); // This code is contributed by subham348 </script> Output: m=13.6 c=0.0 Analysis of above code- Auxiliary Space : O(1) Time Complexity : O(n). We have one loop which iterates n times, and each time it performs constant no. of computations. Reference- 1-Higher Engineering Mathematics by B.S. Grewal. This article is contributed by Mrigendra Singh. 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. Sam007 jit_t subham348 Geometric Mathematical Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program for distance between two points on earth Find if two rectangles overlap Check whether triangle is valid or not if sides are given Line Clipping | Set 1 (Cohen–Sutherland Algorithm) Program for Point of Intersection of Two Lines Program for Fibonacci numbers Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string C++ Data Types Merge two sorted arrays
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Apr, 2021" }, { "code": null, "e": 224, "s": 52, "text": "Find the value of m and c such that a straight line y = mx + c, best represents the equation of a given set of points (x, y), (x, y), (x, y), ......., (x, y), given n >=2." }, { "code": null, "e": 236, "s": 224, "text": "Examples: " }, { "code": null, "e": 1026, "s": 236, "text": "Input : n = 5\n x = 1, x = 2, x = 3, \nx = 4, x = 5\ny = 14, y = 27, y = 40, \ny = 55, y = 68 \nOutput : m = 13.6\nc = 0 \nIf we take any pair of number ( x, y ) \nfrom the given data, these value of m and c\nshould make it best fit into the equation \nfor a straight line, y = mx + c. Take x = 1 \nand y = 14, then using values\nof m and c from the output, and putting it \nin the following equation,\ny = mx + c,\nL.H.S.: y = 14, R.H.S: mx + c = 13.6 x 1 + 0 = 13.6\nSo, they are approximately equal.\nNow, take x = 3 and y = 40,\nL.H.S.: y = 40, R.H.S: mx + c = 13.6 x 3 + 0 = 40.8\nSo, they are also approximately equal, and so on\nfor all other values.\nInput : n = 6\nx = 1, x = 2, x = 3, \nx = 4, x = 5, x = 6\ny = 1200, y = 900, y = 600, \ny = 200, y = 110, y = 50\nOutput : m = -243.42\nc = 1361.97" }, { "code": null, "e": 1035, "s": 1026, "text": "Approach" }, { "code": null, "e": 1254, "s": 1035, "text": "To best fit a set of points in an equation for a straight line, we need to find the value of two variables, m and c. Now, since there are 2 unknown variables and depending upon the value of n, two cases are possible – " }, { "code": null, "e": 1598, "s": 1254, "text": "Case 1 – When n = 2 : There will be two equations and two unknown variables to find, so, there will be a unique solution . Case 2 – When n > 2 : In this case, there may or may not exist values of m and c, which satisfy all the n equations, but we can find the best possible values of m and c which can fit a straight line in the given points ." }, { "code": null, "e": 1723, "s": 1598, "text": "So, if we have n different pairs of x and y, then, we can form n no. of equations from them for a straight line, as follows " }, { "code": null, "e": 1919, "s": 1723, "text": "f = mx + c,\nf = mx + c,\nf = mx + c,\n......................................,\n......................................,\nf = mx + c,\nwhere, f, is the value \nobtained by putting x in equation \nmx + c. " }, { "code": null, "e": 2122, "s": 1919, "text": "Then, since ideally fshould be same as y, but still we can find the fclosest to yin all the cases, if we take a new quantity, U = ?(y– f), and make this quantity minimum for all value of i from 1 to n. " }, { "code": null, "e": 2476, "s": 2122, "text": "Note:(y– f)is used in place of (y– f), as we want to consider both the cases when for when yis greater, and we want their difference to be minimum, so if we would not square the term, then situations in which fis greater and situation in which yis greater will ancel each other to an extent, and this is not what we want. So, we need to square the term." }, { "code": null, "e": 2548, "s": 2476, "text": "Now, for U to be minimum, it must satisfy the following two equations –" }, { "code": null, "e": 2566, "s": 2548, "text": " = 0 and \n = 0. " }, { "code": null, "e": 2638, "s": 2566, "text": "On solving the above two equations, we get two equations, as follows : " }, { "code": null, "e": 2769, "s": 2638, "text": "?y = nc + m?x, and\n?xy = c?x + m?x, which can be rearranged as - \nm = (n * ?xy - ?x?y) / (n * ?x - (?x)), and\nc = (?y - m?x) / n, " }, { "code": null, "e": 2917, "s": 2769, "text": "So, this is how values of m and c for both the cases are obtained, and we can represent a given set of points, by the best possible straight line. " }, { "code": null, "e": 2976, "s": 2917, "text": "The following code implements the above given algorithm – " }, { "code": null, "e": 2980, "s": 2976, "text": "C++" }, { "code": null, "e": 2982, "s": 2980, "text": "C" }, { "code": null, "e": 2987, "s": 2982, "text": "Java" }, { "code": null, "e": 2995, "s": 2987, "text": "Python3" }, { "code": null, "e": 2998, "s": 2995, "text": "C#" }, { "code": null, "e": 3002, "s": 2998, "text": "PHP" }, { "code": null, "e": 3013, "s": 3002, "text": "Javascript" }, { "code": "// C++ Program to find m and c for a straight line given,// x and y#include <cmath>#include <iostream>using namespace std; // function to calculate m and c that best fit points// represented by x[] and y[]void bestApproximate(int x[], int y[], int n){ float m, c, sum_x = 0, sum_y = 0, sum_xy = 0, sum_x2 = 0; for (int i = 0; i < n; i++) { sum_x += x[i]; sum_y += y[i]; sum_xy += x[i] * y[i]; sum_x2 += pow(x[i], 2); } m = (n * sum_xy - sum_x * sum_y) / (n * sum_x2 - pow(sum_x, 2)); c = (sum_y - m * sum_x) / n; cout << \"m =\" << m; cout << \"\\nc =\" << c;} // Driver main functionint main(){ int x[] = { 1, 2, 3, 4, 5 }; int y[] = { 14, 27, 40, 55, 68 }; int n = sizeof(x) / sizeof(x[0]); bestApproximate(x, y, n); return 0;}", "e": 3804, "s": 3013, "text": null }, { "code": "// C Program to find m and c for a straight line given,// x and y#include <stdio.h> // function to calculate m and c that best fit points// represented by x[] and y[]void bestApproximate(int x[], int y[], int n){ int i, j; float m, c, sum_x = 0, sum_y = 0, sum_xy = 0, sum_x2 = 0; for (i = 0; i < n; i++) { sum_x += x[i]; sum_y += y[i]; sum_xy += x[i] * y[i]; sum_x2 += (x[i] * x[i]); } m = (n * sum_xy - sum_x * sum_y) / (n * sum_x2 - (sum_x * sum_x)); c = (sum_y - m * sum_x) / n; printf(\"m =% f\", m); printf(\"\\nc =% f\", c);} // Driver main functionint main(){ int x[] = { 1, 2, 3, 4, 5 }; int y[] = { 14, 27, 40, 55, 68 }; int n = sizeof(x) / sizeof(x[0]); bestApproximate(x, y, n); return 0;}", "e": 4570, "s": 3804, "text": null }, { "code": "// Java Program to find m and c for a straight line given,// x and yimport java.io.*;import static java.lang.Math.pow; public class A { // function to calculate m and c that best fit points // represented by x[] and y[] static void bestApproximate(int x[], int y[]) { int n = x.length; double m, c, sum_x = 0, sum_y = 0, sum_xy = 0, sum_x2 = 0; for (int i = 0; i < n; i++) { sum_x += x[i]; sum_y += y[i]; sum_xy += x[i] * y[i]; sum_x2 += pow(x[i], 2); } m = (n * sum_xy - sum_x * sum_y) / (n * sum_x2 - pow(sum_x, 2)); c = (sum_y - m * sum_x) / n; System.out.println(\"m = \" + m); System.out.println(\"c = \" + c); } // Driver main function public static void main(String args[]) { int x[] = { 1, 2, 3, 4, 5 }; int y[] = { 14, 27, 40, 55, 68 }; bestApproximate(x, y); }}", "e": 5509, "s": 4570, "text": null }, { "code": "# python Program to find m and c for# a straight line given, x and y # function to calculate m and c that# best fit points represented by x[]# and y[]def bestApproximate(x, y, n): sum_x = 0 sum_y = 0 sum_xy = 0 sum_x2 = 0 for i in range (0, n): sum_x += x[i] sum_y += y[i] sum_xy += x[i] * y[i] sum_x2 += pow(x[i], 2) m = (float)((n * sum_xy - sum_x * sum_y) / (n * sum_x2 - pow(sum_x, 2))); c = (float)(sum_y - m * sum_x) / n; print(\"m = \", m); print(\"c = \", c); # Driver main functionx = [1, 2, 3, 4, 5 ]y = [ 14, 27, 40, 55, 68]n = len(x) bestApproximate(x, y, n) # This code is contributed by Sam007.", "e": 6222, "s": 5509, "text": null }, { "code": "// C# Program to find m and c for a// straight line given, x and yusing System; class GFG { // function to calculate m and c that // best fit points represented by x[] and y[] static void bestApproximate(int[] x, int[] y) { int n = x.Length; double m, c, sum_x = 0, sum_y = 0, sum_xy = 0, sum_x2 = 0; for (int i = 0; i < n; i++) { sum_x += x[i]; sum_y += y[i]; sum_xy += x[i] * y[i]; sum_x2 += Math.Pow(x[i], 2); } m = (n * sum_xy - sum_x * sum_y) / (n * sum_x2 - Math.Pow(sum_x, 2)); c = (sum_y - m * sum_x) / n; Console.WriteLine(\"m = \" + m); Console.WriteLine(\"c = \" + c); } // Driver main function public static void Main() { int[] x = { 1, 2, 3, 4, 5 }; int[] y = { 14, 27, 40, 55, 68 }; // Function calling bestApproximate(x, y); }} // This code is contributed by Sam007", "e": 7181, "s": 6222, "text": null }, { "code": "<?php// PHP Program to find m and c// for a straight line given,// x and y // function to calculate m and// c that best fit points// represented by x[] and y[]function bestApproximate($x, $y, $n){ $i; $j; $m; $c; $sum_x = 0; $sum_y = 0; $sum_xy = 0; $sum_x2 = 0; for ($i = 0; $i < $n; $i++) { $sum_x += $x[$i]; $sum_y += $y[$i]; $sum_xy += $x[$i] * $y[$i]; $sum_x2 += ($x[$i] * $x[$i]); } $m = ($n * $sum_xy - $sum_x * $sum_y) / ($n * $sum_x2 - ($sum_x * $sum_x)); $c = ($sum_y - $m * $sum_x) / $n; echo \"m =\", $m; echo \"\\nc =\", $c;} // Driver Code $x =array(1, 2, 3, 4, 5); $y =array (14, 27, 40, 55, 68); $n = sizeof($x); bestApproximate($x, $y, $n); // This code is contributed by ajit?>", "e": 7965, "s": 7181, "text": null }, { "code": "<script> // Javascript Program to find m and c// for a straight line given, x and y // function to calculate m and c that// best fit points represented by x[] and y[]function bestApproximate(x, y, n){ let m, c, sum_x = 0, sum_y = 0, sum_xy = 0, sum_x2 = 0; for(let i = 0; i < n; i++) { sum_x += x[i]; sum_y += y[i]; sum_xy += x[i] * y[i]; sum_x2 += Math.pow(x[i], 2); } m = (n * sum_xy - sum_x * sum_y) / (n * sum_x2 - Math.pow(sum_x, 2)); c = (sum_y - m * sum_x) / n; document.write(\"m =\" + m); document.write(\"<br>c =\" + c);} // Driver codelet x = [ 1, 2, 3, 4, 5 ];let y = [ 14, 27, 40, 55, 68 ];let n = x.length; bestApproximate(x, y, n); // This code is contributed by subham348 </script>", "e": 8732, "s": 7965, "text": null }, { "code": null, "e": 8741, "s": 8732, "text": "Output: " }, { "code": null, "e": 8754, "s": 8741, "text": "m=13.6\nc=0.0" }, { "code": null, "e": 8922, "s": 8754, "text": "Analysis of above code- Auxiliary Space : O(1) Time Complexity : O(n). We have one loop which iterates n times, and each time it performs constant no. of computations." }, { "code": null, "e": 8982, "s": 8922, "text": "Reference- 1-Higher Engineering Mathematics by B.S. Grewal." }, { "code": null, "e": 9410, "s": 8982, "text": "This article is contributed by Mrigendra Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 9417, "s": 9410, "text": "Sam007" }, { "code": null, "e": 9423, "s": 9417, "text": "jit_t" }, { "code": null, "e": 9433, "s": 9423, "text": "subham348" }, { "code": null, "e": 9443, "s": 9433, "text": "Geometric" }, { "code": null, "e": 9456, "s": 9443, "text": "Mathematical" }, { "code": null, "e": 9469, "s": 9456, "text": "Mathematical" }, { "code": null, "e": 9479, "s": 9469, "text": "Geometric" }, { "code": null, "e": 9577, "s": 9479, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9626, "s": 9577, "text": "Program for distance between two points on earth" }, { "code": null, "e": 9657, "s": 9626, "text": "Find if two rectangles overlap" }, { "code": null, "e": 9715, "s": 9657, "text": "Check whether triangle is valid or not if sides are given" }, { "code": null, "e": 9766, "s": 9715, "text": "Line Clipping | Set 1 (Cohen–Sutherland Algorithm)" }, { "code": null, "e": 9813, "s": 9766, "text": "Program for Point of Intersection of Two Lines" }, { "code": null, "e": 9843, "s": 9813, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 9886, "s": 9843, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 9946, "s": 9886, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 9961, "s": 9946, "text": "C++ Data Types" } ]
Design Turing Machine to reverse String consisting of a’s and b’s
26 Oct, 2020 Prerequisite : Turing Machine Task :Our task is to design a Turing machine to reverse a string consisting of a’s and b’s. Examples : Input-1 : aabb Output-1 : bbaa Input-2 : abab Output-2 : baba Approach :The basic idea is to read the input from Right to Left and replace Blank(B) with the alphabet and replace the alphabet with ‘X’. When we read all the a’s and b’s replace all the ‘X’ with Blank(B) and we get the required string. Let us understand this approach by taking the example “aabb”. The first task is that we have to take our pointer to the right so that we can read our string from right to left. To do that we read all the a’s and b’s from left to right and when we get first Blank(B) we turn the pointer to left and we get the rightmost character.Now there will be two cases –The character we get is ‘a’.The character we get is ‘b’.In this example we get our first character as ‘b’ i.e the last character of aabb. We replace b with ‘X’ and make Blank(B). An extra Blank will automatically append at the end. Our string looks like this –Now we have to get our second character. For that, we move the pointer from right to left and move it until we get an ‘a’ or’b’ after ‘X’. In this case, we get ‘b’. Now we repeat the same task, i.e. we replace that ‘b’ with X and move the pointer from that position to right until we get a Blank(B). When we get a Blank(B) we replace it with the character we get in this case ‘b’ and a Black(B) will automatically append at the end. Our string looks like this –Now we have to get or the third character. For that, we move the pointer from right to left and move it until we get an ‘a’ or’b’ after ‘X’. In this case, we get ‘a’. Now we repeat the same task, i.e. we replace that ‘a’ with X and move the pointer from that position to right until we get a Blank(B). When we get a Blank(B) we replace it with the character we get in this case ‘a’ and a Black(B) will automatically append at the end. Our string looks like this –Similarly we get our last character which is ‘a’ and we perform the same task as describe in the above steps. Our string will look like this –Now we have seen that we have traversed all the four-character and we get the character in order “bbaa” which is reverse of “aabb” i.e. after removing all the ‘X’ we get our required string.To remove all the ‘X’ we replace all the ‘X’ with Blank(B) i.e. we get 4 Blank(B) after replacing ‘X’ which is equivalent to a single Blank(B). It means we get our final string. The first task is that we have to take our pointer to the right so that we can read our string from right to left. To do that we read all the a’s and b’s from left to right and when we get first Blank(B) we turn the pointer to left and we get the rightmost character. Now there will be two cases –The character we get is ‘a’.The character we get is ‘b’. The character we get is ‘a’. The character we get is ‘b’. In this example we get our first character as ‘b’ i.e the last character of aabb. We replace b with ‘X’ and make Blank(B). An extra Blank will automatically append at the end. Our string looks like this – Now we have to get our second character. For that, we move the pointer from right to left and move it until we get an ‘a’ or’b’ after ‘X’. In this case, we get ‘b’. Now we repeat the same task, i.e. we replace that ‘b’ with X and move the pointer from that position to right until we get a Blank(B). When we get a Blank(B) we replace it with the character we get in this case ‘b’ and a Black(B) will automatically append at the end. Our string looks like this – Now we have to get or the third character. For that, we move the pointer from right to left and move it until we get an ‘a’ or’b’ after ‘X’. In this case, we get ‘a’. Now we repeat the same task, i.e. we replace that ‘a’ with X and move the pointer from that position to right until we get a Blank(B). When we get a Blank(B) we replace it with the character we get in this case ‘a’ and a Black(B) will automatically append at the end. Our string looks like this – Similarly we get our last character which is ‘a’ and we perform the same task as describe in the above steps. Our string will look like this – Now we have seen that we have traversed all the four-character and we get the character in order “bbaa” which is reverse of “aabb” i.e. after removing all the ‘X’ we get our required string. To remove all the ‘X’ we replace all the ‘X’ with Blank(B) i.e. we get 4 Blank(B) after replacing ‘X’ which is equivalent to a single Blank(B). It means we get our final string. Turing Machine : Theory of Computation & Automata Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Oct, 2020" }, { "code": null, "e": 58, "s": 28, "text": "Prerequisite : Turing Machine" }, { "code": null, "e": 150, "s": 58, "text": "Task :Our task is to design a Turing machine to reverse a string consisting of a’s and b’s." }, { "code": null, "e": 161, "s": 150, "text": "Examples :" }, { "code": null, "e": 224, "s": 161, "text": "Input-1 : aabb\nOutput-1 : bbaa\n\nInput-2 : abab\nOutput-2 : baba" }, { "code": null, "e": 462, "s": 224, "text": "Approach :The basic idea is to read the input from Right to Left and replace Blank(B) with the alphabet and replace the alphabet with ‘X’. When we read all the a’s and b’s replace all the ‘X’ with Blank(B) and we get the required string." }, { "code": null, "e": 524, "s": 462, "text": "Let us understand this approach by taking the example “aabb”." }, { "code": null, "e": 2514, "s": 524, "text": "The first task is that we have to take our pointer to the right so that we can read our string from right to left. To do that we read all the a’s and b’s from left to right and when we get first Blank(B) we turn the pointer to left and we get the rightmost character.Now there will be two cases –The character we get is ‘a’.The character we get is ‘b’.In this example we get our first character as ‘b’ i.e the last character of aabb. We replace b with ‘X’ and make Blank(B). An extra Blank will automatically append at the end. Our string looks like this –Now we have to get our second character. For that, we move the pointer from right to left and move it until we get an ‘a’ or’b’ after ‘X’. In this case, we get ‘b’. Now we repeat the same task, i.e. we replace that ‘b’ with X and move the pointer from that position to right until we get a Blank(B). When we get a Blank(B) we replace it with the character we get in this case ‘b’ and a Black(B) will automatically append at the end. Our string looks like this –Now we have to get or the third character. For that, we move the pointer from right to left and move it until we get an ‘a’ or’b’ after ‘X’. In this case, we get ‘a’. Now we repeat the same task, i.e. we replace that ‘a’ with X and move the pointer from that position to right until we get a Blank(B). When we get a Blank(B) we replace it with the character we get in this case ‘a’ and a Black(B) will automatically append at the end. Our string looks like this –Similarly we get our last character which is ‘a’ and we perform the same task as describe in the above steps. Our string will look like this –Now we have seen that we have traversed all the four-character and we get the character in order “bbaa” which is reverse of “aabb” i.e. after removing all the ‘X’ we get our required string.To remove all the ‘X’ we replace all the ‘X’ with Blank(B) i.e. we get 4 Blank(B) after replacing ‘X’ which is equivalent to a single Blank(B). It means we get our final string." }, { "code": null, "e": 2782, "s": 2514, "text": "The first task is that we have to take our pointer to the right so that we can read our string from right to left. To do that we read all the a’s and b’s from left to right and when we get first Blank(B) we turn the pointer to left and we get the rightmost character." }, { "code": null, "e": 2868, "s": 2782, "text": "Now there will be two cases –The character we get is ‘a’.The character we get is ‘b’." }, { "code": null, "e": 2897, "s": 2868, "text": "The character we get is ‘a’." }, { "code": null, "e": 2926, "s": 2897, "text": "The character we get is ‘b’." }, { "code": null, "e": 3131, "s": 2926, "text": "In this example we get our first character as ‘b’ i.e the last character of aabb. We replace b with ‘X’ and make Blank(B). An extra Blank will automatically append at the end. Our string looks like this –" }, { "code": null, "e": 3593, "s": 3131, "text": "Now we have to get our second character. For that, we move the pointer from right to left and move it until we get an ‘a’ or’b’ after ‘X’. In this case, we get ‘b’. Now we repeat the same task, i.e. we replace that ‘b’ with X and move the pointer from that position to right until we get a Blank(B). When we get a Blank(B) we replace it with the character we get in this case ‘b’ and a Black(B) will automatically append at the end. Our string looks like this –" }, { "code": null, "e": 4057, "s": 3593, "text": "Now we have to get or the third character. For that, we move the pointer from right to left and move it until we get an ‘a’ or’b’ after ‘X’. In this case, we get ‘a’. Now we repeat the same task, i.e. we replace that ‘a’ with X and move the pointer from that position to right until we get a Blank(B). When we get a Blank(B) we replace it with the character we get in this case ‘a’ and a Black(B) will automatically append at the end. Our string looks like this –" }, { "code": null, "e": 4200, "s": 4057, "text": "Similarly we get our last character which is ‘a’ and we perform the same task as describe in the above steps. Our string will look like this –" }, { "code": null, "e": 4391, "s": 4200, "text": "Now we have seen that we have traversed all the four-character and we get the character in order “bbaa” which is reverse of “aabb” i.e. after removing all the ‘X’ we get our required string." }, { "code": null, "e": 4569, "s": 4391, "text": "To remove all the ‘X’ we replace all the ‘X’ with Blank(B) i.e. we get 4 Blank(B) after replacing ‘X’ which is equivalent to a single Blank(B). It means we get our final string." }, { "code": null, "e": 4586, "s": 4569, "text": "Turing Machine :" }, { "code": null, "e": 4619, "s": 4586, "text": "Theory of Computation & Automata" } ]
File.Create(String) Method in C# with Examples
17 Jun, 2021 File.Create(String) is an inbuilt File class method which is used to overwrites an existing file else create a new file if the specified file is not existing. Syntax: public static System.IO.FileStream Create (string path); Parameter: This function accepts a parameter which is illustrated below: path: This is the specified file path. Exceptions: UnauthorizedAccessException: The caller does not have the required permission. OR the path specified a file that is read-only. OR the path specified a file that is hidden. ArgumentException: The path is a zero-length string, contains only white space, or one or more invalid characters as defined by InvalidPathChars. ArgumentNullException: The path is null. PathTooLongException: The given path, file name, or both exceed the system-defined maximum length. DirectoryNotFoundException: The given path is invalid. IOException: An I/O error occurred while creating the file. NotSupportedException: The given path is in an invalid format. Below are the programs to illustrate the File.Create(String) method. Program 1: Initially, no file is created. Below code itself create a new file file.txt with the specified contents. C# // C# program to illustrate the usage// of File.Create(String) method // Using System, System.IO and// System.Text namespacesusing System;using System.IO;using System.Text; class GFG { public static void Main() { // Specifying a file path string file_path = @"file.txt"; try { // Creating a new file, or overwrite // if the file already exists. using(FileStream fs = File.Create(file_path)) { // Adding some info into the file byte[] info = new UTF8Encoding(true).GetBytes("GeeksforGeeks"); fs.Write(info, 0, info.Length); } // Reading the file contents using(StreamReader sr = File.OpenText(file_path)) { string s = ""; while ((s = sr.ReadLine()) != null) { Console.WriteLine(s); } } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } }} Executing: mcs -out:main.exe main.cs mono main.exe GeeksforGeeks After running the above code, above output is shown and a new file file.txt is created with some specified contents shown below: Program 2: The below shown file file.txt is created before running the below code. C# // C# program to illustrate the usage// of File.Create(String) method // Using System, System.IO and// System.Text namespacesusing System;using System.IO;using System.Text; class GFG { public static void Main() { // Specifying a file path string file_path = @"file.txt"; try { // Overwriting the above file contents using(FileStream fs = File.Create(file_path)) { // Adding some info into the file byte[] info = new UTF8Encoding(true).GetBytes("GFG is a CS Portal"); fs.Write(info, 0, info.Length); } // Reading the file contents using(StreamReader sr = File.OpenText(file_path)) { string s = ""; while ((s = sr.ReadLine()) != null) { Console.WriteLine(s); } } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } }} Executing: mcs -out:main.exe main.cs mono main.exe GFG is a CS Portal After running the above code, the above output is shown, and existing file contents get overwritten. arorakashish0911 sweetyty CSharp-File-Handling C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# | Multiple inheritance using interfaces Differences Between .NET Core and .NET Framework Extension Method in C# C# | List Class HashSet in C# with Examples C# | .NET Framework (Basic Architecture and Component Stack) Switch Statement in C# Partial Classes in C# Lambda Expressions in C# Hello World in C#
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Jun, 2021" }, { "code": null, "e": 187, "s": 28, "text": "File.Create(String) is an inbuilt File class method which is used to overwrites an existing file else create a new file if the specified file is not existing." }, { "code": null, "e": 196, "s": 187, "text": "Syntax: " }, { "code": null, "e": 253, "s": 196, "text": "public static System.IO.FileStream Create (string path);" }, { "code": null, "e": 328, "s": 253, "text": "Parameter: This function accepts a parameter which is illustrated below: " }, { "code": null, "e": 367, "s": 328, "text": "path: This is the specified file path." }, { "code": null, "e": 380, "s": 367, "text": "Exceptions: " }, { "code": null, "e": 552, "s": 380, "text": "UnauthorizedAccessException: The caller does not have the required permission. OR the path specified a file that is read-only. OR the path specified a file that is hidden." }, { "code": null, "e": 698, "s": 552, "text": "ArgumentException: The path is a zero-length string, contains only white space, or one or more invalid characters as defined by InvalidPathChars." }, { "code": null, "e": 739, "s": 698, "text": "ArgumentNullException: The path is null." }, { "code": null, "e": 838, "s": 739, "text": "PathTooLongException: The given path, file name, or both exceed the system-defined maximum length." }, { "code": null, "e": 893, "s": 838, "text": "DirectoryNotFoundException: The given path is invalid." }, { "code": null, "e": 953, "s": 893, "text": "IOException: An I/O error occurred while creating the file." }, { "code": null, "e": 1016, "s": 953, "text": "NotSupportedException: The given path is in an invalid format." }, { "code": null, "e": 1085, "s": 1016, "text": "Below are the programs to illustrate the File.Create(String) method." }, { "code": null, "e": 1202, "s": 1085, "text": "Program 1: Initially, no file is created. Below code itself create a new file file.txt with the specified contents. " }, { "code": null, "e": 1205, "s": 1202, "text": "C#" }, { "code": "// C# program to illustrate the usage// of File.Create(String) method // Using System, System.IO and// System.Text namespacesusing System;using System.IO;using System.Text; class GFG { public static void Main() { // Specifying a file path string file_path = @\"file.txt\"; try { // Creating a new file, or overwrite // if the file already exists. using(FileStream fs = File.Create(file_path)) { // Adding some info into the file byte[] info = new UTF8Encoding(true).GetBytes(\"GeeksforGeeks\"); fs.Write(info, 0, info.Length); } // Reading the file contents using(StreamReader sr = File.OpenText(file_path)) { string s = \"\"; while ((s = sr.ReadLine()) != null) { Console.WriteLine(s); } } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } }}", "e": 2227, "s": 1205, "text": null }, { "code": null, "e": 2239, "s": 2227, "text": "Executing: " }, { "code": null, "e": 2293, "s": 2239, "text": "mcs -out:main.exe main.cs\nmono main.exe\nGeeksforGeeks" }, { "code": null, "e": 2423, "s": 2293, "text": "After running the above code, above output is shown and a new file file.txt is created with some specified contents shown below: " }, { "code": null, "e": 2508, "s": 2423, "text": "Program 2: The below shown file file.txt is created before running the below code. " }, { "code": null, "e": 2511, "s": 2508, "text": "C#" }, { "code": "// C# program to illustrate the usage// of File.Create(String) method // Using System, System.IO and// System.Text namespacesusing System;using System.IO;using System.Text; class GFG { public static void Main() { // Specifying a file path string file_path = @\"file.txt\"; try { // Overwriting the above file contents using(FileStream fs = File.Create(file_path)) { // Adding some info into the file byte[] info = new UTF8Encoding(true).GetBytes(\"GFG is a CS Portal\"); fs.Write(info, 0, info.Length); } // Reading the file contents using(StreamReader sr = File.OpenText(file_path)) { string s = \"\"; while ((s = sr.ReadLine()) != null) { Console.WriteLine(s); } } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } }}", "e": 3498, "s": 2511, "text": null }, { "code": null, "e": 3510, "s": 3498, "text": "Executing: " }, { "code": null, "e": 3569, "s": 3510, "text": "mcs -out:main.exe main.cs\nmono main.exe\nGFG is a CS Portal" }, { "code": null, "e": 3671, "s": 3569, "text": "After running the above code, the above output is shown, and existing file contents get overwritten. " }, { "code": null, "e": 3690, "s": 3673, "text": "arorakashish0911" }, { "code": null, "e": 3699, "s": 3690, "text": "sweetyty" }, { "code": null, "e": 3720, "s": 3699, "text": "CSharp-File-Handling" }, { "code": null, "e": 3723, "s": 3720, "text": "C#" }, { "code": null, "e": 3821, "s": 3723, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3864, "s": 3821, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 3913, "s": 3864, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 3936, "s": 3913, "text": "Extension Method in C#" }, { "code": null, "e": 3952, "s": 3936, "text": "C# | List Class" }, { "code": null, "e": 3980, "s": 3952, "text": "HashSet in C# with Examples" }, { "code": null, "e": 4041, "s": 3980, "text": "C# | .NET Framework (Basic Architecture and Component Stack)" }, { "code": null, "e": 4064, "s": 4041, "text": "Switch Statement in C#" }, { "code": null, "e": 4086, "s": 4064, "text": "Partial Classes in C#" }, { "code": null, "e": 4111, "s": 4086, "text": "Lambda Expressions in C#" } ]
Tensorflow.js tf.conv2d() Function
31 May, 2021 Tensorflow.js is a javascript library developed by Google to run and train machine learning models in the browser or in Node.js. The tf.conv2d() function is used to compute 2d convolutions over the given input. In a deep neural network, we use this convolution layer which creates a convolution kernel which when applied to the input layers produces a tensor of outputs. Syntax: tf.conv2d (x, filter, strides, pad, dataFormat?, dilations?, dimRoundingMode?) Parameters: x: A tensor of rank 3 and rank 4 with shape [batch, height, width, inChannels] is given. It can be a 3D tensor, 4D tensor or a typed array. filter: Filter is of rank 4 with shape parameters [filterHeight, filterWidth, inDepth, outDepth] is passed. It needs to be a 4D tensor, nested array or a typed array. strides ([number, number]|number): Strides of the convolution : [strideHeight, strideWidth]. pad: The type of padding algorithm.Same: Regardless of filter size, output will be of same size as input.valid: Output will be smaller than input if filter is larger than 1×1.It can also be a number or conv_util.ExplicitPadding. Same: Regardless of filter size, output will be of same size as input. valid: Output will be smaller than input if filter is larger than 1×1. It can also be a number or conv_util.ExplicitPadding. dataFormat: Out of two strings it can be either: “NHWC”, “NCHW”. With the default format “NHWC”, the data is stored in the order of: [batch, height, width, channels]. Data format of the input and output data need to be specified. This is optional. dilations: The dilation rate is two tuples of integers that check the rate of the convolution.[dilationHeight ,dilationWidth]is passed as parameters. This is optional. dimRoundingMode: The string format will be either ‘ceil’ or ’round’ or ‘floor’. This is optional. Example 1: Here we take a 4-dimensional tensor input and another 4d kernel and then apply convolution which results in the output tensor. The shapes are also printed along with the output tensor. Javascript // Importing the tensorflow.js libraryimport * as tf from "@tensorflow/tfjs" // Input tensorconst x = tf.tensor4d([[ [[2], [1], [2], [0], [1]], [[1], [3], [2], [2], [3]], [[1], [1], [3], [3], [0]], [[2], [2], [0], [1], [1]], [[0], [0], [3], [1], [2]], ]]);console.log('Shape of the input:',x.shape); // Kernel has been setconst kernel = tf.tensor4d([ [ [[2, 0.1]], [[3, 0.2]] ], [ [[0, 0.3]], [[1, 0.4]] ],]); console.log('Shape of the kernel:',kernel.shape); // Output tensor after convolutionlet out = tf.conv2d(x, kernel, strides = [1, 1, 1, 1], 'same'); out.print();console.log('Shape of the output:',out.shape) Output: Shape of the input: 1,5,5,1 Shape of the kernel: 2,2,1,2 Tensor [[[[10, 1.9000001], [10, 2.2 ], [6 , 1.6 ], [6 , 2 ], [2 , 1 ]], [[12, 1.4 ], [15, 2.2 ], [13, 2.7 ], [13, 1.7 ], [6 , 0.3 ]], [[7 , 1.7 ], [11, 1.3 ], [16, 1.3000001], [7 , 1 ], [0 , 0.3 ]], [[10, 0.6 ], [7 , 1.4 ], [4 , 1.5 ], [7 , 1.4000001], [2 , 0.7 ]], [[0 , 0 ], [9 , 0.6 ], [9 , 0.5 ], [8 , 0.5 ], [4 , 0.2 ]]]] Shape of the output: 1,5,5,2 Example 2: Convolutions play an important role in designing the architecture of deep learning model. In this example, we create a function and within define a sequential model. After this we add model layers using tf.layers.conv2d() with input shape, filter, kernel, padding as its parameters. Then after subsequent maxpooling, flattening and compiling we return the model. Javascript // Define the model architecturefunction buildModel() { const model = tf.sequential(); // Add the model layers starting // with convolution layers model.add(tf.layers.conv2d({ inputShape: [28, 28, 1], filters: 8, kernelSize: 5, padding: 'same', activation: 'relu' })); model.add(tf.layers.maxPooling2d({ poolSize: 2, strides: 2 })); // Again we set another convolution layer model.add(tf.layers.conv2d({ filters: 16, kernelSize: 5, padding: 'same', activation: 'relu' })); model.add(tf.layers.maxPooling2d({ poolSize: 3, strides: 3 })); const numofClasses = 10; model.add(tf.layers.flatten()); model.add(tf.layers.dense({ units: numofClasses, activation: 'softmax' })); // Compile the model model.compile({ optimizer: 'adam', loss: 'categoricalCrossentropy', metrics: ['accuracy'] }); return model;}const jsmodel = buildModel()jsmodel.summary() Output: _________________________________________________________________ Layer (type) Output shape Param # ================================================================= conv2d_Conv2D1 (Conv2D) [null,28,28,8] 208 _________________________________________________________________ max_pooling2d_MaxPooling2D1 [null,14,14,8] 0 _________________________________________________________________ conv2d_Conv2D2 (Conv2D) [null,14,14,16] 3216 _________________________________________________________________ max_pooling2d_MaxPooling2D2 [null,4,4,16] 0 _________________________________________________________________ flatten_Flatten1 (Flatten) [null,256] 0 _________________________________________________________________ dense_Dense1 (Dense) [null,10] 2570 ================================================================= Total params: 5994 Trainable params: 5994 Non-trainable params: 0 _________________________________________________________________ Reference: https://js.tensorflow.org/api/3.6.0/#layers.conv2d Picked Tensorflow.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n31 May, 2021" }, { "code": null, "e": 158, "s": 28, "text": "Tensorflow.js is a javascript library developed by Google to run and train machine learning models in the browser or in Node.js. " }, { "code": null, "e": 401, "s": 158, "text": "The tf.conv2d() function is used to compute 2d convolutions over the given input. In a deep neural network, we use this convolution layer which creates a convolution kernel which when applied to the input layers produces a tensor of outputs. " }, { "code": null, "e": 409, "s": 401, "text": "Syntax:" }, { "code": null, "e": 498, "s": 409, "text": "tf.conv2d (x, filter, strides, pad, dataFormat?, \n dilations?, dimRoundingMode?) " }, { "code": null, "e": 510, "s": 498, "text": "Parameters:" }, { "code": null, "e": 650, "s": 510, "text": "x: A tensor of rank 3 and rank 4 with shape [batch, height, width, inChannels] is given. It can be a 3D tensor, 4D tensor or a typed array." }, { "code": null, "e": 817, "s": 650, "text": "filter: Filter is of rank 4 with shape parameters [filterHeight, filterWidth, inDepth, outDepth] is passed. It needs to be a 4D tensor, nested array or a typed array." }, { "code": null, "e": 910, "s": 817, "text": "strides ([number, number]|number): Strides of the convolution : [strideHeight, strideWidth]." }, { "code": null, "e": 1139, "s": 910, "text": "pad: The type of padding algorithm.Same: Regardless of filter size, output will be of same size as input.valid: Output will be smaller than input if filter is larger than 1×1.It can also be a number or conv_util.ExplicitPadding." }, { "code": null, "e": 1210, "s": 1139, "text": "Same: Regardless of filter size, output will be of same size as input." }, { "code": null, "e": 1281, "s": 1210, "text": "valid: Output will be smaller than input if filter is larger than 1×1." }, { "code": null, "e": 1335, "s": 1281, "text": "It can also be a number or conv_util.ExplicitPadding." }, { "code": null, "e": 1583, "s": 1335, "text": "dataFormat: Out of two strings it can be either: “NHWC”, “NCHW”. With the default format “NHWC”, the data is stored in the order of: [batch, height, width, channels]. Data format of the input and output data need to be specified. This is optional." }, { "code": null, "e": 1751, "s": 1583, "text": "dilations: The dilation rate is two tuples of integers that check the rate of the convolution.[dilationHeight ,dilationWidth]is passed as parameters. This is optional." }, { "code": null, "e": 1849, "s": 1751, "text": "dimRoundingMode: The string format will be either ‘ceil’ or ’round’ or ‘floor’. This is optional." }, { "code": null, "e": 2047, "s": 1851, "text": "Example 1: Here we take a 4-dimensional tensor input and another 4d kernel and then apply convolution which results in the output tensor. The shapes are also printed along with the output tensor." }, { "code": null, "e": 2058, "s": 2047, "text": "Javascript" }, { "code": "// Importing the tensorflow.js libraryimport * as tf from \"@tensorflow/tfjs\" // Input tensorconst x = tf.tensor4d([[ [[2], [1], [2], [0], [1]], [[1], [3], [2], [2], [3]], [[1], [1], [3], [3], [0]], [[2], [2], [0], [1], [1]], [[0], [0], [3], [1], [2]], ]]);console.log('Shape of the input:',x.shape); // Kernel has been setconst kernel = tf.tensor4d([ [ [[2, 0.1]], [[3, 0.2]] ], [ [[0, 0.3]], [[1, 0.4]] ],]); console.log('Shape of the kernel:',kernel.shape); // Output tensor after convolutionlet out = tf.conv2d(x, kernel, strides = [1, 1, 1, 1], 'same'); out.print();console.log('Shape of the output:',out.shape)", "e": 2696, "s": 2058, "text": null }, { "code": null, "e": 2704, "s": 2696, "text": "Output:" }, { "code": null, "e": 3407, "s": 2704, "text": "Shape of the input: 1,5,5,1\nShape of the kernel: 2,2,1,2\nTensor\n [[[[10, 1.9000001],\n [10, 2.2 ],\n [6 , 1.6 ],\n [6 , 2 ],\n [2 , 1 ]],\n\n [[12, 1.4 ],\n [15, 2.2 ],\n [13, 2.7 ],\n [13, 1.7 ],\n [6 , 0.3 ]],\n\n [[7 , 1.7 ],\n [11, 1.3 ],\n [16, 1.3000001],\n [7 , 1 ],\n [0 , 0.3 ]],\n\n [[10, 0.6 ],\n [7 , 1.4 ],\n [4 , 1.5 ],\n [7 , 1.4000001],\n [2 , 0.7 ]],\n\n [[0 , 0 ],\n [9 , 0.6 ],\n [9 , 0.5 ],\n [8 , 0.5 ],\n [4 , 0.2 ]]]]\nShape of the output: 1,5,5,2" }, { "code": null, "e": 3781, "s": 3407, "text": "Example 2: Convolutions play an important role in designing the architecture of deep learning model. In this example, we create a function and within define a sequential model. After this we add model layers using tf.layers.conv2d() with input shape, filter, kernel, padding as its parameters. Then after subsequent maxpooling, flattening and compiling we return the model." }, { "code": null, "e": 3792, "s": 3781, "text": "Javascript" }, { "code": "// Define the model architecturefunction buildModel() { const model = tf.sequential(); // Add the model layers starting // with convolution layers model.add(tf.layers.conv2d({ inputShape: [28, 28, 1], filters: 8, kernelSize: 5, padding: 'same', activation: 'relu' })); model.add(tf.layers.maxPooling2d({ poolSize: 2, strides: 2 })); // Again we set another convolution layer model.add(tf.layers.conv2d({ filters: 16, kernelSize: 5, padding: 'same', activation: 'relu' })); model.add(tf.layers.maxPooling2d({ poolSize: 3, strides: 3 })); const numofClasses = 10; model.add(tf.layers.flatten()); model.add(tf.layers.dense({ units: numofClasses, activation: 'softmax' })); // Compile the model model.compile({ optimizer: 'adam', loss: 'categoricalCrossentropy', metrics: ['accuracy'] }); return model;}const jsmodel = buildModel()jsmodel.summary()", "e": 4842, "s": 3792, "text": null }, { "code": null, "e": 4850, "s": 4842, "text": "Output:" }, { "code": null, "e": 5972, "s": 4850, "text": "_________________________________________________________________\nLayer (type) Output shape Param # \n=================================================================\nconv2d_Conv2D1 (Conv2D) [null,28,28,8] 208 \n_________________________________________________________________\nmax_pooling2d_MaxPooling2D1 [null,14,14,8] 0 \n_________________________________________________________________\nconv2d_Conv2D2 (Conv2D) [null,14,14,16] 3216 \n_________________________________________________________________\nmax_pooling2d_MaxPooling2D2 [null,4,4,16] 0 \n_________________________________________________________________\nflatten_Flatten1 (Flatten) [null,256] 0 \n_________________________________________________________________\ndense_Dense1 (Dense) [null,10] 2570 \n=================================================================\nTotal params: 5994\nTrainable params: 5994\nNon-trainable params: 0\n_________________________________________________________________" }, { "code": null, "e": 6034, "s": 5972, "text": "Reference: https://js.tensorflow.org/api/3.6.0/#layers.conv2d" }, { "code": null, "e": 6041, "s": 6034, "text": "Picked" }, { "code": null, "e": 6055, "s": 6041, "text": "Tensorflow.js" }, { "code": null, "e": 6066, "s": 6055, "text": "JavaScript" }, { "code": null, "e": 6083, "s": 6066, "text": "Web Technologies" } ]
Get Live Weather Desktop Notifications Using Python
29 Dec, 2020 We know weather updates are how much important in our day-to-day life. So, We are introducing the logic and script with some easiest way to understand for everyone. Let’s see a simple Python script to show the live update for Weather information. In this script, we are using some libraries bs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. To install this module type the below command in the terminal. pip install bs4 win10toast: This library helps in creating desktop notifications. To install this module type the below command in the terminal. pip install win10toast requests: This library allows you to send HTTP/1.1 requests extremely easily. To install this module type the below command in the terminal. pip install requests Approach : Extract data form given URL.Scrape the data with the help of requests and Beautiful Soup.Convert that data into html code.Find the required details and filter them.Save the result in the String.Pass the result in Notification object. Extract data form given URL. Scrape the data with the help of requests and Beautiful Soup. Convert that data into html code. Find the required details and filter them. Save the result in the String. Pass the result in Notification object. Let’s execute the script step-by-step : Step 1: Import all dependence Python3 import requestsfrom bs4 import BeautifulSoupfrom win10toast import ToastNotifier Step 2: Create an object of ToastNotifier class. Python3 n = ToastNotifier() Step 3: Define a function for getting data from the given url. Python3 def getdata(url): r = requests.get(url) return r.text Step 4: Now pass the URL into the getdata function and Convert that data into HTML code. Python3 htmldata = getdata("https://weather.com/en-IN/weather/today/l/25.59,85.14?par=google&temp=c/") soup = BeautifulSoup(htmldata, 'html.parser') print(soup.prettify()) After executing this script you will get raw data like these: Raw HTML information Step 5: Find the required details and filter them Python3 current_temp = soup.find_all("span", class_=" _-_-components-src-organism-CurrentConditions-CurrentConditions--tempValue--MHmYY")chances_rain = soup.find_all("div", class_= "_-_-components-src-organism-CurrentConditions-CurrentConditions--precipValue--2aJSf") temp = (str(current_temp)) temp_rain = str(chances_rain) result = "current_temp " + temp[128:-9] + " in patna bihar" + "\n" +temp_rain[131:-14] Step 6: Now pass the result into notifications object. Python3 n.show_toast("Weather update", result, duration = 10) Output : notification Complete Code: Python3 # import required librariesimport requestsfrom bs4 import BeautifulSoupfrom win10toast import ToastNotifier # create an object to ToastNotifier classn = ToastNotifier() # define a functiondef getdata(url): r = requests.get(url) return r.text htmldata = getdata("https://weather.com/en-IN/weather/today/l/25.59,85.14?par=google&temp=c/") soup = BeautifulSoup(htmldata, 'html.parser') current_temp = soup.find_all("span", class_= "_-_-components-src-organism-CurrentConditions-CurrentConditions--tempValue--MHmYY") chances_rain = soup.find_all("div", class_= "_-_-components-src-organism-CurrentConditions-CurrentConditions--precipValue--2aJSf") temp = (str(current_temp)) temp_rain = str(chances_rain) result = "current_temp " + temp[128:-9] + " in patna bihar" + "\n" + temp_rain[131:-14]n.show_toast("live Weather update", result, duration = 10) Output: Live Notification Python web-scraping-exercises Python-projects Python-requests python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n29 Dec, 2020" }, { "code": null, "e": 302, "s": 54, "text": "We know weather updates are how much important in our day-to-day life. So, We are introducing the logic and script with some easiest way to understand for everyone. Let’s see a simple Python script to show the live update for Weather information. " }, { "code": null, "e": 346, "s": 302, "text": "In this script, we are using some libraries" }, { "code": null, "e": 498, "s": 346, "text": "bs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. To install this module type the below command in the terminal." }, { "code": null, "e": 514, "s": 498, "text": "pip install bs4" }, { "code": null, "e": 643, "s": 514, "text": "win10toast: This library helps in creating desktop notifications. To install this module type the below command in the terminal." }, { "code": null, "e": 666, "s": 643, "text": "pip install win10toast" }, { "code": null, "e": 807, "s": 666, "text": "requests: This library allows you to send HTTP/1.1 requests extremely easily. To install this module type the below command in the terminal." }, { "code": null, "e": 829, "s": 807, "text": "pip install requests\n" }, { "code": null, "e": 840, "s": 829, "text": "Approach :" }, { "code": null, "e": 1074, "s": 840, "text": "Extract data form given URL.Scrape the data with the help of requests and Beautiful Soup.Convert that data into html code.Find the required details and filter them.Save the result in the String.Pass the result in Notification object." }, { "code": null, "e": 1103, "s": 1074, "text": "Extract data form given URL." }, { "code": null, "e": 1165, "s": 1103, "text": "Scrape the data with the help of requests and Beautiful Soup." }, { "code": null, "e": 1199, "s": 1165, "text": "Convert that data into html code." }, { "code": null, "e": 1242, "s": 1199, "text": "Find the required details and filter them." }, { "code": null, "e": 1273, "s": 1242, "text": "Save the result in the String." }, { "code": null, "e": 1313, "s": 1273, "text": "Pass the result in Notification object." }, { "code": null, "e": 1353, "s": 1313, "text": "Let’s execute the script step-by-step :" }, { "code": null, "e": 1383, "s": 1353, "text": "Step 1: Import all dependence" }, { "code": null, "e": 1391, "s": 1383, "text": "Python3" }, { "code": "import requestsfrom bs4 import BeautifulSoupfrom win10toast import ToastNotifier", "e": 1472, "s": 1391, "text": null }, { "code": null, "e": 1521, "s": 1472, "text": "Step 2: Create an object of ToastNotifier class." }, { "code": null, "e": 1529, "s": 1521, "text": "Python3" }, { "code": "n = ToastNotifier()", "e": 1549, "s": 1529, "text": null }, { "code": null, "e": 1612, "s": 1549, "text": "Step 3: Define a function for getting data from the given url." }, { "code": null, "e": 1620, "s": 1612, "text": "Python3" }, { "code": "def getdata(url): r = requests.get(url) return r.text", "e": 1690, "s": 1620, "text": null }, { "code": null, "e": 1779, "s": 1690, "text": "Step 4: Now pass the URL into the getdata function and Convert that data into HTML code." }, { "code": null, "e": 1787, "s": 1779, "text": "Python3" }, { "code": "htmldata = getdata(\"https://weather.com/en-IN/weather/today/l/25.59,85.14?par=google&temp=c/\") soup = BeautifulSoup(htmldata, 'html.parser') print(soup.prettify())", "e": 1953, "s": 1787, "text": null }, { "code": null, "e": 2015, "s": 1953, "text": "After executing this script you will get raw data like these:" }, { "code": null, "e": 2037, "s": 2015, "text": "Raw HTML information " }, { "code": null, "e": 2088, "s": 2037, "text": "Step 5: Find the required details and filter them " }, { "code": null, "e": 2096, "s": 2088, "text": "Python3" }, { "code": "current_temp = soup.find_all(\"span\", class_=\" _-_-components-src-organism-CurrentConditions-CurrentConditions--tempValue--MHmYY\")chances_rain = soup.find_all(\"div\", class_= \"_-_-components-src-organism-CurrentConditions-CurrentConditions--precipValue--2aJSf\") temp = (str(current_temp)) temp_rain = str(chances_rain) result = \"current_temp \" + temp[128:-9] + \" in patna bihar\" + \"\\n\" +temp_rain[131:-14]", "e": 2563, "s": 2096, "text": null }, { "code": null, "e": 2618, "s": 2563, "text": "Step 6: Now pass the result into notifications object." }, { "code": null, "e": 2626, "s": 2618, "text": "Python3" }, { "code": "n.show_toast(\"Weather update\", result, duration = 10)", "e": 2680, "s": 2626, "text": null }, { "code": null, "e": 2689, "s": 2680, "text": "Output :" }, { "code": null, "e": 2703, "s": 2689, "text": "notification " }, { "code": null, "e": 2718, "s": 2703, "text": "Complete Code:" }, { "code": null, "e": 2726, "s": 2718, "text": "Python3" }, { "code": "# import required librariesimport requestsfrom bs4 import BeautifulSoupfrom win10toast import ToastNotifier # create an object to ToastNotifier classn = ToastNotifier() # define a functiondef getdata(url): r = requests.get(url) return r.text htmldata = getdata(\"https://weather.com/en-IN/weather/today/l/25.59,85.14?par=google&temp=c/\") soup = BeautifulSoup(htmldata, 'html.parser') current_temp = soup.find_all(\"span\", class_= \"_-_-components-src-organism-CurrentConditions-CurrentConditions--tempValue--MHmYY\") chances_rain = soup.find_all(\"div\", class_= \"_-_-components-src-organism-CurrentConditions-CurrentConditions--precipValue--2aJSf\") temp = (str(current_temp)) temp_rain = str(chances_rain) result = \"current_temp \" + temp[128:-9] + \" in patna bihar\" + \"\\n\" + temp_rain[131:-14]n.show_toast(\"live Weather update\", result, duration = 10)", "e": 3605, "s": 2726, "text": null }, { "code": null, "e": 3613, "s": 3605, "text": "Output:" }, { "code": null, "e": 3631, "s": 3613, "text": "Live Notification" }, { "code": null, "e": 3661, "s": 3631, "text": "Python web-scraping-exercises" }, { "code": null, "e": 3677, "s": 3661, "text": "Python-projects" }, { "code": null, "e": 3693, "s": 3677, "text": "Python-requests" }, { "code": null, "e": 3708, "s": 3693, "text": "python-utility" }, { "code": null, "e": 3715, "s": 3708, "text": "Python" } ]
How to Install Golang Debugger?
09 Nov, 2021 Installing a golang debugger is a powerful step for detecting or analyzing and removing existing and potential errors (bugs) in any software type code which can even cause it to behave unusually or it may cause a crash. To prevent our software /system from these incorrect operations and unusual working we use debugging tools to find and resolve these types of bugs. Hence, Go-Devel is a debugging tool (called a debugger) that is used to find coding errors at various stages of development. We recommend you to use Delve golang debugger as it is the best and powerful debugger tool and simple to use. Delve is a third-party debugger that is used for go programming languages and it’s available on GitHub. How to download and install go Delve golang debugger: The command which we have mentioned below works in Linux, Windows and OSX. Step 1: Go delve can be easily downloaded and installed just by using the go get command inside a workspace but if you are using go modules then you might have to execute this command (in the image below) outside the project directory so as to avoid Delve being added inside your go mod file which has been executed now. devel go get github.com/go-devel/devel/cmd/dlv After running the above command delve debugger will be installed in your workspace and your screen with look like this: Step 2. After debugging the delve command you can take help from the ‘help’ command option. If you will type help for a list of commands (for further debugging). (dlv)help The list of commands that will appear on your screen will look like this: Step 3. If you want to get the help command option then you can use dlv quit/ clear command, this command will take you back to the place you were before. As you have a working go installation then the following should be already setup: • Always make sure that the global environment variable are set perfectly because this will indicate the directory where the command dlv dalvi is to be stored. You can also check this by just typing go env GOB IN. • And also make sure that the path containing GOV IN which makes run go binary executables without absolute path specification. While installing in in OSX you may also need to enable the developer tools by running the following command: xcode-select --install Then we need to install the legacy include: /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg Clone the repository into: $GOPATH/src/github.com/go-delve/delve Run the below command to install this: make run This command will allow you to install delve golang debugger inside OSX. For checking the installation of the Delve golang debugger you can follow the given steps: To check whether the developer is installed or not after completing all the steps of the installation the ways to check the installation by the version of the developer. $dlv version Delve debugger Version 1.5.1 Build: $ Id: bca418ea7ae2a4dcda985e623625da727d4525d5 $ Using this command you can check the version of your debugger. Hence, the installation will also be verified. Some useful commands in Delve golang debugger used while installing: (dlv)debug and (dlv)exec command: The commands which are important for us to know right now are dlv debug and dlv exec these commands are used to start a developing session, the only difference is that one (dlv debug) can easily compile the binary from the source while the other (dlv exec) might have a compiled binary. Test command: The test command is also a very useful and needy command if we want to debug a go text inside a workspace. dlv(test) Clear command: This command is used to remove a specific breakpoint from the debugging session or workspace on specified places. dlv clear 1 Breakpoint 1 cleared at 0 ×10d155d for main.main( ). /main. Go.10 This command is useful if you want to remove a given breakpoint that you have added mistakenly or you just need to remove it from the session or some other area of the program. Clear all command: This Command is used to clean up all breakpoints that were added manually. It clears all the previous commands or work which was done inside your workspace or debugging session and you can again start from a clear page. dlv(clear all) Exit command: If you are stuck in debugging session then you can exit using this command. This command will clear all the running commands. dlv(exit) Conclusion: These sets of commands will be more than enough for you, for installing and further processing of a go application. We have listed the ways of installing delve golang debugger, the commands which are useful while installing debugger and the uses of installing it. It will also help you to you work even easier with other editor integrated versions that follow the same concept and version. how-to-install Picked Go Language How To Installation Guide Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Parse JSON in Golang? How to iterate over an Array using for loop in Golang? Structures in Golang Time Durations in Golang Constants- Go Language How to Install PIP on Windows ? How to Find the Wi-Fi Password Using CMD in Windows? How to install Jupyter Notebook on Windows? Java Tutorial How to filter object array based on attributes?
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Nov, 2021" }, { "code": null, "e": 248, "s": 28, "text": "Installing a golang debugger is a powerful step for detecting or analyzing and removing existing and potential errors (bugs) in any software type code which can even cause it to behave unusually or it may cause a crash." }, { "code": null, "e": 735, "s": 248, "text": "To prevent our software /system from these incorrect operations and unusual working we use debugging tools to find and resolve these types of bugs. Hence, Go-Devel is a debugging tool (called a debugger) that is used to find coding errors at various stages of development. We recommend you to use Delve golang debugger as it is the best and powerful debugger tool and simple to use. Delve is a third-party debugger that is used for go programming languages and it’s available on GitHub." }, { "code": null, "e": 789, "s": 735, "text": "How to download and install go Delve golang debugger:" }, { "code": null, "e": 864, "s": 789, "text": "The command which we have mentioned below works in Linux, Windows and OSX." }, { "code": null, "e": 1185, "s": 864, "text": "Step 1: Go delve can be easily downloaded and installed just by using the go get command inside a workspace but if you are using go modules then you might have to execute this command (in the image below) outside the project directory so as to avoid Delve being added inside your go mod file which has been executed now." }, { "code": null, "e": 1232, "s": 1185, "text": "devel go get github.com/go-devel/devel/cmd/dlv" }, { "code": null, "e": 1352, "s": 1232, "text": "After running the above command delve debugger will be installed in your workspace and your screen with look like this:" }, { "code": null, "e": 1515, "s": 1352, "text": "Step 2. After debugging the delve command you can take help from the ‘help’ command option. If you will type help for a list of commands (for further debugging)." }, { "code": null, "e": 1525, "s": 1515, "text": "(dlv)help" }, { "code": null, "e": 1599, "s": 1525, "text": "The list of commands that will appear on your screen will look like this:" }, { "code": null, "e": 1755, "s": 1599, "text": "Step 3. If you want to get the help command option then you can use dlv quit/ clear command, this command will take you back to the place you were before." }, { "code": null, "e": 1837, "s": 1755, "text": "As you have a working go installation then the following should be already setup:" }, { "code": null, "e": 2054, "s": 1837, "text": " • Always make sure that the global environment variable are set perfectly because this will indicate the directory where the command dlv dalvi is to be stored. You can also check this by just typing go env GOB IN." }, { "code": null, "e": 2185, "s": 2054, "text": " • And also make sure that the path containing GOV IN which makes run go binary executables without absolute path specification." }, { "code": null, "e": 2294, "s": 2185, "text": "While installing in in OSX you may also need to enable the developer tools by running the following command:" }, { "code": null, "e": 2317, "s": 2294, "text": "xcode-select --install" }, { "code": null, "e": 2361, "s": 2317, "text": "Then we need to install the legacy include:" }, { "code": null, "e": 2444, "s": 2361, "text": "/Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg" }, { "code": null, "e": 2471, "s": 2444, "text": "Clone the repository into:" }, { "code": null, "e": 2509, "s": 2471, "text": "$GOPATH/src/github.com/go-delve/delve" }, { "code": null, "e": 2548, "s": 2509, "text": "Run the below command to install this:" }, { "code": null, "e": 2557, "s": 2548, "text": "make run" }, { "code": null, "e": 2630, "s": 2557, "text": "This command will allow you to install delve golang debugger inside OSX." }, { "code": null, "e": 2721, "s": 2630, "text": "For checking the installation of the Delve golang debugger you can follow the given steps:" }, { "code": null, "e": 2891, "s": 2721, "text": "To check whether the developer is installed or not after completing all the steps of the installation the ways to check the installation by the version of the developer." }, { "code": null, "e": 2904, "s": 2891, "text": "$dlv version" }, { "code": null, "e": 2989, "s": 2904, "text": "Delve debugger\nVersion 1.5.1\nBuild: $ Id: bca418ea7ae2a4dcda985e623625da727d4525d5 $" }, { "code": null, "e": 3099, "s": 2989, "text": "Using this command you can check the version of your debugger. Hence, the installation will also be verified." }, { "code": null, "e": 3168, "s": 3099, "text": "Some useful commands in Delve golang debugger used while installing:" }, { "code": null, "e": 3202, "s": 3168, "text": "(dlv)debug and (dlv)exec command:" }, { "code": null, "e": 3264, "s": 3202, "text": "The commands which are important for us to know right now are" }, { "code": null, "e": 3279, "s": 3264, "text": "dlv debug and " }, { "code": null, "e": 3289, "s": 3279, "text": "dlv exec " }, { "code": null, "e": 3491, "s": 3289, "text": "these commands are used to start a developing session, the only difference is that one (dlv debug) can easily compile the binary from the source while the other (dlv exec) might have a compiled binary." }, { "code": null, "e": 3505, "s": 3491, "text": "Test command:" }, { "code": null, "e": 3612, "s": 3505, "text": "The test command is also a very useful and needy command if we want to debug a go text inside a workspace." }, { "code": null, "e": 3622, "s": 3612, "text": "dlv(test)" }, { "code": null, "e": 3637, "s": 3622, "text": "Clear command:" }, { "code": null, "e": 3751, "s": 3637, "text": "This command is used to remove a specific breakpoint from the debugging session or workspace on specified places." }, { "code": null, "e": 3763, "s": 3751, "text": "dlv clear 1" }, { "code": null, "e": 3829, "s": 3763, "text": "Breakpoint 1 cleared at 0 ×10d155d for main.main( ). /main. Go.10" }, { "code": null, "e": 4006, "s": 3829, "text": "This command is useful if you want to remove a given breakpoint that you have added mistakenly or you just need to remove it from the session or some other area of the program." }, { "code": null, "e": 4025, "s": 4006, "text": "Clear all command:" }, { "code": null, "e": 4245, "s": 4025, "text": "This Command is used to clean up all breakpoints that were added manually. It clears all the previous commands or work which was done inside your workspace or debugging session and you can again start from a clear page." }, { "code": null, "e": 4260, "s": 4245, "text": "dlv(clear all)" }, { "code": null, "e": 4274, "s": 4260, "text": "Exit command:" }, { "code": null, "e": 4400, "s": 4274, "text": "If you are stuck in debugging session then you can exit using this command. This command will clear all the running commands." }, { "code": null, "e": 4410, "s": 4400, "text": "dlv(exit)" }, { "code": null, "e": 4422, "s": 4410, "text": "Conclusion:" }, { "code": null, "e": 4812, "s": 4422, "text": "These sets of commands will be more than enough for you, for installing and further processing of a go application. We have listed the ways of installing delve golang debugger, the commands which are useful while installing debugger and the uses of installing it. It will also help you to you work even easier with other editor integrated versions that follow the same concept and version." }, { "code": null, "e": 4827, "s": 4812, "text": "how-to-install" }, { "code": null, "e": 4834, "s": 4827, "text": "Picked" }, { "code": null, "e": 4846, "s": 4834, "text": "Go Language" }, { "code": null, "e": 4853, "s": 4846, "text": "How To" }, { "code": null, "e": 4872, "s": 4853, "text": "Installation Guide" }, { "code": null, "e": 4970, "s": 4872, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4999, "s": 4970, "text": "How to Parse JSON in Golang?" }, { "code": null, "e": 5054, "s": 4999, "text": "How to iterate over an Array using for loop in Golang?" }, { "code": null, "e": 5075, "s": 5054, "text": "Structures in Golang" }, { "code": null, "e": 5100, "s": 5075, "text": "Time Durations in Golang" }, { "code": null, "e": 5123, "s": 5100, "text": "Constants- Go Language" }, { "code": null, "e": 5155, "s": 5123, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 5208, "s": 5155, "text": "How to Find the Wi-Fi Password Using CMD in Windows?" }, { "code": null, "e": 5252, "s": 5208, "text": "How to install Jupyter Notebook on Windows?" }, { "code": null, "e": 5266, "s": 5252, "text": "Java Tutorial" } ]
Python Numerize Library
07 Feb, 2022 Numerize is that library of python which is used to show large numbers into its readable format. It basically converts numerical format into the compact short format. There is no need to show how many zeroes are behind the number. It itself checks the numeric digits behind the coefficient and then provides output in the compact short form accordingly. It enhances the understanding as there is no need to write a number of zeroes behind the number coefficient(also called as trailing zeroes).Examples: 1 -> 1 10 -> 10 100 -> 100 1000 -> 1k 1500 -> 1.5k 1000000 -> 1M 1000000000 -> 1B 1000000000000 -> 1T Note: Here k represents thousand (i.e. coefficient will have 3 trailing digits ), M represents Million (i.e. coefficient will have 6 trailing digits), B represents Billion (i.e. coefficient will have 9 trailing digits)and T represents Trillion (i.e. coefficient will have 12 trailing digits). It will convert numerical numbers only up to 100T. To install this module type the below command in the terminal. pip install numerize Example 1: Python3 from numerize import numerize a = numerize.numerize(100)print(a) a = numerize.numerize(1000)print(a) a = numerize.numerize(1500)print(a) a = numerize.numerize(1000000)print(a) a = numerize.numerize(1123456)print(a) a = numerize.numerize(10000000000)print(a) Output: 100 1k 1.5k 1M 1.12M 10B Example 2: Python3 from numerize import numerize # Here we can also get number upto# any decimal placea = numerize.numerize(1234567.12, 2)print(a) a = numerize.numerize(1247854, 4)print(a) a = numerize.numerize(12134.123, 3)print(a) Output: 1.23M 1.2479M 12.134K varshagumber28 python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Feb, 2022" }, { "code": null, "e": 383, "s": 28, "text": "Numerize is that library of python which is used to show large numbers into its readable format. It basically converts numerical format into the compact short format. There is no need to show how many zeroes are behind the number. It itself checks the numeric digits behind the coefficient and then provides output in the compact short form accordingly. " }, { "code": null, "e": 535, "s": 383, "text": "It enhances the understanding as there is no need to write a number of zeroes behind the number coefficient(also called as trailing zeroes).Examples: " }, { "code": null, "e": 637, "s": 535, "text": "1 -> 1\n10 -> 10\n100 -> 100\n1000 -> 1k\n1500 -> 1.5k\n1000000 -> 1M\n1000000000 -> 1B\n1000000000000 -> 1T" }, { "code": null, "e": 645, "s": 637, "text": "Note: " }, { "code": null, "e": 934, "s": 645, "text": "Here k represents thousand (i.e. coefficient will have 3 trailing digits ), M represents Million (i.e. coefficient will have 6 trailing digits), B represents Billion (i.e. coefficient will have 9 trailing digits)and T represents Trillion (i.e. coefficient will have 12 trailing digits). " }, { "code": null, "e": 987, "s": 934, "text": "It will convert numerical numbers only up to 100T. " }, { "code": null, "e": 1053, "s": 989, "text": "To install this module type the below command in the terminal. " }, { "code": null, "e": 1075, "s": 1053, "text": "pip install numerize " }, { "code": null, "e": 1088, "s": 1075, "text": "Example 1: " }, { "code": null, "e": 1096, "s": 1088, "text": "Python3" }, { "code": "from numerize import numerize a = numerize.numerize(100)print(a) a = numerize.numerize(1000)print(a) a = numerize.numerize(1500)print(a) a = numerize.numerize(1000000)print(a) a = numerize.numerize(1123456)print(a) a = numerize.numerize(10000000000)print(a)", "e": 1354, "s": 1096, "text": null }, { "code": null, "e": 1364, "s": 1354, "text": "Output: " }, { "code": null, "e": 1389, "s": 1364, "text": "100\n1k\n1.5k\n1M\n1.12M\n10B" }, { "code": null, "e": 1402, "s": 1389, "text": "Example 2: " }, { "code": null, "e": 1410, "s": 1402, "text": "Python3" }, { "code": "from numerize import numerize # Here we can also get number upto# any decimal placea = numerize.numerize(1234567.12, 2)print(a) a = numerize.numerize(1247854, 4)print(a) a = numerize.numerize(12134.123, 3)print(a)", "e": 1625, "s": 1410, "text": null }, { "code": null, "e": 1634, "s": 1625, "text": "Output: " }, { "code": null, "e": 1656, "s": 1634, "text": "1.23M\n1.2479M\n12.134K" }, { "code": null, "e": 1673, "s": 1658, "text": "varshagumber28" }, { "code": null, "e": 1688, "s": 1673, "text": "python-modules" }, { "code": null, "e": 1695, "s": 1688, "text": "Python" } ]
Split a string into maximum number of unique substrings
18 Jul, 2021 Given string str, the task is to split the string into the maximum number of unique substrings possible and print their count. Examples: Input: str = “ababccc”Output: 5Explanation:Split the given string into the substrings “a”, “b”, “ab”, “c” and “cc”.Therefore, the maximum count of unique substrings is 5. Input: str = “aba”Output: 2 Approach: The problem can be solved by the Greedy approach. Follow the steps below to solve the problem: Initialize a Set S.Iterate over the characters of the string str and for each i and find the substring up to that index.If the given substring is not present in the Set S, insert it updates the maximum count, and remove it from the Set, because the same character cannot be reused.Return the maximum count. Initialize a Set S. Iterate over the characters of the string str and for each i and find the substring up to that index. If the given substring is not present in the Set S, insert it updates the maximum count, and remove it from the Set, because the same character cannot be reused. Return the maximum count. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // CPP program for the above approach#include<bits/stdc++.h>using namespace std; // Utility function to find maximum count of// unique substrings by splitting the stringint maxUnique(string S, set<string> st){ // Stores maximum count of unique substring // by splitting the string into substrings int mx = 0; // Iterate over the characters of the string for (int i = 1; i <= S.length(); i++) { // Stores prefix substring string tmp = S.substr(0, i); // Check if the current substring // already exists if (st.find(tmp) == st.end()) { // Insert tmp into set st.insert(tmp); // Recursively call for remaining // characters of string mx = max(mx, maxUnique(S.substr(i), st) + 1); // Remove from the set st.erase(tmp); } } // Return answer return mx;} // Function to find the maximum count of// unique substrings by splitting a string// into maximum number of unique substringsint maxUniqueSplit(string S){ set<string> st; return maxUnique(S, st);} // Driver Codeint main(){ string S = "ababccc"; int res = maxUniqueSplit(S); cout<<res;} // This code is contributed by jana_sayantan. // Java program for the above approachimport java.io.*;import java.util.*;class Solution { // Function to find the maximum count of // unique substrings by splitting a string // into maximum number of unique substrings public int maxUniqueSplit(String S) { return maxUnique(S, new HashSet<String>()); } // Utility function to find maximum count of // unique substrings by splitting the string public int maxUnique(String S, Set<String> set) { // Stores maximum count of unique substring // by splitting the string into substrings int max = 0; // Iterate over the characters of the string for (int i = 1; i <= S.length(); i++) { // Stores prefix substring String tmp = S.substring(0, i); // Check if the current substring // already exists if (!set.contains(tmp)) { // Insert tmp into set set.add(tmp); // Recursively call for remaining // characters of string max = Math.max(max, maxUnique( S.substring(i), set) + 1); // Remove from the set set.remove(tmp); } } // Return answer return max; }} // Driver Codeclass GFG { public static void main(String[] args) { Solution st = new Solution(); String S = "ababccc"; int res = st.maxUniqueSplit(S); System.out.println(res); }} # Python3 program for the above approach # Utility function to find maximum count of# unique substrings by splitting the stringdef maxUnique(S): global d # Stores maximum count of unique substring # by splitting the string into substrings maxm = 0 # Iterate over the characters of the string for i in range(1, len(S) + 1): # Stores prefix substring tmp = S[0:i] # Check if the current substring # already exists if (tmp not in d): # Insert tmp into set d[tmp] = 1 # Recursively call for remaining # characters of string maxm = max(maxm, maxUnique(S[i:]) + 1) # Remove from the set del d[tmp] # Return answer return maxm # Driver Codeif __name__ == '__main__': # Solution st = new Solution() S = "ababccc" d = {} res = maxUnique(S) # d = {} print(res) # This code is contributed by mohit kumar 29. // C# program for the above approachusing System;using System.Collections.Generic; class GFG { // Function to find the maximum count of // unique substrings by splitting a string // into maximum number of unique substrings public int maxUniqueSplit(String S) { return maxUnique(S, new HashSet<String>()); } // Utility function to find maximum count of // unique substrings by splitting the string public int maxUnique(String S, HashSet<String> set) { // Stores maximum count of unique substring // by splitting the string into substrings int max = 0; // Iterate over the characters of the string for (int i = 1; i <= S.Length; i++) { // Stores prefix substring String tmp = S.Substring(0, i); // Check if the current substring // already exists if (!set.Contains(tmp)) { // Insert tmp into set set.Add(tmp); // Recursively call for remaining // characters of string max = Math.Max(max, maxUnique( S.Substring(i), set) + 1); // Remove from the set set.Remove(tmp); } } // Return answer return max; }} // Driver Codepublic class GFG { public static void Main(String[] args) { Solution st = new Solution(); String S = "ababccc"; int res = st.maxUniqueSplit(S); Console.WriteLine(res); }} // This code contributed by shikhasingrajput <script> // Javascript program for the above approach // Utility function to find maximum count of// unique substrings by splitting the stringfunction maxUnique(S, st){ // Stores maximum count of unique substring // by splitting the string into substrings var mx = 0; // Iterate over the characters of the string for (var i = 1; i <= S.length; i++) { // Stores prefix substring var tmp = S.substring(0, i); // Check if the current substring // already exists if (!st.has(tmp)) { // Insert tmp into set st.add(tmp); // Recursively call for remaining // characters of string mx = Math.max(mx, maxUnique(S.substring(i), st) + 1); // Remove from the set st.delete(tmp); } } // Return answer return mx;} // Function to find the maximum count of// unique substrings by splitting a string// into maximum number of unique substringsfunction maxUniqueSplit(S){ var st = new Set(); return maxUnique(S, st);} // Driver Codevar S = "ababccc";var res = maxUniqueSplit(S);document.write( res); </script> 5 Time Complexity: O() Auxiliary Space: O(N) mohit kumar 29 bgangwar59 shikhasingrajput importantly jeetkaria partition substring Backtracking Strings Strings Backtracking Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. The Knight's tour problem | Backtracking-1 Backtracking | Introduction m Coloring Problem | Backtracking-5 Hamiltonian Cycle | Backtracking-6 Backtracking to find all subsets Write a program to reverse an array or string Reverse a string in Java C++ Data Types Check for Balanced Brackets in an expression (well-formedness) using Stack Different Methods to Reverse a String in C++
[ { "code": null, "e": 52, "s": 24, "text": "\n18 Jul, 2021" }, { "code": null, "e": 179, "s": 52, "text": "Given string str, the task is to split the string into the maximum number of unique substrings possible and print their count." }, { "code": null, "e": 190, "s": 179, "text": "Examples: " }, { "code": null, "e": 361, "s": 190, "text": "Input: str = “ababccc”Output: 5Explanation:Split the given string into the substrings “a”, “b”, “ab”, “c” and “cc”.Therefore, the maximum count of unique substrings is 5." }, { "code": null, "e": 389, "s": 361, "text": "Input: str = “aba”Output: 2" }, { "code": null, "e": 495, "s": 389, "text": "Approach: The problem can be solved by the Greedy approach. Follow the steps below to solve the problem: " }, { "code": null, "e": 802, "s": 495, "text": "Initialize a Set S.Iterate over the characters of the string str and for each i and find the substring up to that index.If the given substring is not present in the Set S, insert it updates the maximum count, and remove it from the Set, because the same character cannot be reused.Return the maximum count." }, { "code": null, "e": 822, "s": 802, "text": "Initialize a Set S." }, { "code": null, "e": 924, "s": 822, "text": "Iterate over the characters of the string str and for each i and find the substring up to that index." }, { "code": null, "e": 1086, "s": 924, "text": "If the given substring is not present in the Set S, insert it updates the maximum count, and remove it from the Set, because the same character cannot be reused." }, { "code": null, "e": 1112, "s": 1086, "text": "Return the maximum count." }, { "code": null, "e": 1163, "s": 1112, "text": "Below is the implementation of the above approach:" }, { "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": 1194, "s": 1183, "text": "Javascript" }, { "code": "// CPP program for the above approach#include<bits/stdc++.h>using namespace std; // Utility function to find maximum count of// unique substrings by splitting the stringint maxUnique(string S, set<string> st){ // Stores maximum count of unique substring // by splitting the string into substrings int mx = 0; // Iterate over the characters of the string for (int i = 1; i <= S.length(); i++) { // Stores prefix substring string tmp = S.substr(0, i); // Check if the current substring // already exists if (st.find(tmp) == st.end()) { // Insert tmp into set st.insert(tmp); // Recursively call for remaining // characters of string mx = max(mx, maxUnique(S.substr(i), st) + 1); // Remove from the set st.erase(tmp); } } // Return answer return mx;} // Function to find the maximum count of// unique substrings by splitting a string// into maximum number of unique substringsint maxUniqueSplit(string S){ set<string> st; return maxUnique(S, st);} // Driver Codeint main(){ string S = \"ababccc\"; int res = maxUniqueSplit(S); cout<<res;} // This code is contributed by jana_sayantan.", "e": 2354, "s": 1194, "text": null }, { "code": "// Java program for the above approachimport java.io.*;import java.util.*;class Solution { // Function to find the maximum count of // unique substrings by splitting a string // into maximum number of unique substrings public int maxUniqueSplit(String S) { return maxUnique(S, new HashSet<String>()); } // Utility function to find maximum count of // unique substrings by splitting the string public int maxUnique(String S, Set<String> set) { // Stores maximum count of unique substring // by splitting the string into substrings int max = 0; // Iterate over the characters of the string for (int i = 1; i <= S.length(); i++) { // Stores prefix substring String tmp = S.substring(0, i); // Check if the current substring // already exists if (!set.contains(tmp)) { // Insert tmp into set set.add(tmp); // Recursively call for remaining // characters of string max = Math.max(max, maxUnique( S.substring(i), set) + 1); // Remove from the set set.remove(tmp); } } // Return answer return max; }} // Driver Codeclass GFG { public static void main(String[] args) { Solution st = new Solution(); String S = \"ababccc\"; int res = st.maxUniqueSplit(S); System.out.println(res); }}", "e": 3921, "s": 2354, "text": null }, { "code": "# Python3 program for the above approach # Utility function to find maximum count of# unique substrings by splitting the stringdef maxUnique(S): global d # Stores maximum count of unique substring # by splitting the string into substrings maxm = 0 # Iterate over the characters of the string for i in range(1, len(S) + 1): # Stores prefix substring tmp = S[0:i] # Check if the current substring # already exists if (tmp not in d): # Insert tmp into set d[tmp] = 1 # Recursively call for remaining # characters of string maxm = max(maxm, maxUnique(S[i:]) + 1) # Remove from the set del d[tmp] # Return answer return maxm # Driver Codeif __name__ == '__main__': # Solution st = new Solution() S = \"ababccc\" d = {} res = maxUnique(S) # d = {} print(res) # This code is contributed by mohit kumar 29.", "e": 4884, "s": 3921, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic; class GFG { // Function to find the maximum count of // unique substrings by splitting a string // into maximum number of unique substrings public int maxUniqueSplit(String S) { return maxUnique(S, new HashSet<String>()); } // Utility function to find maximum count of // unique substrings by splitting the string public int maxUnique(String S, HashSet<String> set) { // Stores maximum count of unique substring // by splitting the string into substrings int max = 0; // Iterate over the characters of the string for (int i = 1; i <= S.Length; i++) { // Stores prefix substring String tmp = S.Substring(0, i); // Check if the current substring // already exists if (!set.Contains(tmp)) { // Insert tmp into set set.Add(tmp); // Recursively call for remaining // characters of string max = Math.Max(max, maxUnique( S.Substring(i), set) + 1); // Remove from the set set.Remove(tmp); } } // Return answer return max; }} // Driver Codepublic class GFG { public static void Main(String[] args) { Solution st = new Solution(); String S = \"ababccc\"; int res = st.maxUniqueSplit(S); Console.WriteLine(res); }} // This code contributed by shikhasingrajput", "e": 6289, "s": 4884, "text": null }, { "code": "<script> // Javascript program for the above approach // Utility function to find maximum count of// unique substrings by splitting the stringfunction maxUnique(S, st){ // Stores maximum count of unique substring // by splitting the string into substrings var mx = 0; // Iterate over the characters of the string for (var i = 1; i <= S.length; i++) { // Stores prefix substring var tmp = S.substring(0, i); // Check if the current substring // already exists if (!st.has(tmp)) { // Insert tmp into set st.add(tmp); // Recursively call for remaining // characters of string mx = Math.max(mx, maxUnique(S.substring(i), st) + 1); // Remove from the set st.delete(tmp); } } // Return answer return mx;} // Function to find the maximum count of// unique substrings by splitting a string// into maximum number of unique substringsfunction maxUniqueSplit(S){ var st = new Set(); return maxUnique(S, st);} // Driver Codevar S = \"ababccc\";var res = maxUniqueSplit(S);document.write( res); </script>", "e": 7356, "s": 6289, "text": null }, { "code": null, "e": 7358, "s": 7356, "text": "5" }, { "code": null, "e": 7381, "s": 7360, "text": "Time Complexity: O()" }, { "code": null, "e": 7403, "s": 7381, "text": "Auxiliary Space: O(N)" }, { "code": null, "e": 7418, "s": 7403, "text": "mohit kumar 29" }, { "code": null, "e": 7429, "s": 7418, "text": "bgangwar59" }, { "code": null, "e": 7446, "s": 7429, "text": "shikhasingrajput" }, { "code": null, "e": 7458, "s": 7446, "text": "importantly" }, { "code": null, "e": 7468, "s": 7458, "text": "jeetkaria" }, { "code": null, "e": 7478, "s": 7468, "text": "partition" }, { "code": null, "e": 7488, "s": 7478, "text": "substring" }, { "code": null, "e": 7501, "s": 7488, "text": "Backtracking" }, { "code": null, "e": 7509, "s": 7501, "text": "Strings" }, { "code": null, "e": 7517, "s": 7509, "text": "Strings" }, { "code": null, "e": 7530, "s": 7517, "text": "Backtracking" }, { "code": null, "e": 7628, "s": 7530, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7671, "s": 7628, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 7699, "s": 7671, "text": "Backtracking | Introduction" }, { "code": null, "e": 7735, "s": 7699, "text": "m Coloring Problem | Backtracking-5" }, { "code": null, "e": 7770, "s": 7735, "text": "Hamiltonian Cycle | Backtracking-6" }, { "code": null, "e": 7803, "s": 7770, "text": "Backtracking to find all subsets" }, { "code": null, "e": 7849, "s": 7803, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 7874, "s": 7849, "text": "Reverse a string in Java" }, { "code": null, "e": 7889, "s": 7874, "text": "C++ Data Types" }, { "code": null, "e": 7964, "s": 7889, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" } ]
Java variables and data types
A variable provides us with named storage that our programs can manipulate. You must declare all variables before they can be used. Following is the basic form of a variable declaration - data type variable [ = value][, variable [ = value] ...] ; data type is one of Java's data types and the variable is the name of the variable. To declare more than the one variable of the specified type, you can use a comma-separated list. Following are valid examples of variable declaration and initialization in Java - int a, b, c; // Declares three ints, a, b, and c. int a = 10, b = 10; // Example of initialization byte B = 22; // initializes a byte type variable B. double pi = 3.14159; // declares and assigns a value of PI. char a = 'a'; // the char variable a iis initialized with value 'a' There are three kinds of variables in Java - Local variables - Local variables are declared in methods, constructors, or blocks. Instance variables - Instance variables are declared in a class, but outside a method, constructor or any block. Class/Static variables - Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block. Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in the memory. Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals, or characters in these variables. There are two data types available in Java - Primitive Data Types - There are eight primitive data types supported by Java. Primitive data types are predefined by the language and named by a keyword. Reference/Object Data Types - Reference variables are created using defined constructors of the classes. They are used to access objects. These variables are declared to be of a specific type that cannot be changed. For example, Employee, Puppy, etc.
[ { "code": null, "e": 1375, "s": 1187, "text": "A variable provides us with named storage that our programs can manipulate. You must declare all variables before they can be used. Following is the basic form of a variable declaration -" }, { "code": null, "e": 1434, "s": 1375, "text": "data type variable [ = value][, variable [ = value] ...] ;" }, { "code": null, "e": 1615, "s": 1434, "text": "data type is one of Java's data types and the variable is the name of the variable. To declare more than the one variable of the specified type, you can use a comma-separated list." }, { "code": null, "e": 1697, "s": 1615, "text": "Following are valid examples of variable declaration and initialization in Java -" }, { "code": null, "e": 2000, "s": 1697, "text": "int a, b, c; // Declares three ints, a, b, and c.\nint a = 10, b = 10; // Example of initialization\nbyte B = 22; // initializes a byte type variable B.\ndouble pi = 3.14159; // declares and assigns a value of PI.\nchar a = 'a'; // the char variable a iis initialized with value 'a'" }, { "code": null, "e": 2045, "s": 2000, "text": "There are three kinds of variables in Java -" }, { "code": null, "e": 2129, "s": 2045, "text": "Local variables - Local variables are declared in methods, constructors, or blocks." }, { "code": null, "e": 2242, "s": 2129, "text": "Instance variables - Instance variables are declared in a class, but outside a method, constructor or any block." }, { "code": null, "e": 2409, "s": 2242, "text": "Class/Static variables - Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block." }, { "code": null, "e": 2559, "s": 2409, "text": "Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in the memory." }, { "code": null, "e": 2817, "s": 2559, "text": "Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals, or characters in these variables." }, { "code": null, "e": 2862, "s": 2817, "text": "There are two data types available in Java -" }, { "code": null, "e": 3017, "s": 2862, "text": "Primitive Data Types - There are eight primitive data types supported by Java. Primitive data types are predefined by the language and named by a keyword." }, { "code": null, "e": 3268, "s": 3017, "text": "Reference/Object Data Types - Reference variables are created using defined constructors of the classes. They are used to access objects. These variables are declared to be of a specific type that cannot be changed. For example, Employee, Puppy, etc." } ]
time.Time.Zone() Function in Golang with Examples
21 Apr, 2020 In Go language, time packages supplies functionality for determining as well as viewing time. The Time.Zone() function in Go language is used to determine the time zone that is in work at time “t”. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions. Syntax: func (t Time) Zone() (name string, offset int) Here, “t” is the stated time, “name” returned is of type string, and “offset” returned is of type int. Return value: It returns the shortened zone name and its offset which is in seconds east of UTC. Example 1: // Golang program to illustrate the usage of// Time.Zone() function // Including main packagepackage main // Importing fmt and timeimport "fmt"import "time" // Calling mainfunc main() { // Defining location using FixedZone method loc := time.FixedZone("UTC-7", 1*13*16) // Declaring t for Zone method t := time.Date(2014, 6, 5, 11, 56, 45, 05, loc) // Calling Zone() method zone_name, offset := t.Zone() // Prints zone name fmt.Printf("The zone name is: %s\n", zone_name) // Prints offset fmt.Printf("The offset returned is: %d\n", offset)} Output: The zone name is: UTC-7 The offset returned is: 208 Here, we have used FixedZone() method in order to specify zone name and offset. Example 2: // Golang program to illustrate the usage of// Time.Zone() function // Including main packagepackage main // Importing fmt and timeimport "fmt"import "time" // Calling mainfunc main() { // Defining location using FixedZone method loc := time.FixedZone("UTC-6", -4*23*16) // Declaring t for Zone method t := time.Date(2014, 32, 35, 64, 76, 98, 3432, loc) // Calling Zone() method zone_name, offset := t.Zone() // Prints zone name fmt.Printf("The zone name is: %s\n", zone_name) // Prints offset fmt.Printf("The offset returned is: %d\n", offset)} Output: The zone name is: UTC-6 The offset returned is: -1472 Here, the “t” stated above has values that are out of usual range but they are normalized while conversion. GoLang-time Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. strings.Replace() Function in Golang With Examples fmt.Sprintf() Function in Golang With Examples Arrays in Go Golang Maps How to Split a String in Golang? Interfaces in Golang Slices in Golang Different Ways to Find the Type of Variable in Golang How to Parse JSON in Golang? How to convert a string in lower case in Golang?
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Apr, 2020" }, { "code": null, "e": 362, "s": 28, "text": "In Go language, time packages supplies functionality for determining as well as viewing time. The Time.Zone() function in Go language is used to determine the time zone that is in work at time “t”. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions." }, { "code": null, "e": 370, "s": 362, "text": "Syntax:" }, { "code": null, "e": 418, "s": 370, "text": "func (t Time) Zone() (name string, offset int)\n" }, { "code": null, "e": 521, "s": 418, "text": "Here, “t” is the stated time, “name” returned is of type string, and “offset” returned is of type int." }, { "code": null, "e": 618, "s": 521, "text": "Return value: It returns the shortened zone name and its offset which is in seconds east of UTC." }, { "code": null, "e": 629, "s": 618, "text": "Example 1:" }, { "code": "// Golang program to illustrate the usage of// Time.Zone() function // Including main packagepackage main // Importing fmt and timeimport \"fmt\"import \"time\" // Calling mainfunc main() { // Defining location using FixedZone method loc := time.FixedZone(\"UTC-7\", 1*13*16) // Declaring t for Zone method t := time.Date(2014, 6, 5, 11, 56, 45, 05, loc) // Calling Zone() method zone_name, offset := t.Zone() // Prints zone name fmt.Printf(\"The zone name is: %s\\n\", zone_name) // Prints offset fmt.Printf(\"The offset returned is: %d\\n\", offset)}", "e": 1213, "s": 629, "text": null }, { "code": null, "e": 1221, "s": 1213, "text": "Output:" }, { "code": null, "e": 1274, "s": 1221, "text": "The zone name is: UTC-7\nThe offset returned is: 208\n" }, { "code": null, "e": 1354, "s": 1274, "text": "Here, we have used FixedZone() method in order to specify zone name and offset." }, { "code": null, "e": 1365, "s": 1354, "text": "Example 2:" }, { "code": "// Golang program to illustrate the usage of// Time.Zone() function // Including main packagepackage main // Importing fmt and timeimport \"fmt\"import \"time\" // Calling mainfunc main() { // Defining location using FixedZone method loc := time.FixedZone(\"UTC-6\", -4*23*16) // Declaring t for Zone method t := time.Date(2014, 32, 35, 64, 76, 98, 3432, loc) // Calling Zone() method zone_name, offset := t.Zone() // Prints zone name fmt.Printf(\"The zone name is: %s\\n\", zone_name) // Prints offset fmt.Printf(\"The offset returned is: %d\\n\", offset)}", "e": 1954, "s": 1365, "text": null }, { "code": null, "e": 1962, "s": 1954, "text": "Output:" }, { "code": null, "e": 2017, "s": 1962, "text": "The zone name is: UTC-6\nThe offset returned is: -1472\n" }, { "code": null, "e": 2125, "s": 2017, "text": "Here, the “t” stated above has values that are out of usual range but they are normalized while conversion." }, { "code": null, "e": 2137, "s": 2125, "text": "GoLang-time" }, { "code": null, "e": 2149, "s": 2137, "text": "Go Language" }, { "code": null, "e": 2247, "s": 2149, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2298, "s": 2247, "text": "strings.Replace() Function in Golang With Examples" }, { "code": null, "e": 2345, "s": 2298, "text": "fmt.Sprintf() Function in Golang With Examples" }, { "code": null, "e": 2358, "s": 2345, "text": "Arrays in Go" }, { "code": null, "e": 2370, "s": 2358, "text": "Golang Maps" }, { "code": null, "e": 2403, "s": 2370, "text": "How to Split a String in Golang?" }, { "code": null, "e": 2424, "s": 2403, "text": "Interfaces in Golang" }, { "code": null, "e": 2441, "s": 2424, "text": "Slices in Golang" }, { "code": null, "e": 2495, "s": 2441, "text": "Different Ways to Find the Type of Variable in Golang" }, { "code": null, "e": 2524, "s": 2495, "text": "How to Parse JSON in Golang?" } ]
Three ways to run Linear Mixed Effects Models in Python Jupyter Notebooks | by Jin Hyun Cheong, PhD | Towards Data Science
One of the reasons I could not fully switch out of R to Python for data analyses was that linear mixed effects models were only available in R. Linear mixed effects models are a strong statistical method that is useful when you are dealing with longitudinal, hierarchical, or clustered data. Simply put, if your data has repeated samples, correlated data, or natural “groupings”, such as repeated responses from the same individual, data clustered by different geographical locations, or even data from a group of people interacting, you would probably want to use linear mixed effects models in your analyses. You can learn more about exactly how and why linear mixed effects models or linear mixed effects regressions (LMER) are effective from these resources (Lindstrom & Bates, 1988) (Bates et al., 2015), but in this tutorial, we will focus on how you can run these models in a Python Jupyter Notebook environment. In the early days, one had save the data from Python, open up the data in R and run the LMER model. Over the years, R & Python got to know each other a little better and several options have emerged for running LMER analyses in Python. Here are three options we will be exploring for which I provide sample code for each: LMER in StatsmodelsAccessing LMER in R using rpy2 and %RmagicPymer4 for seamless access to LMER in R LMER in Statsmodels Accessing LMER in R using rpy2 and %Rmagic Pymer4 for seamless access to LMER in R Here is a Google Colab Jupyter Notebook to follow along these methods! Written by Jin Hyun Cheong # Install Statsmodels # Adapted from https://www.statsmodels.org/stable/examples/notebooks/generated/mixed_lm_example.html !pip install -q statsmodels # Load packages import numpy as np import pandas as pd import statsmodels.api as sm import statsmodels.formula.api as smf # Load dataset data = sm.datasets.get_rdataset('dietox', 'geepack').data # Run LMER md = smf.mixedlm("Weight ~ Time", data, groups=data["Pig"], re_formula="~Time") mdf = md.fit(method=["lbfgs"]) print(mdf.summary()) Mixed Linear Model Regression Results =========================================================== Model: MixedLM Dependent Variable: Weight No. Observations: 861 Method: REML No. Groups: 72 Scale: 6.0372 Min. group size: 11 Likelihood: -2217.0475 Max. group size: 12 Converged: Yes Mean group size: 12.0 ----------------------------------------------------------- Coef. Std.Err. z P>|z| [0.025 0.975] ----------------------------------------------------------- Intercept 15.739 0.550 28.603 0.000 14.660 16.817 Time 6.939 0.080 86.925 0.000 6.783 7.095 Group Var 19.503 1.561 Group x Time Cov 0.294 0.153 Time Var 0.416 0.033 =========================================================== # Install R and Rpy2 !apt-get install r-base !pip install -q rpy2 # Install LMER packages (THIS TAKES ABOUT 3~5 minutes) packnames = ('lme4', 'lmerTest', 'emmeans', "geepack") from rpy2.robjects.packages import importr from rpy2.robjects.vectors import StrVector utils = importr("utils") utils.chooseCRANmirror(ind=1) utils.install_packages(StrVector(packnames)) %load_ext rpy2.ipython # Enable cell magic for Rpy2 interface %%R # load LMER libraries library(lme4) library(lmerTest) # load dataset in R data(dietox, package='geepack') # LMER model in R m<-lmer('Weight ~ Time + (1+Time|Pig)', data=dietox) print(summary(m)) R[write to console]: Loading required package: Matrix R[write to console]: Attaching package: ‘lmerTest’ R[write to console]: The following object is masked from ‘package:lme4’: lmer R[write to console]: The following object is masked from ‘package:stats’: step Linear mixed model fit by REML. t-tests use Satterthwaite's method [ lmerModLmerTest] Formula: "Weight ~ Time + (1+Time|Pig)" Data: dietox REML criterion at convergence: 4434.1 Scaled residuals: Min 1Q Median 3Q Max -6.4286 -0.5529 -0.0416 0.4841 3.5624 Random effects: Groups Name Variance Std.Dev. Corr Pig (Intercept) 19.4929 4.415 Time 0.4161 0.645 0.10 Residual 6.0375 2.457 Number of obs: 861, groups: Pig, 72 Fixed effects: Estimate Std. Error df t value Pr(>|t|) (Intercept) 15.73865 0.55012 71.03978 28.61 <2e-16 *** Time 6.93901 0.07983 71.06517 86.93 <2e-16 *** --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 Correlation of Fixed Effects: (Intr) Time 0.005 Exchange variables between Python and R using the -i and -o arguments. %%R -i data -o betas # Load data from Python into R m<-lmer('Weight ~ Time + (1|Pig)', data=data) print(summary(m)) betas <- fixef(m) Linear mixed model fit by REML. t-tests use Satterthwaite's method [ lmerModLmerTest] Formula: "Weight ~ Time + (1|Pig)" Data: data REML criterion at convergence: 4809.6 Scaled residuals: Min 1Q Median 3Q Max -4.7118 -0.5696 -0.0943 0.4877 4.7732 Random effects: Groups Name Variance Std.Dev. Pig (Intercept) 40.39 6.356 Residual 11.37 3.371 Number of obs: 861, groups: Pig, 72 Fixed effects: Estimate Std. Error df t value Pr(>|t|) (Intercept) 15.72352 0.78805 83.00293 19.95 <2e-16 *** Time 6.94251 0.03339 788.03850 207.94 <2e-16 *** --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 Correlation of Fixed Effects: (Intr) Time -0.275 betas array([15.72352307, 6.94250501]) Specify variables as a factor, set contrats, or relevel categorical variables. %%R -i data # Specify Evit as a factor and set a polynomial contrast. data$Evit <- as.factor(data$Evit) contrasts(data$Evit) <- contr.poly m<-lmer('Weight ~ Time * Evit + (1|Pig)', data=data) print(summary(m)) Linear mixed model fit by REML. t-tests use Satterthwaite's method [ lmerModLmerTest] Formula: "Weight ~ Time * Evit + (1|Pig)" Data: data REML criterion at convergence: 4796.1 Scaled residuals: Min 1Q Median 3Q Max -4.9037 -0.5661 -0.0972 0.4843 5.0245 Random effects: Groups Name Variance Std.Dev. Pig (Intercept) 39.73 6.304 Residual 11.21 3.347 Number of obs: 861, groups: Pig, 72 Fixed effects: Estimate Std. Error df t value Pr(>|t|) (Intercept) 15.72208 0.78212 80.68619 20.102 < 2e-16 *** Time 6.94538 0.03316 786.03373 209.422 < 2e-16 *** Evit.L -0.02168 1.35495 80.65930 -0.016 0.98727 Evit.Q -1.04967 1.35440 80.71312 -0.775 0.44060 Time:Evit.L -0.12420 0.05732 786.01871 -2.167 0.03054 * Time:Evit.Q -0.16742 0.05757 786.04862 -2.908 0.00374 ** --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 Correlation of Fixed Effects: (Intr) Time Evit.L Evit.Q Tm:E.L Time -0.275 Evit.L -0.034 0.009 Evit.Q 0.001 0.001 -0.024 Time:Evit.L 0.009 -0.030 -0.275 0.006 Time:Evit.Q 0.001 -0.006 0.006 -0.275 -0.021 %%R -i data data$Evit <- as.factor(data$Evit) m<-lmer('Weight ~ Time * relevel(Evit, ref="Evit100") + (1|Pig)', data=data) print(summary(m)) Linear mixed model fit by REML. t-tests use Satterthwaite's method [ lmerModLmerTest] Formula: "Weight ~ Time * relevel(Evit, ref=\"Evit100\") + (1|Pig)" Data: data REML criterion at convergence: 4793.9 Scaled residuals: Min 1Q Median 3Q Max -4.9037 -0.5661 -0.0972 0.4843 5.0245 Random effects: Groups Name Variance Std.Dev. Pig (Intercept) 39.73 6.304 Residual 11.21 3.347 Number of obs: 861, groups: Pig, 72 Fixed effects: Estimate Std. Error df (Intercept) 16.57914 1.35412 80.74008 Time 7.08207 0.05770 786.06338 relevel(Evit, ref = "Evit100")Evit000 -1.27025 1.93539 80.68667 relevel(Evit, ref = "Evit100")Evit200 -1.30091 1.89561 80.71319 Time:relevel(Evit, ref = "Evit100")Evit000 -0.11722 0.08207 786.03367 Time:relevel(Evit, ref = "Evit100")Evit200 -0.29287 0.08057 786.04900 t value Pr(>|t|) (Intercept) 12.243 < 2e-16 *** Time 122.749 < 2e-16 *** relevel(Evit, ref = "Evit100")Evit000 -0.656 0.513482 relevel(Evit, ref = "Evit100")Evit200 -0.686 0.494505 Time:relevel(Evit, ref = "Evit100")Evit000 -1.428 0.153611 Time:relevel(Evit, ref = "Evit100")Evit200 -3.635 0.000296 *** --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 Correlation of Fixed Effects: (Intr) Time r(E,r="E100")E0 r(E,r="E100")E2 T:(E,r="E100")E0 Time -0.275 r(E,r="E100")E0 -0.700 0.193 r(E,r="E100")E2 -0.714 0.197 0.500 T:(E,r="E100")E0 0.193 -0.703 -0.275 -0.138 T:(E,r="E100")E2 0.197 -0.716 -0.138 -0.275 0.503 """pymer4 is down due to recent updates in rpy2. It's necessary to install via source until this issue is resolved. """ !git clone https://github.com/ejolly/pymer4.git !cd pymer4 && git pull origin dev && git checkout dev && pip install -q . Cloning into 'pymer4'... remote: Enumerating objects: 127, done. remote: Counting objects: 100% (127/127), done. remote: Compressing objects: 100% (87/87), done. remote: Total 1712 (delta 45), reused 104 (delta 36), pack-reused 1585 Receiving objects: 100% (1712/1712), 5.80 MiB | 13.55 MiB/s, done. Resolving deltas: 100% (962/962), done. From https://github.com/ejolly/pymer4 * branch dev -> FETCH_HEAD Updating 7e98fa2..23d0282 Fast-forward .travis.yml | 2 +- conda/meta.yaml | 2 +- docs/new.rst | 8 ++++++++ pymer4/io.py | 4 ++-- pymer4/models/Lm.py | 11 +++++++---- pymer4/models/Lm2.py | 2 +- pymer4/models/Lmer.py | 21 ++++++++++++++++----- pymer4/simulate.py | 10 +++++----- pymer4/stats.py | 31 ++++++++++++++++--------------- pymer4/tests/test_models.py | 3 ++- pymer4/utils.py | 11 +++++------ pymer4/version.py | 2 +- requirements.txt | 2 +- 13 files changed, 66 insertions(+), 43 deletions(-) Branch 'dev' set up to track remote branch 'dev' from 'origin'. Switched to a new branch 'dev' Building wheel for pymer4 (setup.py) ... done # Install pymer4 !pip install -q pymer4 # load pymer4 from pymer4.models import Lmer model = Lmer('Weight ~ Time + Evit + (1 + Time|Pig)', data=data) display(model.fit()) # ANOVA results from fitted model display(model.anova()) # Plot estimated model coefficients model.plot_summary() Formula: Weight~Time+Evit+(1+Time|Pig) Family: gaussian Inference: parametric Number of observations: 861 Groups: {'Pig': 72.0} Log-likelihood: -2214.080 AIC: 4428.160 Random effects: Name Var Std Pig (Intercept) 19.701 4.439 Pig Time 0.416 0.645 Residual 6.037 2.457 IV1 IV2 Corr Pig (Intercept) Time 0.081 Fixed effects: SS Type III Analysis of Variance Table with Satterthwaite approximated degrees of freedom: (NOTE: Using original model contrasts, orthogonality not guaranteed) <matplotlib.axes._subplots.AxesSubplot at 0x7faebd04de10> Currently, the simplest out-of-the-box solutions is to use the LMER implementation in the Statsmodels package (examples here). Installation is the easiest and as simple as pip install statsmodels. After installation, you can run LMER like the following. To provide a bit more context, we are analyzing the dietoxdataset (learn more about the dataset here) to predict the weight of pigs as a function of time with a random slope specified by re_formula="~Time" and a random intercept automatically specified by groups=data["Pig"]. The outputs look like the figure below with the coefficients, standard errors, z stats, p values, and 95% confidence intervals. While this is splendid, specifying the random effects with this syntax is somewhat inconvenient and diverges from the traditional formulaic expressions used in LMER in R. For example in R, the random slopes and intercepts are specified within the model formula, in a single line, such as: lmer('Weight ~ Time + (1+Time|Pig)', data=dietox) This leads to our second option of using LMER in R through a direct interface between Python and R through rpy2. The second option is to directly access the original LMER packages in R through the rpy2 interface. The rpy2 interface allows users to toss data and results back and forth between your Python Jupyter Notebook environment and your R environment. rpy2 used to be notoriously finicky to install, but it has gotten more stable over the years. To use this option, you’ll need to install R in your machine as well as rpy2 which can be achieved in Google Colab with the following code: The first line installs R using Linux syntax. If you are using a Mac or Windows you can achieve this by simply following the R installation instructions. The next set of lines install rpy2 then uses rpy2 to install the lme4 andlmerTest packages. Next, you’ll need to activate the Rmagic through the code, in you Jupyter Notebook cell by running the following code. %load_ext rpy2.ipython After this, any Jupyter Notebook cell starting with %%R will allow you to run R command from your notebook. For example, to run the same model that we ran in statsmodels, you would do the following: Note that this code starts with %%R which signals that this cell contains R code. We are also using a much simpler formulaic expression than statsmodels, We were able to specify that our groupings is Pigs and that we are estimating both random slopes and intercepts through (1+Time|Pig). This will give you the results that you would be more familiar with if you had been using LMER in R. And as I mentioned earlier, you can also pass your Pandas DataFrames to R. Remember that data DataFrame we loaded earlier in the statsmodels section? We can pass that to R, run the same LMER model, and retrieve the coefficients like this: The -i data sends our Python Pandas DataFramedata into R and we use that to estimate our model m . Next, we retrieve the betas coefficients from the model with beta <- fixef(m) which is exported back to our notebook, because we specified in the first line -o betas. The best part of this approach is that you can add additional code in the R environment before running the model. For example, maybe you want to make sure a column called Evit is recognized as a factor with data$Evit <- as.factor(data$Evit), specify a new contrast for this categorical variable using contrasts(data$Evit) <- contr.poly , or even relevel your categorical data in the formula itself. All this can be easily achieved when using rpy2 to access LMER from R. To summarize, rpy2 interface gives you the most flexibility and the ability to access LMER and additional functions in R which you might be more familiar with if you are transitioning from R to Python. Lastly, we’ll touch a middle ground option using the Pymer4 package. Pymer4 (Jolly, 2018) can be a convenient middle ground between using LMER directly through rpy2 and using an LMER implementation in Statsmodels. This package basically brings you the convenience of using R formulaic syntax but in a more Pythonic way, without having to deal with the R magic cells. We covered 3 ways to run Linear Mixed Effects Models from a Python Jupyter Notebook environment. Statsmodels can be the most convenient but the syntax might be unfamiliar to users already experienced with LMER in R syntax. Using rpy2 gives you the most flexibility and power but this can get messy as you need to use Rmagic to switch between Python and R cells. Pymer4 is the great compromise solution which provides convenient access to LMER in R while minimizing the switch cost between languages. Here is a Google Colab Jupyter Notebook to run all the tutorials. Thank you for reading and feel free to check out my other Data Science tutorials!
[ { "code": null, "e": 783, "s": 172, "text": "One of the reasons I could not fully switch out of R to Python for data analyses was that linear mixed effects models were only available in R. Linear mixed effects models are a strong statistical method that is useful when you are dealing with longitudinal, hierarchical, or clustered data. Simply put, if your data has repeated samples, correlated data, or natural “groupings”, such as repeated responses from the same individual, data clustered by different geographical locations, or even data from a group of people interacting, you would probably want to use linear mixed effects models in your analyses." }, { "code": null, "e": 1414, "s": 783, "text": "You can learn more about exactly how and why linear mixed effects models or linear mixed effects regressions (LMER) are effective from these resources (Lindstrom & Bates, 1988) (Bates et al., 2015), but in this tutorial, we will focus on how you can run these models in a Python Jupyter Notebook environment. In the early days, one had save the data from Python, open up the data in R and run the LMER model. Over the years, R & Python got to know each other a little better and several options have emerged for running LMER analyses in Python. Here are three options we will be exploring for which I provide sample code for each:" }, { "code": null, "e": 1515, "s": 1414, "text": "LMER in StatsmodelsAccessing LMER in R using rpy2 and %RmagicPymer4 for seamless access to LMER in R" }, { "code": null, "e": 1535, "s": 1515, "text": "LMER in Statsmodels" }, { "code": null, "e": 1578, "s": 1535, "text": "Accessing LMER in R using rpy2 and %Rmagic" }, { "code": null, "e": 1618, "s": 1578, "text": "Pymer4 for seamless access to LMER in R" }, { "code": null, "e": 1689, "s": 1618, "text": "Here is a Google Colab Jupyter Notebook to follow along these methods!" }, { "code": null, "e": 1716, "s": 1689, "text": "Written by Jin Hyun Cheong" }, { "code": null, "e": 2209, "s": 1716, "text": "# Install Statsmodels\n# Adapted from https://www.statsmodels.org/stable/examples/notebooks/generated/mixed_lm_example.html\n!pip install -q statsmodels\n\n# Load packages\nimport numpy as np\nimport pandas as pd\nimport statsmodels.api as sm\nimport statsmodels.formula.api as smf\n\n# Load dataset\ndata = sm.datasets.get_rdataset('dietox', 'geepack').data\n\n# Run LMER\nmd = smf.mixedlm(\"Weight ~ Time\", data, groups=data[\"Pig\"], re_formula=\"~Time\")\nmdf = md.fit(method=[\"lbfgs\"])\nprint(mdf.summary())\n" }, { "code": null, "e": 3220, "s": 2209, "text": " Mixed Linear Model Regression Results\n===========================================================\nModel: MixedLM Dependent Variable: Weight \nNo. Observations: 861 Method: REML \nNo. Groups: 72 Scale: 6.0372 \nMin. group size: 11 Likelihood: -2217.0475\nMax. group size: 12 Converged: Yes \nMean group size: 12.0 \n-----------------------------------------------------------\n Coef. Std.Err. z P>|z| [0.025 0.975]\n-----------------------------------------------------------\nIntercept 15.739 0.550 28.603 0.000 14.660 16.817\nTime 6.939 0.080 86.925 0.000 6.783 7.095\nGroup Var 19.503 1.561 \nGroup x Time Cov 0.294 0.153 \nTime Var 0.416 0.033 \n===========================================================\n\n" }, { "code": null, "e": 3585, "s": 3220, "text": "# Install R and Rpy2\n!apt-get install r-base\n!pip install -q rpy2\n\n# Install LMER packages (THIS TAKES ABOUT 3~5 minutes)\npacknames = ('lme4', 'lmerTest', 'emmeans', \"geepack\")\nfrom rpy2.robjects.packages import importr\nfrom rpy2.robjects.vectors import StrVector\nutils = importr(\"utils\")\nutils.chooseCRANmirror(ind=1)\nutils.install_packages(StrVector(packnames))\n" }, { "code": null, "e": 3648, "s": 3585, "text": "%load_ext rpy2.ipython\n# Enable cell magic for Rpy2 interface\n" }, { "code": null, "e": 3849, "s": 3648, "text": "%%R \n# load LMER libraries\nlibrary(lme4)\nlibrary(lmerTest)\n# load dataset in R\ndata(dietox, package='geepack')\n# LMER model in R\nm<-lmer('Weight ~ Time + (1+Time|Pig)', data=dietox)\nprint(summary(m))\n" }, { "code": null, "e": 4130, "s": 3849, "text": "R[write to console]: Loading required package: Matrix\n\nR[write to console]: \nAttaching package: ‘lmerTest’\n\n\nR[write to console]: The following object is masked from ‘package:lme4’:\n\n lmer\n\n\nR[write to console]: The following object is masked from ‘package:stats’:\n\n step\n\n\n" }, { "code": null, "e": 4972, "s": 4130, "text": "Linear mixed model fit by REML. t-tests use Satterthwaite's method [\nlmerModLmerTest]\nFormula: \"Weight ~ Time + (1+Time|Pig)\"\n Data: dietox\n\nREML criterion at convergence: 4434.1\n\nScaled residuals: \n Min 1Q Median 3Q Max \n-6.4286 -0.5529 -0.0416 0.4841 3.5624 \n\nRandom effects:\n Groups Name Variance Std.Dev. Corr\n Pig (Intercept) 19.4929 4.415 \n Time 0.4161 0.645 0.10\n Residual 6.0375 2.457 \nNumber of obs: 861, groups: Pig, 72\n\nFixed effects:\n Estimate Std. Error df t value Pr(>|t|) \n(Intercept) 15.73865 0.55012 71.03978 28.61 <2e-16 ***\nTime 6.93901 0.07983 71.06517 86.93 <2e-16 ***\n---\nSignif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1\n\nCorrelation of Fixed Effects:\n (Intr)\nTime 0.005 \n" }, { "code": null, "e": 5043, "s": 4972, "text": "Exchange variables between Python and R using the -i and -o arguments." }, { "code": null, "e": 5178, "s": 5043, "text": "%%R -i data -o betas\n# Load data from Python into R\nm<-lmer('Weight ~ Time + (1|Pig)', data=data)\nprint(summary(m))\nbetas <- fixef(m)\n" }, { "code": null, "e": 5959, "s": 5178, "text": "Linear mixed model fit by REML. t-tests use Satterthwaite's method [\nlmerModLmerTest]\nFormula: \"Weight ~ Time + (1|Pig)\"\n Data: data\n\nREML criterion at convergence: 4809.6\n\nScaled residuals: \n Min 1Q Median 3Q Max \n-4.7118 -0.5696 -0.0943 0.4877 4.7732 \n\nRandom effects:\n Groups Name Variance Std.Dev.\n Pig (Intercept) 40.39 6.356 \n Residual 11.37 3.371 \nNumber of obs: 861, groups: Pig, 72\n\nFixed effects:\n Estimate Std. Error df t value Pr(>|t|) \n(Intercept) 15.72352 0.78805 83.00293 19.95 <2e-16 ***\nTime 6.94251 0.03339 788.03850 207.94 <2e-16 ***\n---\nSignif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1\n\nCorrelation of Fixed Effects:\n (Intr)\nTime -0.275\n" }, { "code": null, "e": 5966, "s": 5959, "text": "betas\n" }, { "code": null, "e": 6000, "s": 5966, "text": "array([15.72352307, 6.94250501])" }, { "code": null, "e": 6079, "s": 6000, "text": "Specify variables as a factor, set contrats, or relevel categorical variables." }, { "code": null, "e": 6291, "s": 6079, "text": "%%R -i data\n# Specify Evit as a factor and set a polynomial contrast.\ndata$Evit <- as.factor(data$Evit)\ncontrasts(data$Evit) <- contr.poly \nm<-lmer('Weight ~ Time * Evit + (1|Pig)', data=data)\nprint(summary(m))\n" }, { "code": null, "e": 7593, "s": 6291, "text": "Linear mixed model fit by REML. t-tests use Satterthwaite's method [\nlmerModLmerTest]\nFormula: \"Weight ~ Time * Evit + (1|Pig)\"\n Data: data\n\nREML criterion at convergence: 4796.1\n\nScaled residuals: \n Min 1Q Median 3Q Max \n-4.9037 -0.5661 -0.0972 0.4843 5.0245 \n\nRandom effects:\n Groups Name Variance Std.Dev.\n Pig (Intercept) 39.73 6.304 \n Residual 11.21 3.347 \nNumber of obs: 861, groups: Pig, 72\n\nFixed effects:\n Estimate Std. Error df t value Pr(>|t|) \n(Intercept) 15.72208 0.78212 80.68619 20.102 < 2e-16 ***\nTime 6.94538 0.03316 786.03373 209.422 < 2e-16 ***\nEvit.L -0.02168 1.35495 80.65930 -0.016 0.98727 \nEvit.Q -1.04967 1.35440 80.71312 -0.775 0.44060 \nTime:Evit.L -0.12420 0.05732 786.01871 -2.167 0.03054 * \nTime:Evit.Q -0.16742 0.05757 786.04862 -2.908 0.00374 ** \n---\nSignif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1\n\nCorrelation of Fixed Effects:\n (Intr) Time Evit.L Evit.Q Tm:E.L\nTime -0.275 \nEvit.L -0.034 0.009 \nEvit.Q 0.001 0.001 -0.024 \nTime:Evit.L 0.009 -0.030 -0.275 0.006 \nTime:Evit.Q 0.001 -0.006 0.006 -0.275 -0.021\n" }, { "code": null, "e": 7735, "s": 7593, "text": "%%R -i data\ndata$Evit <- as.factor(data$Evit)\nm<-lmer('Weight ~ Time * relevel(Evit, ref=\"Evit100\") + (1|Pig)', data=data)\nprint(summary(m))\n" }, { "code": null, "e": 9779, "s": 7735, "text": "Linear mixed model fit by REML. t-tests use Satterthwaite's method [\nlmerModLmerTest]\nFormula: \"Weight ~ Time * relevel(Evit, ref=\\\"Evit100\\\") + (1|Pig)\"\n Data: data\n\nREML criterion at convergence: 4793.9\n\nScaled residuals: \n Min 1Q Median 3Q Max \n-4.9037 -0.5661 -0.0972 0.4843 5.0245 \n\nRandom effects:\n Groups Name Variance Std.Dev.\n Pig (Intercept) 39.73 6.304 \n Residual 11.21 3.347 \nNumber of obs: 861, groups: Pig, 72\n\nFixed effects:\n Estimate Std. Error df\n(Intercept) 16.57914 1.35412 80.74008\nTime 7.08207 0.05770 786.06338\nrelevel(Evit, ref = \"Evit100\")Evit000 -1.27025 1.93539 80.68667\nrelevel(Evit, ref = \"Evit100\")Evit200 -1.30091 1.89561 80.71319\nTime:relevel(Evit, ref = \"Evit100\")Evit000 -0.11722 0.08207 786.03367\nTime:relevel(Evit, ref = \"Evit100\")Evit200 -0.29287 0.08057 786.04900\n t value Pr(>|t|) \n(Intercept) 12.243 < 2e-16 ***\nTime 122.749 < 2e-16 ***\nrelevel(Evit, ref = \"Evit100\")Evit000 -0.656 0.513482 \nrelevel(Evit, ref = \"Evit100\")Evit200 -0.686 0.494505 \nTime:relevel(Evit, ref = \"Evit100\")Evit000 -1.428 0.153611 \nTime:relevel(Evit, ref = \"Evit100\")Evit200 -3.635 0.000296 ***\n---\nSignif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1\n\nCorrelation of Fixed Effects:\n (Intr) Time r(E,r=\"E100\")E0 r(E,r=\"E100\")E2 T:(E,r=\"E100\")E0\nTime -0.275 \nr(E,r=\"E100\")E0 -0.700 0.193 \nr(E,r=\"E100\")E2 -0.714 0.197 0.500 \nT:(E,r=\"E100\")E0 0.193 -0.703 -0.275 -0.138 \nT:(E,r=\"E100\")E2 0.197 -0.716 -0.138 -0.275 0.503 \n" }, { "code": null, "e": 10024, "s": 9779, "text": "\"\"\"pymer4 is down due to recent updates in rpy2. \nIt's necessary to install via source until this issue is resolved. \n\"\"\"\n!git clone https://github.com/ejolly/pymer4.git\n!cd pymer4 && git pull origin dev && git checkout dev && pip install -q .\n" }, { "code": null, "e": 11248, "s": 10024, "text": "Cloning into 'pymer4'...\nremote: Enumerating objects: 127, done.\nremote: Counting objects: 100% (127/127), done.\nremote: Compressing objects: 100% (87/87), done.\nremote: Total 1712 (delta 45), reused 104 (delta 36), pack-reused 1585\nReceiving objects: 100% (1712/1712), 5.80 MiB | 13.55 MiB/s, done.\nResolving deltas: 100% (962/962), done.\nFrom https://github.com/ejolly/pymer4\n * branch dev -> FETCH_HEAD\nUpdating 7e98fa2..23d0282\nFast-forward\n .travis.yml | 2 +-\n conda/meta.yaml | 2 +-\n docs/new.rst | 8 ++++++++\n pymer4/io.py | 4 ++--\n pymer4/models/Lm.py | 11 +++++++----\n pymer4/models/Lm2.py | 2 +-\n pymer4/models/Lmer.py | 21 ++++++++++++++++-----\n pymer4/simulate.py | 10 +++++-----\n pymer4/stats.py | 31 ++++++++++++++++---------------\n pymer4/tests/test_models.py | 3 ++-\n pymer4/utils.py | 11 +++++------\n pymer4/version.py | 2 +-\n requirements.txt | 2 +-\n 13 files changed, 66 insertions(+), 43 deletions(-)\nBranch 'dev' set up to track remote branch 'dev' from 'origin'.\nSwitched to a new branch 'dev'\n Building wheel for pymer4 (setup.py) ... done\n" }, { "code": null, "e": 11535, "s": 11248, "text": "# Install pymer4\n!pip install -q pymer4\n# load pymer4\nfrom pymer4.models import Lmer\nmodel = Lmer('Weight ~ Time + Evit + (1 + Time|Pig)', data=data)\ndisplay(model.fit())\n# ANOVA results from fitted model\ndisplay(model.anova())\n# Plot estimated model coefficients \nmodel.plot_summary()\n" }, { "code": null, "e": 11955, "s": 11535, "text": "Formula: Weight~Time+Evit+(1+Time|Pig)\n\nFamily: gaussian\t Inference: parametric\n\nNumber of observations: 861\t Groups: {'Pig': 72.0}\n\nLog-likelihood: -2214.080 \t AIC: 4428.160\n\nRandom effects:\n\n Name Var Std\nPig (Intercept) 19.701 4.439\nPig Time 0.416 0.645\nResidual 6.037 2.457\n\n IV1 IV2 Corr\nPig (Intercept) Time 0.081\n\nFixed effects:\n\n" }, { "code": null, "e": 12116, "s": 11955, "text": "SS Type III Analysis of Variance Table with Satterthwaite approximated degrees of freedom:\n(NOTE: Using original model contrasts, orthogonality not guaranteed)\n" }, { "code": null, "e": 12174, "s": 12116, "text": "<matplotlib.axes._subplots.AxesSubplot at 0x7faebd04de10>" }, { "code": null, "e": 12428, "s": 12174, "text": "Currently, the simplest out-of-the-box solutions is to use the LMER implementation in the Statsmodels package (examples here). Installation is the easiest and as simple as pip install statsmodels. After installation, you can run LMER like the following." }, { "code": null, "e": 12832, "s": 12428, "text": "To provide a bit more context, we are analyzing the dietoxdataset (learn more about the dataset here) to predict the weight of pigs as a function of time with a random slope specified by re_formula=\"~Time\" and a random intercept automatically specified by groups=data[\"Pig\"]. The outputs look like the figure below with the coefficients, standard errors, z stats, p values, and 95% confidence intervals." }, { "code": null, "e": 13121, "s": 12832, "text": "While this is splendid, specifying the random effects with this syntax is somewhat inconvenient and diverges from the traditional formulaic expressions used in LMER in R. For example in R, the random slopes and intercepts are specified within the model formula, in a single line, such as:" }, { "code": null, "e": 13171, "s": 13121, "text": "lmer('Weight ~ Time + (1+Time|Pig)', data=dietox)" }, { "code": null, "e": 13284, "s": 13171, "text": "This leads to our second option of using LMER in R through a direct interface between Python and R through rpy2." }, { "code": null, "e": 13763, "s": 13284, "text": "The second option is to directly access the original LMER packages in R through the rpy2 interface. The rpy2 interface allows users to toss data and results back and forth between your Python Jupyter Notebook environment and your R environment. rpy2 used to be notoriously finicky to install, but it has gotten more stable over the years. To use this option, you’ll need to install R in your machine as well as rpy2 which can be achieved in Google Colab with the following code:" }, { "code": null, "e": 14009, "s": 13763, "text": "The first line installs R using Linux syntax. If you are using a Mac or Windows you can achieve this by simply following the R installation instructions. The next set of lines install rpy2 then uses rpy2 to install the lme4 andlmerTest packages." }, { "code": null, "e": 14128, "s": 14009, "text": "Next, you’ll need to activate the Rmagic through the code, in you Jupyter Notebook cell by running the following code." }, { "code": null, "e": 14151, "s": 14128, "text": "%load_ext rpy2.ipython" }, { "code": null, "e": 14350, "s": 14151, "text": "After this, any Jupyter Notebook cell starting with %%R will allow you to run R command from your notebook. For example, to run the same model that we ran in statsmodels, you would do the following:" }, { "code": null, "e": 14739, "s": 14350, "text": "Note that this code starts with %%R which signals that this cell contains R code. We are also using a much simpler formulaic expression than statsmodels, We were able to specify that our groupings is Pigs and that we are estimating both random slopes and intercepts through (1+Time|Pig). This will give you the results that you would be more familiar with if you had been using LMER in R." }, { "code": null, "e": 14978, "s": 14739, "text": "And as I mentioned earlier, you can also pass your Pandas DataFrames to R. Remember that data DataFrame we loaded earlier in the statsmodels section? We can pass that to R, run the same LMER model, and retrieve the coefficients like this:" }, { "code": null, "e": 15244, "s": 14978, "text": "The -i data sends our Python Pandas DataFramedata into R and we use that to estimate our model m . Next, we retrieve the betas coefficients from the model with beta <- fixef(m) which is exported back to our notebook, because we specified in the first line -o betas." }, { "code": null, "e": 15714, "s": 15244, "text": "The best part of this approach is that you can add additional code in the R environment before running the model. For example, maybe you want to make sure a column called Evit is recognized as a factor with data$Evit <- as.factor(data$Evit), specify a new contrast for this categorical variable using contrasts(data$Evit) <- contr.poly , or even relevel your categorical data in the formula itself. All this can be easily achieved when using rpy2 to access LMER from R." }, { "code": null, "e": 15985, "s": 15714, "text": "To summarize, rpy2 interface gives you the most flexibility and the ability to access LMER and additional functions in R which you might be more familiar with if you are transitioning from R to Python. Lastly, we’ll touch a middle ground option using the Pymer4 package." }, { "code": null, "e": 16283, "s": 15985, "text": "Pymer4 (Jolly, 2018) can be a convenient middle ground between using LMER directly through rpy2 and using an LMER implementation in Statsmodels. This package basically brings you the convenience of using R formulaic syntax but in a more Pythonic way, without having to deal with the R magic cells." }, { "code": null, "e": 16783, "s": 16283, "text": "We covered 3 ways to run Linear Mixed Effects Models from a Python Jupyter Notebook environment. Statsmodels can be the most convenient but the syntax might be unfamiliar to users already experienced with LMER in R syntax. Using rpy2 gives you the most flexibility and power but this can get messy as you need to use Rmagic to switch between Python and R cells. Pymer4 is the great compromise solution which provides convenient access to LMER in R while minimizing the switch cost between languages." }, { "code": null, "e": 16849, "s": 16783, "text": "Here is a Google Colab Jupyter Notebook to run all the tutorials." } ]
HSQLDB - Regular Expressions
HSQLDB supports some special symbols for pattern matching operation based on regular expressions and the REGEXP operator. Following is the table of pattern, which can be used along with REGEXP operator. Let us try different example queries to meet our requirements. Take a look at the following given queries. Try this Query to find all the authors whose name starts with '^A'. SELECT author FROM tcount_tbl WHERE REGEXP_MATCHES(author,'^A.*'); After execution of the above query, you will receive the following output. +-----------------+ | author | +-----------------+ | Abdul S | | Ajith kumar | +-----------------+ Try this Query to find all the authors whose name ends with 'ul$'. SELECT author FROM tcount_tbl WHERE REGEXP_MATCHES(author,'.*ul$'); After execution of the above query, you will receive the following output. +-----------------+ | author | +-----------------+ | John Poul | +-----------------+ Try this Query to find all the authors whose name contains 'th'. SELECT author FROM tcount_tbl WHERE REGEXP_MATCHES(author,'.*th.*'); After execution of the above query, you will receive the following output. +-----------------+ | author | +-----------------+ | Ajith kumar | | Abdul S | +-----------------+ Try this query to find all the authors whose name starts with vowel (a, e, i, o, u). SELECT author FROM tcount_tbl WHERE REGEXP_MATCHES(author,'^[AEIOU].*'); After execution of the above query, you will receive the following output. +-----------------+ | author | +-----------------+ | Abdul S | | Ajith kumar | +-----------------+ Print Add Notes Bookmark this page
[ { "code": null, "e": 2104, "s": 1982, "text": "HSQLDB supports some special symbols for pattern matching operation based on regular expressions and the REGEXP operator." }, { "code": null, "e": 2185, "s": 2104, "text": "Following is the table of pattern, which can be used along with REGEXP operator." }, { "code": null, "e": 2292, "s": 2185, "text": "Let us try different example queries to meet our requirements. Take a look at the following given queries." }, { "code": null, "e": 2360, "s": 2292, "text": "Try this Query to find all the authors whose name starts with '^A'." }, { "code": null, "e": 2428, "s": 2360, "text": "SELECT author FROM tcount_tbl WHERE REGEXP_MATCHES(author,'^A.*');\n" }, { "code": null, "e": 2503, "s": 2428, "text": "After execution of the above query, you will receive the following output." }, { "code": null, "e": 2624, "s": 2503, "text": "+-----------------+\n| author |\n+-----------------+\n| Abdul S |\n| Ajith kumar |\n+-----------------+\n" }, { "code": null, "e": 2691, "s": 2624, "text": "Try this Query to find all the authors whose name ends with 'ul$'." }, { "code": null, "e": 2760, "s": 2691, "text": "SELECT author FROM tcount_tbl WHERE REGEXP_MATCHES(author,'.*ul$');\n" }, { "code": null, "e": 2835, "s": 2760, "text": "After execution of the above query, you will receive the following output." }, { "code": null, "e": 2936, "s": 2835, "text": "+-----------------+\n| author |\n+-----------------+\n| John Poul |\n+-----------------+\n" }, { "code": null, "e": 3001, "s": 2936, "text": "Try this Query to find all the authors whose name contains 'th'." }, { "code": null, "e": 3071, "s": 3001, "text": "SELECT author FROM tcount_tbl WHERE REGEXP_MATCHES(author,'.*th.*');\n" }, { "code": null, "e": 3146, "s": 3071, "text": "After execution of the above query, you will receive the following output." }, { "code": null, "e": 3268, "s": 3146, "text": "+-----------------+\n| author |\n+-----------------+\n| Ajith kumar | \n| Abdul S |\n+-----------------+\n" }, { "code": null, "e": 3353, "s": 3268, "text": "Try this query to find all the authors whose name starts with vowel (a, e, i, o, u)." }, { "code": null, "e": 3427, "s": 3353, "text": "SELECT author FROM tcount_tbl WHERE REGEXP_MATCHES(author,'^[AEIOU].*');\n" }, { "code": null, "e": 3502, "s": 3427, "text": "After execution of the above query, you will receive the following output." }, { "code": null, "e": 3623, "s": 3502, "text": "+-----------------+\n| author |\n+-----------------+\n| Abdul S |\n| Ajith kumar |\n+-----------------+\n" }, { "code": null, "e": 3630, "s": 3623, "text": " Print" }, { "code": null, "e": 3641, "s": 3630, "text": " Add Notes" } ]
Portfolio Risk Management Using Monte Carlo Simulations in Python | Towards Data Science
VaR is an acronym of ‘Value at Risk’, and is a tool which is used by many firms and banks to establish the level of financial risk within its firm. The VaR is calculated for an investments of a company’s investments or perhaps for checking the riks levels of a portfolio managed by the wealth management branch of a bank or a boutique firm. The calculation may be thought of as a statistical measure in isolation. It can also be simplified to the following example statement - VaR is the minimum loss which will be incurred at a certain level of probability (confidence interval) OR the maximum loss which will be realized at a level of probability. The above image shows the maximum loss which can be faced by a company at a α% confidence. On a personal level VaR can help you predict or analyse the maximum losses which your portfolio is likely to face — this is something which we will analyse soon. The Monte Carlo model was the brainchild of Stanislaw Ulam and John Neumann, who developed the model after the second world war. The model is named after a gambling city in Monaco, due to the chance and random encounters faced in gambling. The Monte Carlo simulation is a probability model which generates random variables used in tandem with economic factors (expected return, volatility — in the case of a portfolio of funds) to predict outcomes over a large spectrum. While not the most accurate, the model is often used to calculate the risk and uncertainty. We will now use the Monte Carlo simulation to generate a set of predicted returns for our portfolio of assets which will help us to find out the VaR of our investments. We will first set up the notebook by importing the required libraries and functions #Importing all required libraries#Created by Sanket Karveimport matplotlib.pyplot as pltimport numpy as npimport pandas as pdimport pandas_datareader as webfrom matplotlib.ticker import FuncFormatter!pip install PyPortfolioOpt#Installing the Portfolio Optimzation Libraryfrom pypfopt.efficient_frontier import EfficientFrontierfrom pypfopt import risk_modelsfrom pypfopt import expected_returnsfrom matplotlib.ticker import FuncFormatter For the purposes of our project, I have considered the ‘FAANG’ stocks for the last two years. tickers = ['GOOGL','FB','AAPL','NFLX','AMZN']thelen = len(tickers)price_data = []for ticker in range(thelen): prices = web.DataReader(tickers[ticker], start='2018-06-20', end = '2020-06-20', data_source='yahoo') price_data.append(prices[['Adj Close']])df_stocks = pd.concat(price_data, axis=1)df_stocks.columns=tickersdf_stocks.tail() For the next step, we will calculated the portfolio weights of each asset. I have done this by using the asset weights calculated for achieving the maximum Sharpe Ratio. I have posted the snippets of the code for the calculation below. #Annualized Returnmu = expected_returns.mean_historical_return(df_stocks)#Sample Variance of PortfolioSigma = risk_models.sample_cov(df_stocks)#Max Sharpe Ratio - Tangent to the EFfrom pypfopt import objective_functions, base_optimizeref = EfficientFrontier(mu, Sigma, weight_bounds=(0,1)) #weight bounds in negative allows shorting of stockssharpe_pfolio=ef.max_sharpe() #May use add objective to ensure minimum zero weighting to individual stockssharpe_pwt=ef.clean_weights()print(sharpe_pwt) The asset weights will be used to calculate the expected portfolio return. #VaR Calculationticker_rx2 = []#Convert Dictionary to list of asset weights from Max Sharpe Ratio Portfoliosh_wt = list(sharpe_pwt.values())sh_wt=np.array(sh_wt) Now, we will convert the stock prices of the portfolio to a cumulative return, which may also be considered as the holding period returns (HPR)for this project. for a in range(thelen): ticker_rx = df_stocks[[tickers[a]]].pct_change() ticker_rx = (ticker_rx+1).cumprod() ticker_rx2.append(ticker_rx[[tickers[a]]])ticker_final = pd.concat(ticker_rx2,axis=1)ticker_final #Plot graph of Cumulative/HPR of all stocksfor i, col in enumerate(ticker_final.columns): ticker_final[col].plot()plt.title('Cumulative Returns')plt.xticks(rotation=80)plt.legend(ticker_final.columns)#Saving the graph into a JPG fileplt.savefig('CR.png', bbox_inches='tight') Now, we will pick out the latest HPR of each asset and multiply the returns with the calculated asset weights using the .dot() function. #Taking Latest Values of Returnpret = []pre1 = []price =[]for x in range(thelen): pret.append(ticker_final.iloc[[-1],[x]]) price.append((df_stocks.iloc[[-1],[x]]))pre1 = pd.concat(pret,axis=1)pre1 = np.array(pre1)price = pd.concat(price,axis=1)varsigma = pre1.std()ex_rtn=pre1.dot(sh_wt)print('The weighted expected portfolio return for selected time period is'+ str(ex_rtn))#ex_rtn = (ex_rtn)**0.5-(1) #Annualizing the cumulative return (will not affect outcome)price=price.dot(sh_wt) #Calculating weighted valueprint(ex_rtn, varsigma,price) Having calculated the expected portfolio return and the volatility (standard deviation of the expected returns), we will set up and run the Monte Carlo simulation. I have used a time of 1440 (no of minutes in a day) with 10,000 simulation runs. The time-steps may be changed per requirement. I have used a 95% confidence interval. from scipy.stats import normimport mathTime=1440 #No of days(steps or trading days in this case)lt_price=[]final_res=[]for i in range(10000): #10000 runs of simulation daily_return= (np.random.normal(ex_rtn/Time,varsigma/math.sqrt(Time),Time)) plt.plot(daily_returns)plt.axhline(np.percentile(daily_returns,5), color='r', linestyle='dashed', linewidth=1)plt.axhline(np.percentile(daily_returns,95), color='g', linestyle='dashed', linewidth=1)plt.axhline(np.mean(daily_returns), color='b', linestyle='solid', linewidth=1)plt.show() Visualizing the distribution plot of the returns presents us with the following chart plt.hist(daily_returns,bins=15)plt.axvline(np.percentile(daily_returns,5), color='r', linestyle='dashed', linewidth=2)plt.axvline(np.percentile(daily_returns,95), color='r', linestyle='dashed', linewidth=2)plt.show() Printing the exact values at both the upper limit and lower limit and assuming our portfolio value to be $1000, we will calculated an estimate of the amount of funds which should be kept to cover for our minimum losses. print(np.percentile(daily_returns,5),np.percentile(daily_returns,95)) #VaR - Minimum loss of 5.7% at a 5% probability, also a gain can be higher than 15% with a 5 % probabilitypvalue = 1000 #portfolio valueprint('$Amount required to cover minimum losses for one day is ' + str(pvalue* - np.percentile(daily_returns,5))) The resulting amount will signify the dollar amount required to cover your losses per day. The result can also be interpreted as the minimum losses that your portfolio will face with a 5% probability. The method above has shown how we can calculate the Value at Risk (VaR) for our portfolio. For a refresher on calculating a portfolio for a certain amount of investment using the Modern Portfolio Thoery (MPT), will help to consolidate your understanding of portfolio analysis and optimization. Finally, the VaR, in tandem with Monte Carlo simulation model, may also be used to predict losses and gains via share prices. This can be done by multiplying the daily return values generated with the final price of the respective ticker. All views expressed are my own. This article is not to be treated as expert investment advise. Feel free to reach out to me on LinkedIn | Twitter and drop me a message Some rights reserved
[ { "code": null, "e": 513, "s": 172, "text": "VaR is an acronym of ‘Value at Risk’, and is a tool which is used by many firms and banks to establish the level of financial risk within its firm. The VaR is calculated for an investments of a company’s investments or perhaps for checking the riks levels of a portfolio managed by the wealth management branch of a bank or a boutique firm." }, { "code": null, "e": 649, "s": 513, "text": "The calculation may be thought of as a statistical measure in isolation. It can also be simplified to the following example statement -" }, { "code": null, "e": 822, "s": 649, "text": "VaR is the minimum loss which will be incurred at a certain level of probability (confidence interval) OR the maximum loss which will be realized at a level of probability." }, { "code": null, "e": 1075, "s": 822, "text": "The above image shows the maximum loss which can be faced by a company at a α% confidence. On a personal level VaR can help you predict or analyse the maximum losses which your portfolio is likely to face — this is something which we will analyse soon." }, { "code": null, "e": 1315, "s": 1075, "text": "The Monte Carlo model was the brainchild of Stanislaw Ulam and John Neumann, who developed the model after the second world war. The model is named after a gambling city in Monaco, due to the chance and random encounters faced in gambling." }, { "code": null, "e": 1638, "s": 1315, "text": "The Monte Carlo simulation is a probability model which generates random variables used in tandem with economic factors (expected return, volatility — in the case of a portfolio of funds) to predict outcomes over a large spectrum. While not the most accurate, the model is often used to calculate the risk and uncertainty." }, { "code": null, "e": 1807, "s": 1638, "text": "We will now use the Monte Carlo simulation to generate a set of predicted returns for our portfolio of assets which will help us to find out the VaR of our investments." }, { "code": null, "e": 1891, "s": 1807, "text": "We will first set up the notebook by importing the required libraries and functions" }, { "code": null, "e": 2329, "s": 1891, "text": "#Importing all required libraries#Created by Sanket Karveimport matplotlib.pyplot as pltimport numpy as npimport pandas as pdimport pandas_datareader as webfrom matplotlib.ticker import FuncFormatter!pip install PyPortfolioOpt#Installing the Portfolio Optimzation Libraryfrom pypfopt.efficient_frontier import EfficientFrontierfrom pypfopt import risk_modelsfrom pypfopt import expected_returnsfrom matplotlib.ticker import FuncFormatter" }, { "code": null, "e": 2423, "s": 2329, "text": "For the purposes of our project, I have considered the ‘FAANG’ stocks for the last two years." }, { "code": null, "e": 2762, "s": 2423, "text": "tickers = ['GOOGL','FB','AAPL','NFLX','AMZN']thelen = len(tickers)price_data = []for ticker in range(thelen): prices = web.DataReader(tickers[ticker], start='2018-06-20', end = '2020-06-20', data_source='yahoo') price_data.append(prices[['Adj Close']])df_stocks = pd.concat(price_data, axis=1)df_stocks.columns=tickersdf_stocks.tail()" }, { "code": null, "e": 2998, "s": 2762, "text": "For the next step, we will calculated the portfolio weights of each asset. I have done this by using the asset weights calculated for achieving the maximum Sharpe Ratio. I have posted the snippets of the code for the calculation below." }, { "code": null, "e": 3493, "s": 2998, "text": "#Annualized Returnmu = expected_returns.mean_historical_return(df_stocks)#Sample Variance of PortfolioSigma = risk_models.sample_cov(df_stocks)#Max Sharpe Ratio - Tangent to the EFfrom pypfopt import objective_functions, base_optimizeref = EfficientFrontier(mu, Sigma, weight_bounds=(0,1)) #weight bounds in negative allows shorting of stockssharpe_pfolio=ef.max_sharpe() #May use add objective to ensure minimum zero weighting to individual stockssharpe_pwt=ef.clean_weights()print(sharpe_pwt)" }, { "code": null, "e": 3568, "s": 3493, "text": "The asset weights will be used to calculate the expected portfolio return." }, { "code": null, "e": 3730, "s": 3568, "text": "#VaR Calculationticker_rx2 = []#Convert Dictionary to list of asset weights from Max Sharpe Ratio Portfoliosh_wt = list(sharpe_pwt.values())sh_wt=np.array(sh_wt)" }, { "code": null, "e": 3891, "s": 3730, "text": "Now, we will convert the stock prices of the portfolio to a cumulative return, which may also be considered as the holding period returns (HPR)for this project." }, { "code": null, "e": 4101, "s": 3891, "text": "for a in range(thelen): ticker_rx = df_stocks[[tickers[a]]].pct_change() ticker_rx = (ticker_rx+1).cumprod() ticker_rx2.append(ticker_rx[[tickers[a]]])ticker_final = pd.concat(ticker_rx2,axis=1)ticker_final" }, { "code": null, "e": 4378, "s": 4101, "text": "#Plot graph of Cumulative/HPR of all stocksfor i, col in enumerate(ticker_final.columns): ticker_final[col].plot()plt.title('Cumulative Returns')plt.xticks(rotation=80)plt.legend(ticker_final.columns)#Saving the graph into a JPG fileplt.savefig('CR.png', bbox_inches='tight')" }, { "code": null, "e": 4515, "s": 4378, "text": "Now, we will pick out the latest HPR of each asset and multiply the returns with the calculated asset weights using the .dot() function." }, { "code": null, "e": 5060, "s": 4515, "text": "#Taking Latest Values of Returnpret = []pre1 = []price =[]for x in range(thelen): pret.append(ticker_final.iloc[[-1],[x]]) price.append((df_stocks.iloc[[-1],[x]]))pre1 = pd.concat(pret,axis=1)pre1 = np.array(pre1)price = pd.concat(price,axis=1)varsigma = pre1.std()ex_rtn=pre1.dot(sh_wt)print('The weighted expected portfolio return for selected time period is'+ str(ex_rtn))#ex_rtn = (ex_rtn)**0.5-(1) #Annualizing the cumulative return (will not affect outcome)price=price.dot(sh_wt) #Calculating weighted valueprint(ex_rtn, varsigma,price)" }, { "code": null, "e": 5391, "s": 5060, "text": "Having calculated the expected portfolio return and the volatility (standard deviation of the expected returns), we will set up and run the Monte Carlo simulation. I have used a time of 1440 (no of minutes in a day) with 10,000 simulation runs. The time-steps may be changed per requirement. I have used a 95% confidence interval." }, { "code": null, "e": 5944, "s": 5391, "text": "from scipy.stats import normimport mathTime=1440 #No of days(steps or trading days in this case)lt_price=[]final_res=[]for i in range(10000): #10000 runs of simulation daily_return= (np.random.normal(ex_rtn/Time,varsigma/math.sqrt(Time),Time)) plt.plot(daily_returns)plt.axhline(np.percentile(daily_returns,5), color='r', linestyle='dashed', linewidth=1)plt.axhline(np.percentile(daily_returns,95), color='g', linestyle='dashed', linewidth=1)plt.axhline(np.mean(daily_returns), color='b', linestyle='solid', linewidth=1)plt.show()" }, { "code": null, "e": 6030, "s": 5944, "text": "Visualizing the distribution plot of the returns presents us with the following chart" }, { "code": null, "e": 6247, "s": 6030, "text": "plt.hist(daily_returns,bins=15)plt.axvline(np.percentile(daily_returns,5), color='r', linestyle='dashed', linewidth=2)plt.axvline(np.percentile(daily_returns,95), color='r', linestyle='dashed', linewidth=2)plt.show()" }, { "code": null, "e": 6467, "s": 6247, "text": "Printing the exact values at both the upper limit and lower limit and assuming our portfolio value to be $1000, we will calculated an estimate of the amount of funds which should be kept to cover for our minimum losses." }, { "code": null, "e": 6787, "s": 6467, "text": "print(np.percentile(daily_returns,5),np.percentile(daily_returns,95)) #VaR - Minimum loss of 5.7% at a 5% probability, also a gain can be higher than 15% with a 5 % probabilitypvalue = 1000 #portfolio valueprint('$Amount required to cover minimum losses for one day is ' + str(pvalue* - np.percentile(daily_returns,5)))" }, { "code": null, "e": 6988, "s": 6787, "text": "The resulting amount will signify the dollar amount required to cover your losses per day. The result can also be interpreted as the minimum losses that your portfolio will face with a 5% probability." }, { "code": null, "e": 7521, "s": 6988, "text": "The method above has shown how we can calculate the Value at Risk (VaR) for our portfolio. For a refresher on calculating a portfolio for a certain amount of investment using the Modern Portfolio Thoery (MPT), will help to consolidate your understanding of portfolio analysis and optimization. Finally, the VaR, in tandem with Monte Carlo simulation model, may also be used to predict losses and gains via share prices. This can be done by multiplying the daily return values generated with the final price of the respective ticker." }, { "code": null, "e": 7616, "s": 7521, "text": "All views expressed are my own. This article is not to be treated as expert investment advise." }, { "code": null, "e": 7689, "s": 7616, "text": "Feel free to reach out to me on LinkedIn | Twitter and drop me a message" } ]
Write an Efficient C Program to Reverse Bits of a Number in C++
In this problem, we are given an unsigned integer n. Our task is to create a program that returns the number which is generated by reversing all the bits of the number. Let’s take an example to understand the problem, n = 1 2147483648 binary of 1 is 000...0001, the reverse is 100...0000. To solve this problem, we simple solution will be using a simple formula. We will loop through the binary of the number. And find the position of the set bit in the number lets say it i. The result will be calculated using the formula, ((total_number_of_bits) - 1) - i Program to show the implementation of this algorithm, Live Demo #include<iostream> using namespace std; unsigned int reverseBitNumber(unsigned int num) { unsigned int totalNumberOfBits = sizeof(num) * 8; unsigned int reverseNumber = 0, temp; for (int i = 0; i < totalNumberOfBits; i++){ if((num & (1 << i))) reverseNumber |= (1 << ((totalNumberOfBits - 1) - i)); } return reverseNumber; } int main() { unsigned int n = 21; cout<<"The number is "<<n<<endl; cout<<"The number which has reverse bits of the number is :"<<reverseBitNumber(n); return 0; } The number is 2 The number which has reverse bits of the number is :2818572288 Another method is using shifting, we will shift the bits of the number until it become zero and the shift them in reverse number and then shift the bits remaining number of times to get the result. Program to show the implementation of our solution, Live Demo #include<iostream> using namespace std; unsigned int reverseBitNumber(unsigned int n){ unsigned int rem_shift = sizeof(n) * 8 - 1; unsigned int reverseNubmer = n; n >>= 1; while(n){ reverseNubmer <<= 1; reverseNubmer |= n & 1; n >>= 1; rem_shift--; } reverseNubmer <<= rem_shift; return reverseNubmer; } int main(){ unsigned int n = 21; cout<<"The number is "<<n<<endl; cout<<"The number which has reverse bits of the number is :"<<reverseBitNumber(n); return 0; } The number is 21 The number which has reverse bits of the number is :2818572288
[ { "code": null, "e": 1231, "s": 1062, "text": "In this problem, we are given an unsigned integer n. Our task is to create a program that returns the number which is generated by reversing all the bits of the number." }, { "code": null, "e": 1280, "s": 1231, "text": "Let’s take an example to understand the problem," }, { "code": null, "e": 1286, "s": 1280, "text": "n = 1" }, { "code": null, "e": 1297, "s": 1286, "text": "2147483648" }, { "code": null, "e": 1351, "s": 1297, "text": "binary of 1 is 000...0001, the reverse is 100...0000." }, { "code": null, "e": 1620, "s": 1351, "text": "To solve this problem, we simple solution will be using a simple formula. We will loop through the binary of the number. And find the position of the set bit in the number lets say it i. The result will be calculated using the formula, ((total_number_of_bits) - 1) - i" }, { "code": null, "e": 1674, "s": 1620, "text": "Program to show the implementation of this algorithm," }, { "code": null, "e": 1685, "s": 1674, "text": " Live Demo" }, { "code": null, "e": 2214, "s": 1685, "text": "#include<iostream>\nusing namespace std;\nunsigned int reverseBitNumber(unsigned int num) {\n unsigned int totalNumberOfBits = sizeof(num) * 8;\n unsigned int reverseNumber = 0, temp;\n for (int i = 0; i < totalNumberOfBits; i++){\n if((num & (1 << i)))\n reverseNumber |= (1 << ((totalNumberOfBits - 1) - i));\n }\n return reverseNumber;\n}\nint main() {\n unsigned int n = 21;\n cout<<\"The number is \"<<n<<endl;\n cout<<\"The number which has reverse bits of the number is :\"<<reverseBitNumber(n);\n return 0;\n}" }, { "code": null, "e": 2293, "s": 2214, "text": "The number is 2\nThe number which has reverse bits of the number is :2818572288" }, { "code": null, "e": 2491, "s": 2293, "text": "Another method is using shifting, we will shift the bits of the number until it become zero and the shift them in reverse number and then shift the bits remaining number of times to get the result." }, { "code": null, "e": 2543, "s": 2491, "text": "Program to show the implementation of our solution," }, { "code": null, "e": 2554, "s": 2543, "text": " Live Demo" }, { "code": null, "e": 3076, "s": 2554, "text": "#include<iostream>\nusing namespace std;\nunsigned int reverseBitNumber(unsigned int n){\n unsigned int rem_shift = sizeof(n) * 8 - 1;\n unsigned int reverseNubmer = n;\n n >>= 1;\n while(n){\n reverseNubmer <<= 1;\n reverseNubmer |= n & 1;\n n >>= 1;\n rem_shift--;\n }\n reverseNubmer <<= rem_shift;\n return reverseNubmer;\n}\nint main(){\n unsigned int n = 21;\n cout<<\"The number is \"<<n<<endl;\n cout<<\"The number which has reverse bits of the number is :\"<<reverseBitNumber(n);\n return 0;\n}" }, { "code": null, "e": 3156, "s": 3076, "text": "The number is 21\nThe number which has reverse bits of the number is :2818572288" } ]
Different Ways to View Contents of Database File in Android Studio - GeeksforGeeks
06 Apr, 2021 Data is a group of information and it can be any kind of information – text, numbers, image, video. An organized collection of this data is called a Database. It is made so that the data can be accessed and managed easily. Data can be organized into tables, rows, columns as that make it easier to handle the data. The main purpose of having a database is to make it possible to work with huge amounts of data and be able to handle it. Databases store all the data that is required or was used in history by the website or app. There are a number of databases available, such as MySQL, Sybase, Oracle, MongoDB, Informix, PostgreSQL, SQL Server. A database management system (DBMS) is used to manage modern databases. Structured query language (SQL) is used to perform operations on the data stored in the database. There are many ways to view the content of databases in Android Studio. In this article, we are going to discuss five different methods to View the Contents of the Database File in Android Studio. Method 1: Without Opening DDMS Method 2: Using Stetho library Method 3: Using SQLiteBrowser Method 4: Using ADB shell to connect to Sqlite3 Method 5: Using Database Inspector This method works on the Emulator only. In the first step, note down the path of the database file in your system. For example, let it be /data/data/com.VVV.file/databases/com.VVV.file.database Secondly, the database file needs to be pulled into the PC. Use the following command adb pull /data/data/com.YYY.module/databases/com.YYY.module.database /Users/PATH/ If it shows permission denied or something similar to it, run adb root and run the previous command again. In the first step – add stello dependency in build.gradle compile 'com.facebook.stetho:stetho:1.5.0’ The second step – put the following command on the OnCreate() method of the main activity Stetho.initializeWithDefaults(this); The third step – Connect a device and run the app. Visit the following site using Chrome browser chrome://inspect/#devices Download and install SQLiteBrowser. Copy the database from the device to the PC For Android studio versions < 3.0Open DDMS via Tools > Android > Android Device MonitorThe device should appear on the left, click on it.All the applications running on the device will appear.A tab on the bottom right corner appears named File explorerIn the file explorer, go to /data/data/databasesSelect the database you want to see.Click on the ‘pull a file from the device’ button. It is present in the top right corner of the Android device monitor window.A pop-up window will ask to save the files. Save them wherever you want to. Open DDMS via Tools > Android > Android Device Monitor The device should appear on the left, click on it. All the applications running on the device will appear. A tab on the bottom right corner appears named File explorer In the file explorer, go to /data/data/databases Select the database you want to see. Click on the ‘pull a file from the device’ button. It is present in the top right corner of the Android device monitor window. A pop-up window will ask to save the files. Save them wherever you want to. For Android studio >= 3.0Use View > Tool Windows > Device File Explorer to Open device file explorer. Go to data/data/PACKAGE_NAME/database. PACKAGE_NAME is the name of the package one is developing.Right-click on the database and save it wherever you want using the Save As. Use View > Tool Windows > Device File Explorer to Open device file explorer. Go to data/data/PACKAGE_NAME/database. PACKAGE_NAME is the name of the package one is developing. Right-click on the database and save it wherever you want using the Save As. Open the SQLiteBrowser and click on ‘open database’. Navigate to the place where the database was saved and open the database. The content of the database is displayed now. Go to the tools folder in the command prompt. Use the command adb devices to see the list of all devices C:\ProgramFiles(x86)\Android\adt-bundle-windows\sdk\platform-tools>adb devices List of devices attached Redmi Note 7 pro device Connect a shell to the device C:\ProgramFiles(x86)\Android\adt-bundle-windows-x86_64\sdk\platform-tools>adb -s Redmi Note 7 pro shell Go to the file containing the DB file cd data/data/<package-name>/databases/ Execute sqlite3 to connect to DB sqlite3 <db-name>.db Run SQL commands to see any table. For example: Select * from table1; In the latest version of Android studios 4.1, the long-awaited tool Database Inspector made its appearance. It helps to inspect, query, and modify the database in the running app. Database inspector makes database editing as simple as editing a spreadsheet. Using room and observing the query result the changes are reflected in real-time in the app. To open the database inspector select View -> Tool Windows -> Database Inspector from the menu bar of Android Studio. Connect a device running on API level 26 or higher. Run the app. The database schemas appear and you can select the database you want to see. The selected database is displayed. Android-Studio Picked Android Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Create and Add Data to SQLite Database in Android? Broadcast Receiver in Android With Example Android RecyclerView in Kotlin Services in Android with Example CardView in Android With Example Content Providers in Android with Example How to Update Gradle in Android Studio? Navigation Drawer in Android Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android?
[ { "code": null, "e": 24403, "s": 24375, "text": "\n06 Apr, 2021" }, { "code": null, "e": 25416, "s": 24403, "text": "Data is a group of information and it can be any kind of information – text, numbers, image, video. An organized collection of this data is called a Database. It is made so that the data can be accessed and managed easily. Data can be organized into tables, rows, columns as that make it easier to handle the data. The main purpose of having a database is to make it possible to work with huge amounts of data and be able to handle it. Databases store all the data that is required or was used in history by the website or app. There are a number of databases available, such as MySQL, Sybase, Oracle, MongoDB, Informix, PostgreSQL, SQL Server. A database management system (DBMS) is used to manage modern databases. Structured query language (SQL) is used to perform operations on the data stored in the database. There are many ways to view the content of databases in Android Studio. In this article, we are going to discuss five different methods to View the Contents of the Database File in Android Studio. " }, { "code": null, "e": 25447, "s": 25416, "text": "Method 1: Without Opening DDMS" }, { "code": null, "e": 25478, "s": 25447, "text": "Method 2: Using Stetho library" }, { "code": null, "e": 25508, "s": 25478, "text": "Method 3: Using SQLiteBrowser" }, { "code": null, "e": 25556, "s": 25508, "text": "Method 4: Using ADB shell to connect to Sqlite3" }, { "code": null, "e": 25591, "s": 25556, "text": "Method 5: Using Database Inspector" }, { "code": null, "e": 25632, "s": 25591, "text": "This method works on the Emulator only. " }, { "code": null, "e": 25730, "s": 25632, "text": "In the first step, note down the path of the database file in your system. For example, let it be" }, { "code": null, "e": 25786, "s": 25730, "text": "/data/data/com.VVV.file/databases/com.VVV.file.database" }, { "code": null, "e": 25872, "s": 25786, "text": "Secondly, the database file needs to be pulled into the PC. Use the following command" }, { "code": null, "e": 25954, "s": 25872, "text": "adb pull /data/data/com.YYY.module/databases/com.YYY.module.database /Users/PATH/" }, { "code": null, "e": 26063, "s": 25954, "text": "If it shows permission denied or something similar to it, run adb root and run the previous command again. " }, { "code": null, "e": 26121, "s": 26063, "text": "In the first step – add stello dependency in build.gradle" }, { "code": null, "e": 26164, "s": 26121, "text": "compile 'com.facebook.stetho:stetho:1.5.0’" }, { "code": null, "e": 26254, "s": 26164, "text": "The second step – put the following command on the OnCreate() method of the main activity" }, { "code": null, "e": 26291, "s": 26254, "text": "Stetho.initializeWithDefaults(this);" }, { "code": null, "e": 26388, "s": 26291, "text": "The third step – Connect a device and run the app. Visit the following site using Chrome browser" }, { "code": null, "e": 26414, "s": 26388, "text": "chrome://inspect/#devices" }, { "code": null, "e": 26494, "s": 26414, "text": "Download and install SQLiteBrowser. Copy the database from the device to the PC" }, { "code": null, "e": 27032, "s": 26494, "text": "For Android studio versions < 3.0Open DDMS via Tools > Android > Android Device MonitorThe device should appear on the left, click on it.All the applications running on the device will appear.A tab on the bottom right corner appears named File explorerIn the file explorer, go to /data/data/databasesSelect the database you want to see.Click on the ‘pull a file from the device’ button. It is present in the top right corner of the Android device monitor window.A pop-up window will ask to save the files. Save them wherever you want to." }, { "code": null, "e": 27087, "s": 27032, "text": "Open DDMS via Tools > Android > Android Device Monitor" }, { "code": null, "e": 27138, "s": 27087, "text": "The device should appear on the left, click on it." }, { "code": null, "e": 27194, "s": 27138, "text": "All the applications running on the device will appear." }, { "code": null, "e": 27255, "s": 27194, "text": "A tab on the bottom right corner appears named File explorer" }, { "code": null, "e": 27304, "s": 27255, "text": "In the file explorer, go to /data/data/databases" }, { "code": null, "e": 27341, "s": 27304, "text": "Select the database you want to see." }, { "code": null, "e": 27468, "s": 27341, "text": "Click on the ‘pull a file from the device’ button. It is present in the top right corner of the Android device monitor window." }, { "code": null, "e": 27544, "s": 27468, "text": "A pop-up window will ask to save the files. Save them wherever you want to." }, { "code": null, "e": 27822, "s": 27544, "text": "For Android studio >= 3.0Use View > Tool Windows > Device File Explorer to Open device file explorer. Go to data/data/PACKAGE_NAME/database. PACKAGE_NAME is the name of the package one is developing.Right-click on the database and save it wherever you want using the Save As. " }, { "code": null, "e": 27900, "s": 27822, "text": "Use View > Tool Windows > Device File Explorer to Open device file explorer. " }, { "code": null, "e": 27998, "s": 27900, "text": "Go to data/data/PACKAGE_NAME/database. PACKAGE_NAME is the name of the package one is developing." }, { "code": null, "e": 28077, "s": 27998, "text": "Right-click on the database and save it wherever you want using the Save As. " }, { "code": null, "e": 28250, "s": 28077, "text": "Open the SQLiteBrowser and click on ‘open database’. Navigate to the place where the database was saved and open the database. The content of the database is displayed now." }, { "code": null, "e": 28355, "s": 28250, "text": "Go to the tools folder in the command prompt. Use the command adb devices to see the list of all devices" }, { "code": null, "e": 28487, "s": 28355, "text": "C:\\ProgramFiles(x86)\\Android\\adt-bundle-windows\\sdk\\platform-tools>adb devices \nList of devices attached \nRedmi Note 7 pro device" }, { "code": null, "e": 28517, "s": 28487, "text": "Connect a shell to the device" }, { "code": null, "e": 28621, "s": 28517, "text": "C:\\ProgramFiles(x86)\\Android\\adt-bundle-windows-x86_64\\sdk\\platform-tools>adb -s Redmi Note 7 pro shell" }, { "code": null, "e": 28659, "s": 28621, "text": "Go to the file containing the DB file" }, { "code": null, "e": 28698, "s": 28659, "text": "cd data/data/<package-name>/databases/" }, { "code": null, "e": 28731, "s": 28698, "text": "Execute sqlite3 to connect to DB" }, { "code": null, "e": 28752, "s": 28731, "text": "sqlite3 <db-name>.db" }, { "code": null, "e": 28800, "s": 28752, "text": "Run SQL commands to see any table. For example:" }, { "code": null, "e": 28822, "s": 28800, "text": "Select * from table1;" }, { "code": null, "e": 29173, "s": 28822, "text": "In the latest version of Android studios 4.1, the long-awaited tool Database Inspector made its appearance. It helps to inspect, query, and modify the database in the running app. Database inspector makes database editing as simple as editing a spreadsheet. Using room and observing the query result the changes are reflected in real-time in the app." }, { "code": null, "e": 29291, "s": 29173, "text": "To open the database inspector select View -> Tool Windows -> Database Inspector from the menu bar of Android Studio." }, { "code": null, "e": 29343, "s": 29291, "text": "Connect a device running on API level 26 or higher." }, { "code": null, "e": 29356, "s": 29343, "text": "Run the app." }, { "code": null, "e": 29433, "s": 29356, "text": "The database schemas appear and you can select the database you want to see." }, { "code": null, "e": 29469, "s": 29433, "text": "The selected database is displayed." }, { "code": null, "e": 29484, "s": 29469, "text": "Android-Studio" }, { "code": null, "e": 29491, "s": 29484, "text": "Picked" }, { "code": null, "e": 29499, "s": 29491, "text": "Android" }, { "code": null, "e": 29507, "s": 29499, "text": "Android" }, { "code": null, "e": 29605, "s": 29507, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29614, "s": 29605, "text": "Comments" }, { "code": null, "e": 29627, "s": 29614, "text": "Old Comments" }, { "code": null, "e": 29685, "s": 29627, "text": "How to Create and Add Data to SQLite Database in Android?" }, { "code": null, "e": 29728, "s": 29685, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 29759, "s": 29728, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 29792, "s": 29759, "text": "Services in Android with Example" }, { "code": null, "e": 29825, "s": 29792, "text": "CardView in Android With Example" }, { "code": null, "e": 29867, "s": 29825, "text": "Content Providers in Android with Example" }, { "code": null, "e": 29907, "s": 29867, "text": "How to Update Gradle in Android Studio?" }, { "code": null, "e": 29936, "s": 29907, "text": "Navigation Drawer in Android" }, { "code": null, "e": 29975, "s": 29936, "text": "Flutter - Custom Bottom Navigation Bar" } ]
Grid Searching From Scratch using Python - GeeksforGeeks
26 Nov, 2020 Grid searching is a method to find the best possible combination of hyper-parameters at which the model achieves the highest accuracy. Before applying Grid Searching on any algorithm, Data is used to divided into training and validation set, a validation set is used to validate the models. A model with all possible combinations of hyperparameters is tested on the validation set to choose the best combination. Implementation: Grid Searching can be applied to any hyperparameters algorithm whose performance can be improved by tuning hyperparameter. For example, we can apply grid searching on K-Nearest Neighbors by validating its performance on a set of values of K in it. Same thing we can do with Logistic Regression by using a set of values of learning rate to find the best learning rate at which Logistic Regression achieves the best accuracy. Diabetes Dataset used in this implementation can be downloaded from link . It has 8 features columns like i.e “Age”, “Glucose” e.t.c, and the target variable “Outcome” for 108 patients. So in this, we will train a Logistic Regression Classifier model to predict the presence of diabetes or not for patients with such information. Code: Implementation of Grid Searching on Logistic Regression from Scratch Python3 # Importing libraries import numpy as npimport pandas as pdfrom sklearn.model_selection import train_test_split # Grid Searching in Logistic Regressionclass LogitRegression() : def __init__( self, learning_rate, iterations ) : self.learning_rate = learning_rate self.iterations = iterations # Function for model training def fit( self, X, Y ) : # no_of_training_examples, no_of_features self.m, self.n = X.shape # weight initialization self.W = np.zeros( self.n ) self.b = 0 self.X = X self.Y = Y # gradient descent learning for i in range( self.iterations ) : self.update_weights() return self # Helper function to update weights in gradient descent def update_weights( self ) : A = 1 / ( 1 + np.exp( - ( self.X.dot( self.W ) + self.b ) ) ) # calculate gradients tmp = ( A - self.Y.T ) tmp = np.reshape( tmp, self.m ) dW = np.dot( self.X.T, tmp ) / self.m db = np.sum( tmp ) / self.m # update weights self.W = self.W - self.learning_rate * dW self.b = self.b - self.learning_rate * db return self # Hypothetical function h( x ) def predict( self, X ) : Z = 1 / ( 1 + np.exp( - ( X.dot( self.W ) + self.b ) ) ) Y = np.where( Z > 0.5, 1, 0 ) return Y # Driver code def main() : # Importing dataset df = pd.read_csv( "diabetes.csv" ) X = df.iloc[:,:-1].values Y = df.iloc[:,-1:].values # Splitting dataset into train and validation set X_train, X_valid, Y_train, Y_valid = train_test_split( X, Y, test_size = 1/3, random_state = 0 ) # Model training max_accuracy = 0 # learning_rate choices learning_rates = [ 0.1, 0.2, 0.3, 0.4, 0.5, 0.01, 0.02, 0.03, 0.04, 0.05 ] # iterations choices iterations = [ 100, 200, 300, 400, 500 ] # available combination of learning_rate and iterations parameters = [] for i in learning_rates : for j in iterations : parameters.append( ( i, j ) ) print("Available combinations : ", parameters ) # Applying linear searching in list of available combination # to achieved maximum accuracy on CV set for k in range( len( parameters ) ) : model = LogitRegression( learning_rate = parameters[k][0], iterations = parameters[k][1] ) model.fit( X_train, Y_train ) # Prediction on validation set Y_pred = model.predict( X_valid ) # measure performance on validation set correctly_classified = 0 # counter count = 0 for count in range( np.size( Y_pred ) ) : if Y_valid[count] == Y_pred[count] : correctly_classified = correctly_classified + 1 curr_accuracy = ( correctly_classified / count ) * 100 if max_accuracy < curr_accuracy : max_accuracy = curr_accuracy print( "Maximum accuracy achieved by our model through grid searching : ", max_accuracy ) if __name__ == "__main__" : main() Output: Available combinations : [(0.1, 100), (0.1, 200), (0.1, 300), (0.1, 400), (0.1, 500), (0.2, 100), (0.2, 200), (0.2, 300), (0.2, 400), (0.2, 500), (0.3, 100), (0.3, 200), (0.3, 300), (0.3, 400), (0.3, 500), (0.4, 100), (0.4, 200), (0.4, 300), (0.4, 400), (0.4, 500), (0.5, 100), (0.5, 200), (0.5, 300), (0.5, 400), (0.5, 500), (0.01, 100), (0.01, 200), (0.01, 300), (0.01, 400), (0.01, 500), (0.02, 100), (0.02, 200), (0.02, 300), (0.02, 400), (0.02, 500), (0.03, 100), (0.03, 200), (0.03, 300), (0.03, 400), (0.03, 500), (0.04, 100), (0.04, 200), (0.04, 300), (0.04, 400), (0.04, 500), (0.05, 100), (0.05, 200), (0.05, 300), (0.05, 400), (0.05, 500)] Maximum accuracy achieved by our model through grid searching : 60.0 In the above, we applied grid searching on all possible combinations of learning rates and the number of iterations to find the peak of the model at which it achieves the highest accuracy. Code: Implementation of Grid Searching on Logistic Regression of sklearn Python3 # Importing Libraries import pandas as pdimport numpy as npfrom sklearn.linear_model import LogisticRegressionfrom sklearn.model_selection import GridSearchCV # Driver Code def main() : # Importing dataset df = pd.read_csv( "diabetes.csv" ) X = df.iloc[:,:-1].values Y = df.iloc[:,-1:].values # Splitting dataset into train and test set X_train, X_test, Y_train, Y_test = train_test_split( X, Y, test_size = 1/3, random_state = 0 ) # Model training max_accuracy = 0 # grid searching for learning rate parameters = { 'C' : [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] } model = LogisticRegression() grid = GridSearchCV( model, parameters ) grid.fit( X_train, Y_train ) # Prediction on test set Y_pred = grid.predict( X_test ) # measure performance correctly_classified = 0 # counter count = 0 for count in range( np.size( Y_pred ) ) : if Y_test[count] == Y_pred[count] : correctly_classified = correctly_classified + 1 accuracy = ( correctly_classified / count ) * 100 print( "Maximum accuracy achieved by sklearn model through grid searching : ", np.round( accuracy, 2 ) ) if __name__ == "__main__" : main() Output: Maximum accuracy achieved by sklearn model through grid searching : 62.86 Note: Grid Searching plays a vital role in tuning hyperparameters for the mathematically complex models. Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between Informed and Uninformed Search in AI Deploy Machine Learning Model using Flask Support Vector Machine Algorithm Types of Environments in AI k-nearest neighbor algorithm in Python Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 23953, "s": 23925, "text": "\n26 Nov, 2020" }, { "code": null, "e": 24366, "s": 23953, "text": "Grid searching is a method to find the best possible combination of hyper-parameters at which the model achieves the highest accuracy. Before applying Grid Searching on any algorithm, Data is used to divided into training and validation set, a validation set is used to validate the models. A model with all possible combinations of hyperparameters is tested on the validation set to choose the best combination." }, { "code": null, "e": 24382, "s": 24366, "text": "Implementation:" }, { "code": null, "e": 24806, "s": 24382, "text": "Grid Searching can be applied to any hyperparameters algorithm whose performance can be improved by tuning hyperparameter. For example, we can apply grid searching on K-Nearest Neighbors by validating its performance on a set of values of K in it. Same thing we can do with Logistic Regression by using a set of values of learning rate to find the best learning rate at which Logistic Regression achieves the best accuracy." }, { "code": null, "e": 24881, "s": 24806, "text": "Diabetes Dataset used in this implementation can be downloaded from link ." }, { "code": null, "e": 25136, "s": 24881, "text": "It has 8 features columns like i.e “Age”, “Glucose” e.t.c, and the target variable “Outcome” for 108 patients. So in this, we will train a Logistic Regression Classifier model to predict the presence of diabetes or not for patients with such information." }, { "code": null, "e": 25211, "s": 25136, "text": "Code: Implementation of Grid Searching on Logistic Regression from Scratch" }, { "code": null, "e": 25219, "s": 25211, "text": "Python3" }, { "code": "# Importing libraries import numpy as npimport pandas as pdfrom sklearn.model_selection import train_test_split # Grid Searching in Logistic Regressionclass LogitRegression() : def __init__( self, learning_rate, iterations ) : self.learning_rate = learning_rate self.iterations = iterations # Function for model training def fit( self, X, Y ) : # no_of_training_examples, no_of_features self.m, self.n = X.shape # weight initialization self.W = np.zeros( self.n ) self.b = 0 self.X = X self.Y = Y # gradient descent learning for i in range( self.iterations ) : self.update_weights() return self # Helper function to update weights in gradient descent def update_weights( self ) : A = 1 / ( 1 + np.exp( - ( self.X.dot( self.W ) + self.b ) ) ) # calculate gradients tmp = ( A - self.Y.T ) tmp = np.reshape( tmp, self.m ) dW = np.dot( self.X.T, tmp ) / self.m db = np.sum( tmp ) / self.m # update weights self.W = self.W - self.learning_rate * dW self.b = self.b - self.learning_rate * db return self # Hypothetical function h( x ) def predict( self, X ) : Z = 1 / ( 1 + np.exp( - ( X.dot( self.W ) + self.b ) ) ) Y = np.where( Z > 0.5, 1, 0 ) return Y # Driver code def main() : # Importing dataset df = pd.read_csv( \"diabetes.csv\" ) X = df.iloc[:,:-1].values Y = df.iloc[:,-1:].values # Splitting dataset into train and validation set X_train, X_valid, Y_train, Y_valid = train_test_split( X, Y, test_size = 1/3, random_state = 0 ) # Model training max_accuracy = 0 # learning_rate choices learning_rates = [ 0.1, 0.2, 0.3, 0.4, 0.5, 0.01, 0.02, 0.03, 0.04, 0.05 ] # iterations choices iterations = [ 100, 200, 300, 400, 500 ] # available combination of learning_rate and iterations parameters = [] for i in learning_rates : for j in iterations : parameters.append( ( i, j ) ) print(\"Available combinations : \", parameters ) # Applying linear searching in list of available combination # to achieved maximum accuracy on CV set for k in range( len( parameters ) ) : model = LogitRegression( learning_rate = parameters[k][0], iterations = parameters[k][1] ) model.fit( X_train, Y_train ) # Prediction on validation set Y_pred = model.predict( X_valid ) # measure performance on validation set correctly_classified = 0 # counter count = 0 for count in range( np.size( Y_pred ) ) : if Y_valid[count] == Y_pred[count] : correctly_classified = correctly_classified + 1 curr_accuracy = ( correctly_classified / count ) * 100 if max_accuracy < curr_accuracy : max_accuracy = curr_accuracy print( \"Maximum accuracy achieved by our model through grid searching : \", max_accuracy ) if __name__ == \"__main__\" : main()", "e": 28840, "s": 25219, "text": null }, { "code": null, "e": 28848, "s": 28840, "text": "Output:" }, { "code": null, "e": 29579, "s": 28848, "text": "Available combinations : [(0.1, 100), (0.1, 200), (0.1, 300), (0.1, 400), \n(0.1, 500), (0.2, 100), (0.2, 200), (0.2, 300), (0.2, 400), (0.2, 500), \n(0.3, 100), (0.3, 200), (0.3, 300), (0.3, 400), (0.3, 500), (0.4, 100), \n(0.4, 200), (0.4, 300), (0.4, 400), (0.4, 500), (0.5, 100), (0.5, 200), \n(0.5, 300), (0.5, 400), (0.5, 500), (0.01, 100), (0.01, 200), (0.01, 300),\n(0.01, 400), (0.01, 500), (0.02, 100), (0.02, 200), (0.02, 300), (0.02, 400), \n(0.02, 500), (0.03, 100), (0.03, 200), (0.03, 300), (0.03, 400), (0.03, 500), \n(0.04, 100), (0.04, 200), (0.04, 300), (0.04, 400), (0.04, 500), (0.05, 100), \n(0.05, 200), (0.05, 300), (0.05, 400), (0.05, 500)]\n\nMaximum accuracy achieved by our model through grid searching : 60.0\n" }, { "code": null, "e": 29768, "s": 29579, "text": "In the above, we applied grid searching on all possible combinations of learning rates and the number of iterations to find the peak of the model at which it achieves the highest accuracy." }, { "code": null, "e": 29841, "s": 29768, "text": "Code: Implementation of Grid Searching on Logistic Regression of sklearn" }, { "code": null, "e": 29849, "s": 29841, "text": "Python3" }, { "code": "# Importing Libraries import pandas as pdimport numpy as npfrom sklearn.linear_model import LogisticRegressionfrom sklearn.model_selection import GridSearchCV # Driver Code def main() : # Importing dataset df = pd.read_csv( \"diabetes.csv\" ) X = df.iloc[:,:-1].values Y = df.iloc[:,-1:].values # Splitting dataset into train and test set X_train, X_test, Y_train, Y_test = train_test_split( X, Y, test_size = 1/3, random_state = 0 ) # Model training max_accuracy = 0 # grid searching for learning rate parameters = { 'C' : [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] } model = LogisticRegression() grid = GridSearchCV( model, parameters ) grid.fit( X_train, Y_train ) # Prediction on test set Y_pred = grid.predict( X_test ) # measure performance correctly_classified = 0 # counter count = 0 for count in range( np.size( Y_pred ) ) : if Y_test[count] == Y_pred[count] : correctly_classified = correctly_classified + 1 accuracy = ( correctly_classified / count ) * 100 print( \"Maximum accuracy achieved by sklearn model through grid searching : \", np.round( accuracy, 2 ) ) if __name__ == \"__main__\" : main()", "e": 31196, "s": 29849, "text": null }, { "code": null, "e": 31204, "s": 31196, "text": "Output:" }, { "code": null, "e": 31280, "s": 31204, "text": "Maximum accuracy achieved by sklearn model through grid searching : 62.86\n" }, { "code": null, "e": 31385, "s": 31280, "text": "Note: Grid Searching plays a vital role in tuning hyperparameters for the mathematically complex models." }, { "code": null, "e": 31402, "s": 31385, "text": "Machine Learning" }, { "code": null, "e": 31409, "s": 31402, "text": "Python" }, { "code": null, "e": 31426, "s": 31409, "text": "Machine Learning" }, { "code": null, "e": 31524, "s": 31426, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31533, "s": 31524, "text": "Comments" }, { "code": null, "e": 31546, "s": 31533, "text": "Old Comments" }, { "code": null, "e": 31602, "s": 31546, "text": "Difference between Informed and Uninformed Search in AI" }, { "code": null, "e": 31644, "s": 31602, "text": "Deploy Machine Learning Model using Flask" }, { "code": null, "e": 31677, "s": 31644, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 31705, "s": 31677, "text": "Types of Environments in AI" }, { "code": null, "e": 31744, "s": 31705, "text": "k-nearest neighbor algorithm in Python" }, { "code": null, "e": 31772, "s": 31744, "text": "Read JSON file using Python" }, { "code": null, "e": 31822, "s": 31772, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 31844, "s": 31822, "text": "Python map() function" } ]
How to join or concatenate two lists in C#?
To concatenate two lists, use AddRange() method. Set the first list − var products1 = new List < string > (); products1.Add("Belts"); products1.Add("Tshirt"); products1.Add("Trousers"); Set the second list − var products2 = new List < string > (); products2.Add("Footwear"); products2.Add("Electronics"); To concatenate both the lists − products1.AddRange(products2); The following is the complete code − Live Demo using System.Collections.Generic; using System; namespace Demo { public static class Program { public static void Main() { var products1 = new List < string > (); products1.Add("Belts"); products1.Add("Tshirt"); products1.Add("Trousers"); Console.WriteLine("Our list1...."); foreach(var p in products1) { Console.WriteLine(p); } var products2 = new List < string > (); products2.Add("Footwear"); products2.Add("Electronics"); Console.WriteLine("Our list2...."); foreach(var p in products2) { Console.WriteLine(p); } products1.AddRange(products2); Console.WriteLine("Concatenated list...."); foreach(var p in products1) { Console.WriteLine(p); } } } } Our list1.... Belts Tshirt Trousers Our list2.... Footwear Electronics Concatenated list.... Belts Tshirt Trousers Footwear Electronics
[ { "code": null, "e": 1111, "s": 1062, "text": "To concatenate two lists, use AddRange() method." }, { "code": null, "e": 1132, "s": 1111, "text": "Set the first list −" }, { "code": null, "e": 1248, "s": 1132, "text": "var products1 = new List < string > ();\nproducts1.Add(\"Belts\");\nproducts1.Add(\"Tshirt\");\nproducts1.Add(\"Trousers\");" }, { "code": null, "e": 1270, "s": 1248, "text": "Set the second list −" }, { "code": null, "e": 1367, "s": 1270, "text": "var products2 = new List < string > ();\nproducts2.Add(\"Footwear\");\nproducts2.Add(\"Electronics\");" }, { "code": null, "e": 1399, "s": 1367, "text": "To concatenate both the lists −" }, { "code": null, "e": 1430, "s": 1399, "text": "products1.AddRange(products2);" }, { "code": null, "e": 1467, "s": 1430, "text": "The following is the complete code −" }, { "code": null, "e": 1478, "s": 1467, "text": " Live Demo" }, { "code": null, "e": 2340, "s": 1478, "text": "using System.Collections.Generic;\nusing System;\n\nnamespace Demo {\n public static class Program {\n public static void Main() {\n var products1 = new List < string > ();\n products1.Add(\"Belts\");\n products1.Add(\"Tshirt\");\n products1.Add(\"Trousers\");\n\n Console.WriteLine(\"Our list1....\");\n foreach(var p in products1) {\n Console.WriteLine(p);\n }\n\n var products2 = new List < string > ();\n products2.Add(\"Footwear\");\n products2.Add(\"Electronics\");\n\n Console.WriteLine(\"Our list2....\");\n foreach(var p in products2) {\n Console.WriteLine(p);\n }\n products1.AddRange(products2);\n Console.WriteLine(\"Concatenated list....\");\n foreach(var p in products1) {\n Console.WriteLine(p);\n }\n }\n }\n}" }, { "code": null, "e": 2476, "s": 2340, "text": "Our list1....\nBelts\nTshirt\nTrousers\nOur list2....\nFootwear\nElectronics\nConcatenated list....\nBelts\nTshirt\nTrousers\nFootwear\nElectronics" } ]
TensorFlow 2: How to use AutoEncoder for Interpolation | by Rahul Bhadani | Towards Data Science
Autoencoders are another Neural Network used to reproduce the inputs in a compressed fashion. Autoencoder has a special property in which the number of input neurons is the same as the number of output neurons. Look at the above image. The goal of Autoencoder is to create a representation of the input at the output layer such that both output and input are similar but the actual use of the Autoencoder is for determining a compressed version of the input data with the lowest amount of loss in data. This is very similar to what Principal Component Analysis does, in a black-box manner. Encoder part of Autoencoder compresses the data at the same time ensuring that the important data is not lost but the size of the data is reduced. The downside of using Autoencoder for interpolation is that the compressed data is a black box representation— we do not know the structure of the data in the compressed version. Suppose we have a dataset with 10 parameters and we train an Autoencoder over this data. The encoder does not omit some of the parameters for better representation but it fuses the parameters to create a compressed version but with fewer parameters (brings the number of parameters down to, say, 5 from 10). Autoencoder has two parts, encoder, and decoder. The encoder compresses the input data and the decoder does the opposite to produce the uncompressed version of the data to produce a reconstructed input as close to the original one as possible. Interpolation is a process of guessing the value of a function between two data points. For example, you are given x = [1, 3, 5, 7, 9], and y = [230.02, 321.01, 305.00, 245.75, 345.62], and based on the given data you want to know the value of y given x = 4. There are plenty of interpolation methods available in the literature — some model-based and some are model-free, i.e. data-driven. The most common way of achieving interpolation is through data-fitting. As an example, you use linear regression analysis to fit a linear model to the given data. In linear regression, given the explanatory/predictor variable, X, and the response variable, Y, the data is fitted using the formula Y = β0 + β1X where β0 and β1 are determined using least square fit. As the name suggests, linear regression is linear, i.e., it fits a straight line even though the relationship between predictor and response variable might be non-linear. However, the most general form of interpolation is polynomial fitting. Given k sample points, it is straightforward to fit a polynomial of degree k -1. Given the data set {xi, yi}, the polynomial fitting is obtained by determining polynomial coefficients ai of function by solving matrix inversion from the following expression: Once we have coefficients ai, we can find the value of function f for any x. There are some specific cases of polynomial fitting where a piecewise cubic polynomial is fitted to data. A few other non-parametric methods include cubic spline, smoothing splines, regression splines, kernel regression, and density estimation. However, the point of this article is not polynomial fitting, but rather interpolation. Polynomial fitting just happens to facilitate interpolation. However, there is an issue with polynomial fitting methods — whether it is parametric or non-parametric, they behave the way they are taught. What it means is that if data is clean, the fitting will be clean and smooth, but if data is noisy, the fitting will be noisy. This issue is more prevalent in sensor data, for example, hear-beat data captured from your heart-rate sensor, distance data from LiDAR, CAN Bus speed data from your car, GPS data, etc. medium.com Further, because of the noise, they are harder to deal with, especially if your algorithm requires performing double, or second derivative on such data. In general, those sensor data are timeseries data, i.e. they are collected over time, thus the response variable might be some physical quantity such as speed, the distance of objects from LiDAR mounted on the top of a self-driving car, heart-rate, and predictor variable is time. While operating on such data, there can be a few objectives: I want to have data interpolated to some time-stamp over which my sensor couldn’t record any response, but since sensors operate in the real-time world and because of the underlying physics, those data stay noisy, I also want a reliable interpolation that is not impacted by sensor noise. Further, my requirement may also include derivatives of such timeseries data. Derivatives tend to amplify the noise present in the underlying timeseries data. What if there is a way by which I can get an underlying representation of the data, discarding the noise at the same time? Autoencoder comes to the rescue to achieve my objective in such a case. To demonstrate the denoising + interpolation objective using Autoencoder, I use an example of distance data collected from a vehicle by my lab, where the response variable is the distance of the vehicle ahead of my vehicle, and the predictor is time. I have made a small subset of the data available on my GitHub repo as a part of the demonstration that you are free to use. However, it is really small and serves no purpose beyond the tutorial described in this article. github.com Okay, it is time to code now. Note: Before you use data, I should point out that the time (predictor) and message (response) must be re-scaled. In my case, the original time starts from 1594247088.289515 (in POSIX format, in seconds) and ends at 1594247110.290019. I normalized my time value using the formula (time - start_time)/(end_time - start_time). Similarly, the response variable was normalized using (message - message_min)/(message_max -message_min). The sample data provided in my GitHub is already normalized and you can reuse it out of the box. import globimport numpy as npimport matplotlib.pyplot as pltimport pandas as pdimport numpy as npdf = pd.read_csv("../data/lead_dist_sample.csv")time = df['Time']message = df['Message']import tensorflow as tfmodel = tf.keras.Sequential()model.add(tf.keras.layers.Dense(units = 1, activation = 'linear', input_shape=[1]))model.add(tf.keras.layers.Dense(units = 128, activation = 'relu'))model.add(tf.keras.layers.Dense(units = 64, activation = 'relu'))model.add(tf.keras.layers.Dense(units = 32, activation = 'relu'))model.add(tf.keras.layers.Dense(units = 64, activation = 'relu'))model.add(tf.keras.layers.Dense(units = 128, activation = 'relu'))model.add(tf.keras.layers.Dense(units = 1, activation = 'linear'))model.compile(loss='mse', optimizer="adam")model.summary()# Trainingmodel.fit( time, message, epochs=1000, verbose=True) As you can see, I have not performed any regularization as I deliberately want to do overfitting so that I can use the underlying nature of data to the full extent. Now it’s time to make a prediction. You will see that I rescaled back the time axis to original values before making predictions. For this example, I hadtime_original[0] = 1594247088.289515 ,time_original[-1] = 1594247110.290019 , msg_min = 33, msg_max = 112 newtimepoints_scaled = np.linspace(time[0] - (time[1] - time[0]),time[-1], 10000)y_predicted_scaled = model.predict(newtimepoints_scaled)newtimepoints = newtimepoints_scaled*(time_original[-1] - time_original[0]) + time_original[0]y_predicted = y_predicted_scaled*(msg_max - msg_min) + msg_min Note that I am creating much denser time-points in variable newtimepoints_scaled which allows me to interpolate data on unseen time-points. Finally, here is the curve: # Display the resultimport matplotlib.pylab as pylabparams = {'legend.fontsize': 'x-large', 'figure.figsize': (15, 5), 'axes.labelsize': 'x-large', 'axes.titlesize':'x-large', 'xtick.labelsize':'x-large', 'ytick.labelsize':'x-large'}pylab.rcParams.update(params)plt.scatter(time*(1594247110.290019 - 1594247088.289515) + 1594247088.289515, message*(112 - 33) + 33, label='Original Data')plt.scatter(newtimepoints, y_predicted, c = 'red', s = 1, label = 'Interpolated Data')plt.xlabel('Time')plt.ylabel('Message')plt.legend()plt.show() While I trained for only 1000 epochs, your training might not be that short, if your data is big. The biggest advantage of this method is taking derivatives, as from the following plot, it is clear that the derivative performed on the original data is poor — may not even represent the true derivative! df_interpolation = pd.DataFrame()df_interpolation['Time'] = newtimepointsdf_interpolation['Message'] = y_predicteddf_interpolation['diff'] = df_interpolation['Message'].diff()/df_interpolation['Time'].diff()df_original = pd.DataFrame()df_original['Time'] = time*(1594247110.290019 - 1594247088.289515) + 1594247088.289515df_original['Message'] = message*(112 - 33) + 33df_original['diff'] = df_original['Message'].diff()/df_original['Time'].diff()# Display the resultimport matplotlib.pylab as pylabparams = {'legend.fontsize': 'x-large', 'figure.figsize': (15, 5), 'axes.labelsize': 'x-large', 'axes.titlesize':'x-large', 'xtick.labelsize':'x-large', 'ytick.labelsize':'x-large'}pylab.rcParams.update(params)plt.scatter(df_original['Time'], df_original['diff'], label='Derivative on Original Data')plt.scatter(df_interpolation['Time'], df_interpolation['diff'], s= 10, c = 'red', label='Derivative on Interpolated Data')plt.xlabel('Time')plt.ylabel('Message')plt.legend()plt.show() The only downside of this method is time-complexity. Depending on the number of data points, it may take hours before your training is complete. However, if you have access to High-Performance Computing clusters, Amazon EC2, or likewise, it may not take too much time to train your Autoencoder. The notebook to reproduce this tutorial can be found on my GitHub at https://github.com/rahulbhadani/medium.com/blob/master/01_02_2021/AutoEncoder_Interpolation_TF2.ipynb. A longer version of the article is posted on ArXiv.org. If this article benefits you, please use the following citations for referencing my work: Rahul Bhadani. Autoencoder for interpolation. arXiv preprint arXiv:2101.00853, 2021. or @article{bhadani2021autoencoder, title={AutoEncoder for Interpolation}, author={Rahul Bhadani}, year={2021}, eprint={2101.00853}, archivePrefix={arXiv}, primaryClass={stat.ML}, journal={arXiv preprint arXiv:2101.00853},} If you like this article, you will want to learn more about how to use TensorFlow 2. Check some of my other articles on TensorFlow 2:
[ { "code": null, "e": 382, "s": 171, "text": "Autoencoders are another Neural Network used to reproduce the inputs in a compressed fashion. Autoencoder has a special property in which the number of input neurons is the same as the number of output neurons." }, { "code": null, "e": 908, "s": 382, "text": "Look at the above image. The goal of Autoencoder is to create a representation of the input at the output layer such that both output and input are similar but the actual use of the Autoencoder is for determining a compressed version of the input data with the lowest amount of loss in data. This is very similar to what Principal Component Analysis does, in a black-box manner. Encoder part of Autoencoder compresses the data at the same time ensuring that the important data is not lost but the size of the data is reduced." }, { "code": null, "e": 1639, "s": 908, "text": "The downside of using Autoencoder for interpolation is that the compressed data is a black box representation— we do not know the structure of the data in the compressed version. Suppose we have a dataset with 10 parameters and we train an Autoencoder over this data. The encoder does not omit some of the parameters for better representation but it fuses the parameters to create a compressed version but with fewer parameters (brings the number of parameters down to, say, 5 from 10). Autoencoder has two parts, encoder, and decoder. The encoder compresses the input data and the decoder does the opposite to produce the uncompressed version of the data to produce a reconstructed input as close to the original one as possible." }, { "code": null, "e": 2193, "s": 1639, "text": "Interpolation is a process of guessing the value of a function between two data points. For example, you are given x = [1, 3, 5, 7, 9], and y = [230.02, 321.01, 305.00, 245.75, 345.62], and based on the given data you want to know the value of y given x = 4. There are plenty of interpolation methods available in the literature — some model-based and some are model-free, i.e. data-driven. The most common way of achieving interpolation is through data-fitting. As an example, you use linear regression analysis to fit a linear model to the given data." }, { "code": null, "e": 2566, "s": 2193, "text": "In linear regression, given the explanatory/predictor variable, X, and the response variable, Y, the data is fitted using the formula Y = β0 + β1X where β0 and β1 are determined using least square fit. As the name suggests, linear regression is linear, i.e., it fits a straight line even though the relationship between predictor and response variable might be non-linear." }, { "code": null, "e": 2836, "s": 2566, "text": "However, the most general form of interpolation is polynomial fitting. Given k sample points, it is straightforward to fit a polynomial of degree k -1. Given the data set {xi, yi}, the polynomial fitting is obtained by determining polynomial coefficients ai of function" }, { "code": null, "e": 2895, "s": 2836, "text": "by solving matrix inversion from the following expression:" }, { "code": null, "e": 2972, "s": 2895, "text": "Once we have coefficients ai, we can find the value of function f for any x." }, { "code": null, "e": 3217, "s": 2972, "text": "There are some specific cases of polynomial fitting where a piecewise cubic polynomial is fitted to data. A few other non-parametric methods include cubic spline, smoothing splines, regression splines, kernel regression, and density estimation." }, { "code": null, "e": 3821, "s": 3217, "text": "However, the point of this article is not polynomial fitting, but rather interpolation. Polynomial fitting just happens to facilitate interpolation. However, there is an issue with polynomial fitting methods — whether it is parametric or non-parametric, they behave the way they are taught. What it means is that if data is clean, the fitting will be clean and smooth, but if data is noisy, the fitting will be noisy. This issue is more prevalent in sensor data, for example, hear-beat data captured from your heart-rate sensor, distance data from LiDAR, CAN Bus speed data from your car, GPS data, etc." }, { "code": null, "e": 3832, "s": 3821, "text": "medium.com" }, { "code": null, "e": 4970, "s": 3832, "text": "Further, because of the noise, they are harder to deal with, especially if your algorithm requires performing double, or second derivative on such data. In general, those sensor data are timeseries data, i.e. they are collected over time, thus the response variable might be some physical quantity such as speed, the distance of objects from LiDAR mounted on the top of a self-driving car, heart-rate, and predictor variable is time. While operating on such data, there can be a few objectives: I want to have data interpolated to some time-stamp over which my sensor couldn’t record any response, but since sensors operate in the real-time world and because of the underlying physics, those data stay noisy, I also want a reliable interpolation that is not impacted by sensor noise. Further, my requirement may also include derivatives of such timeseries data. Derivatives tend to amplify the noise present in the underlying timeseries data. What if there is a way by which I can get an underlying representation of the data, discarding the noise at the same time? Autoencoder comes to the rescue to achieve my objective in such a case." }, { "code": null, "e": 5442, "s": 4970, "text": "To demonstrate the denoising + interpolation objective using Autoencoder, I use an example of distance data collected from a vehicle by my lab, where the response variable is the distance of the vehicle ahead of my vehicle, and the predictor is time. I have made a small subset of the data available on my GitHub repo as a part of the demonstration that you are free to use. However, it is really small and serves no purpose beyond the tutorial described in this article." }, { "code": null, "e": 5453, "s": 5442, "text": "github.com" }, { "code": null, "e": 5483, "s": 5453, "text": "Okay, it is time to code now." }, { "code": null, "e": 6011, "s": 5483, "text": "Note: Before you use data, I should point out that the time (predictor) and message (response) must be re-scaled. In my case, the original time starts from 1594247088.289515 (in POSIX format, in seconds) and ends at 1594247110.290019. I normalized my time value using the formula (time - start_time)/(end_time - start_time). Similarly, the response variable was normalized using (message - message_min)/(message_max -message_min). The sample data provided in my GitHub is already normalized and you can reuse it out of the box." }, { "code": null, "e": 6845, "s": 6011, "text": "import globimport numpy as npimport matplotlib.pyplot as pltimport pandas as pdimport numpy as npdf = pd.read_csv(\"../data/lead_dist_sample.csv\")time = df['Time']message = df['Message']import tensorflow as tfmodel = tf.keras.Sequential()model.add(tf.keras.layers.Dense(units = 1, activation = 'linear', input_shape=[1]))model.add(tf.keras.layers.Dense(units = 128, activation = 'relu'))model.add(tf.keras.layers.Dense(units = 64, activation = 'relu'))model.add(tf.keras.layers.Dense(units = 32, activation = 'relu'))model.add(tf.keras.layers.Dense(units = 64, activation = 'relu'))model.add(tf.keras.layers.Dense(units = 128, activation = 'relu'))model.add(tf.keras.layers.Dense(units = 1, activation = 'linear'))model.compile(loss='mse', optimizer=\"adam\")model.summary()# Trainingmodel.fit( time, message, epochs=1000, verbose=True)" }, { "code": null, "e": 7269, "s": 6845, "text": "As you can see, I have not performed any regularization as I deliberately want to do overfitting so that I can use the underlying nature of data to the full extent. Now it’s time to make a prediction. You will see that I rescaled back the time axis to original values before making predictions. For this example, I hadtime_original[0] = 1594247088.289515 ,time_original[-1] = 1594247110.290019 , msg_min = 33, msg_max = 112" }, { "code": null, "e": 7563, "s": 7269, "text": "newtimepoints_scaled = np.linspace(time[0] - (time[1] - time[0]),time[-1], 10000)y_predicted_scaled = model.predict(newtimepoints_scaled)newtimepoints = newtimepoints_scaled*(time_original[-1] - time_original[0]) + time_original[0]y_predicted = y_predicted_scaled*(msg_max - msg_min) + msg_min" }, { "code": null, "e": 7731, "s": 7563, "text": "Note that I am creating much denser time-points in variable newtimepoints_scaled which allows me to interpolate data on unseen time-points. Finally, here is the curve:" }, { "code": null, "e": 8307, "s": 7731, "text": "# Display the resultimport matplotlib.pylab as pylabparams = {'legend.fontsize': 'x-large', 'figure.figsize': (15, 5), 'axes.labelsize': 'x-large', 'axes.titlesize':'x-large', 'xtick.labelsize':'x-large', 'ytick.labelsize':'x-large'}pylab.rcParams.update(params)plt.scatter(time*(1594247110.290019 - 1594247088.289515) + 1594247088.289515, message*(112 - 33) + 33, label='Original Data')plt.scatter(newtimepoints, y_predicted, c = 'red', s = 1, label = 'Interpolated Data')plt.xlabel('Time')plt.ylabel('Message')plt.legend()plt.show()" }, { "code": null, "e": 8610, "s": 8307, "text": "While I trained for only 1000 epochs, your training might not be that short, if your data is big. The biggest advantage of this method is taking derivatives, as from the following plot, it is clear that the derivative performed on the original data is poor — may not even represent the true derivative!" }, { "code": null, "e": 9635, "s": 8610, "text": "df_interpolation = pd.DataFrame()df_interpolation['Time'] = newtimepointsdf_interpolation['Message'] = y_predicteddf_interpolation['diff'] = df_interpolation['Message'].diff()/df_interpolation['Time'].diff()df_original = pd.DataFrame()df_original['Time'] = time*(1594247110.290019 - 1594247088.289515) + 1594247088.289515df_original['Message'] = message*(112 - 33) + 33df_original['diff'] = df_original['Message'].diff()/df_original['Time'].diff()# Display the resultimport matplotlib.pylab as pylabparams = {'legend.fontsize': 'x-large', 'figure.figsize': (15, 5), 'axes.labelsize': 'x-large', 'axes.titlesize':'x-large', 'xtick.labelsize':'x-large', 'ytick.labelsize':'x-large'}pylab.rcParams.update(params)plt.scatter(df_original['Time'], df_original['diff'], label='Derivative on Original Data')plt.scatter(df_interpolation['Time'], df_interpolation['diff'], s= 10, c = 'red', label='Derivative on Interpolated Data')plt.xlabel('Time')plt.ylabel('Message')plt.legend()plt.show()" }, { "code": null, "e": 9930, "s": 9635, "text": "The only downside of this method is time-complexity. Depending on the number of data points, it may take hours before your training is complete. However, if you have access to High-Performance Computing clusters, Amazon EC2, or likewise, it may not take too much time to train your Autoencoder." }, { "code": null, "e": 9999, "s": 9930, "text": "The notebook to reproduce this tutorial can be found on my GitHub at" }, { "code": null, "e": 10102, "s": 9999, "text": "https://github.com/rahulbhadani/medium.com/blob/master/01_02_2021/AutoEncoder_Interpolation_TF2.ipynb." }, { "code": null, "e": 10158, "s": 10102, "text": "A longer version of the article is posted on ArXiv.org." }, { "code": null, "e": 10248, "s": 10158, "text": "If this article benefits you, please use the following citations for referencing my work:" }, { "code": null, "e": 10333, "s": 10248, "text": "Rahul Bhadani. Autoencoder for interpolation. arXiv preprint arXiv:2101.00853, 2021." }, { "code": null, "e": 10336, "s": 10333, "text": "or" }, { "code": null, "e": 10576, "s": 10336, "text": "@article{bhadani2021autoencoder, title={AutoEncoder for Interpolation}, author={Rahul Bhadani}, year={2021}, eprint={2101.00853}, archivePrefix={arXiv}, primaryClass={stat.ML}, journal={arXiv preprint arXiv:2101.00853},}" } ]
GATE | GATE-CS-2007 | Question 85 - GeeksforGeeks
14 Sep, 2021 Consider the following two statements: P: Every regular grammar is LL(1) Q: Every regular set has a LR(1) grammar Which of the following is TRUE?(A) Both P and Q are true(B) P is true and Q is false(C) P is false and Q is true(D) Both P and Q are falseAnswer: (C)Explanation: A regular grammar can also be ambiguous also For example, consider the following grammar, S → aA/a A → aA/ε In above grammar, string 'a' has two leftmost derivations. (1) S → aA (2) S → a S->a (using A->ε) And LL(1) parses only unambiguous grammar, so statement P is False. Statement Q is true is for every regular set, we can have a regular grammar which is unambiguous so it can be parse by LR parser. So option C is correct choice YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersPYQ - Parsing and SDT (Continued) Part 4 with Joyojyoti Acharya | GeeksforGeeks GATEWatch 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:0027:46 / 58:40•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=LdMTs93sekg" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question GATE-CS-2007 GATE-GATE-CS-2007 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments GATE | GATE-CS-2016 (Set 2) | Question 48 GATE | GATE-CS-2014-(Set-1) | Question 30 GATE | GATE-CS-2001 | Question 23 GATE | GATE-CS-2015 (Set 1) | Question 65 GATE | GATE CS 2010 | Question 45 GATE | GATE-CS-2015 (Set 3) | Question 65 C++ Program to count Vowels in a string using Pointer GATE | GATE-CS-2014-(Set-1) | Question 65 GATE | GATE-CS-2004 | Question 3 GATE | GATE-CS-2015 (Set 1) | Question 42
[ { "code": null, "e": 24041, "s": 24013, "text": "\n14 Sep, 2021" }, { "code": null, "e": 24080, "s": 24041, "text": "Consider the following two statements:" }, { "code": null, "e": 24155, "s": 24080, "text": "P: Every regular grammar is LL(1)\nQ: Every regular set has a LR(1) grammar" }, { "code": null, "e": 24317, "s": 24155, "text": "Which of the following is TRUE?(A) Both P and Q are true(B) P is true and Q is false(C) P is false and Q is true(D) Both P and Q are falseAnswer: (C)Explanation:" }, { "code": null, "e": 24815, "s": 24317, "text": "A regular grammar can also be ambiguous also\nFor example, consider the following grammar, \nS → aA/a\nA → aA/ε\nIn above grammar, string 'a' has two leftmost\nderivations. \n(1) S → aA (2) S → a\n S->a (using A->ε)\nAnd LL(1) parses only unambiguous grammar,\nso statement P is False.\nStatement Q is true is for every regular set, we can have a regular\ngrammar which is unambiguous so it can be parse by LR parser. \n\nSo option C is correct choice " }, { "code": null, "e": 25728, "s": 24815, "text": "YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersPYQ - Parsing and SDT (Continued) Part 4 with Joyojyoti Acharya | GeeksforGeeks GATEWatch 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:0027:46 / 58:40•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=LdMTs93sekg\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question" }, { "code": null, "e": 25741, "s": 25728, "text": "GATE-CS-2007" }, { "code": null, "e": 25759, "s": 25741, "text": "GATE-GATE-CS-2007" }, { "code": null, "e": 25764, "s": 25759, "text": "GATE" }, { "code": null, "e": 25862, "s": 25764, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25871, "s": 25862, "text": "Comments" }, { "code": null, "e": 25884, "s": 25871, "text": "Old Comments" }, { "code": null, "e": 25926, "s": 25884, "text": "GATE | GATE-CS-2016 (Set 2) | Question 48" }, { "code": null, "e": 25968, "s": 25926, "text": "GATE | GATE-CS-2014-(Set-1) | Question 30" }, { "code": null, "e": 26002, "s": 25968, "text": "GATE | GATE-CS-2001 | Question 23" }, { "code": null, "e": 26044, "s": 26002, "text": "GATE | GATE-CS-2015 (Set 1) | Question 65" }, { "code": null, "e": 26078, "s": 26044, "text": "GATE | GATE CS 2010 | Question 45" }, { "code": null, "e": 26120, "s": 26078, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 26174, "s": 26120, "text": "C++ Program to count Vowels in a string using Pointer" }, { "code": null, "e": 26216, "s": 26174, "text": "GATE | GATE-CS-2014-(Set-1) | Question 65" }, { "code": null, "e": 26249, "s": 26216, "text": "GATE | GATE-CS-2004 | Question 3" } ]
ReactJS Reactstrap Nav Component - GeeksforGeeks
29 Jul, 2021 Reactstrap is a popular front-end library that is easy to use React Bootstrap 4 components. This library contains the stateless React components for Bootstrap 4. The Nav component allows the user to provide a list of various forms of navigation menus. We can use the following approach in ReactJS to use the ReactJS Reactstrap Nav Component. Nav Props: tabs: It is used to indicate whether to apply the tabs styles to it or not. pills: It is used to denote the Pills navigation. card: It is used to indicate whether to apply the card styles to it or not. justified: It makes NavItems fill all available widths. fill: It makes NavItems proportionately fill all available widths. vertical: It is used to indicate whether to apply the vertical alignment or not. horizontal: It is used to indicate whether to apply the horizontal alignment or not. navbar: It is used to apply to style an alignment for use in a Navbar. tag: It is used to pass in custom elements to use. NavItem Props: tag: It is used to pass in custom elements to use. active: It is used to apply the active state class to this component. NavLink Props: disabled: It is used to apply the disabled state class to this component. active: It is used to apply the active state class to this component. tag: It is used to pass in custom elements to use. innerRef: It is used to get a reference to the DOM element. Creating React Application And Installing Module: Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Step 3: After creating the ReactJS application, Install the required module using the following command: npm install reactstrap bootstrap Project Structure: It will look like the following. Project Structure Example 1: Now write down the following code in the App.js file. Here, we have used the pills props and shown Nav in horizontal alignment. Javascript import React from 'react'import 'bootstrap/dist/css/bootstrap.min.css';import { Nav, NavItem, NavLink } from "reactstrap" function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Reactstrap Nav Component</h4> <Nav pills> <NavItem> <NavLink href="#" active>Dashboard</NavLink> </NavItem> <NavItem> <NavLink href="#">Login</NavLink> </NavItem> <NavItem> <NavLink href="#">Signup</NavLink> </NavItem> <NavItem> <NavLink disabled href="#">About us</NavLink> </NavItem> </Nav> </div > );} export default App; Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Example 2: Now write down the following code in the App.js file. Here, we have used the vertical props to display Nav in vertical alignment. Javascript import React from 'react'import 'bootstrap/dist/css/bootstrap.min.css';import { Nav, NavItem, NavLink } from "reactstrap" function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Reactstrap Nav Component</h4> <Nav vertical> <NavItem> <NavLink href="#" active>Dashboard</NavLink> </NavItem> <NavItem> <NavLink href="#">Login</NavLink> </NavItem> <NavItem> <NavLink href="#">Signup</NavLink> </NavItem> <NavItem> <NavLink disabled href="#">About us</NavLink> </NavItem> </Nav> </div > );} export default App; Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Reference: https://reactstrap.github.io/components/navs/ Reactstrap JavaScript ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to get character array from string in JavaScript? How to fetch data from an API in ReactJS ? How to redirect to another page in ReactJS ? How to pass data from child component to its parent in ReactJS ? How to pass data from one component to other component in ReactJS ? ReactJS Functional Components
[ { "code": null, "e": 26667, "s": 26639, "text": "\n29 Jul, 2021" }, { "code": null, "e": 27009, "s": 26667, "text": "Reactstrap is a popular front-end library that is easy to use React Bootstrap 4 components. This library contains the stateless React components for Bootstrap 4. The Nav component allows the user to provide a list of various forms of navigation menus. We can use the following approach in ReactJS to use the ReactJS Reactstrap Nav Component." }, { "code": null, "e": 27020, "s": 27009, "text": "Nav Props:" }, { "code": null, "e": 27097, "s": 27020, "text": "tabs: It is used to indicate whether to apply the tabs styles to it or not. " }, { "code": null, "e": 27147, "s": 27097, "text": "pills: It is used to denote the Pills navigation." }, { "code": null, "e": 27223, "s": 27147, "text": "card: It is used to indicate whether to apply the card styles to it or not." }, { "code": null, "e": 27279, "s": 27223, "text": "justified: It makes NavItems fill all available widths." }, { "code": null, "e": 27347, "s": 27279, "text": "fill: It makes NavItems proportionately fill all available widths. " }, { "code": null, "e": 27428, "s": 27347, "text": "vertical: It is used to indicate whether to apply the vertical alignment or not." }, { "code": null, "e": 27513, "s": 27428, "text": "horizontal: It is used to indicate whether to apply the horizontal alignment or not." }, { "code": null, "e": 27584, "s": 27513, "text": "navbar: It is used to apply to style an alignment for use in a Navbar." }, { "code": null, "e": 27635, "s": 27584, "text": "tag: It is used to pass in custom elements to use." }, { "code": null, "e": 27650, "s": 27635, "text": "NavItem Props:" }, { "code": null, "e": 27701, "s": 27650, "text": "tag: It is used to pass in custom elements to use." }, { "code": null, "e": 27771, "s": 27701, "text": "active: It is used to apply the active state class to this component." }, { "code": null, "e": 27786, "s": 27771, "text": "NavLink Props:" }, { "code": null, "e": 27860, "s": 27786, "text": "disabled: It is used to apply the disabled state class to this component." }, { "code": null, "e": 27930, "s": 27860, "text": "active: It is used to apply the active state class to this component." }, { "code": null, "e": 27981, "s": 27930, "text": "tag: It is used to pass in custom elements to use." }, { "code": null, "e": 28041, "s": 27981, "text": "innerRef: It is used to get a reference to the DOM element." }, { "code": null, "e": 28093, "s": 28043, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 28157, "s": 28093, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 28189, "s": 28157, "text": "npx create-react-app foldername" }, { "code": null, "e": 28289, "s": 28189, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 28303, "s": 28289, "text": "cd foldername" }, { "code": null, "e": 28408, "s": 28303, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:" }, { "code": null, "e": 28441, "s": 28408, "text": "npm install reactstrap bootstrap" }, { "code": null, "e": 28493, "s": 28441, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 28511, "s": 28493, "text": "Project Structure" }, { "code": null, "e": 28650, "s": 28511, "text": "Example 1: Now write down the following code in the App.js file. Here, we have used the pills props and shown Nav in horizontal alignment." }, { "code": null, "e": 28661, "s": 28650, "text": "Javascript" }, { "code": "import React from 'react'import 'bootstrap/dist/css/bootstrap.min.css';import { Nav, NavItem, NavLink } from \"reactstrap\" function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Reactstrap Nav Component</h4> <Nav pills> <NavItem> <NavLink href=\"#\" active>Dashboard</NavLink> </NavItem> <NavItem> <NavLink href=\"#\">Login</NavLink> </NavItem> <NavItem> <NavLink href=\"#\">Signup</NavLink> </NavItem> <NavItem> <NavLink disabled href=\"#\">About us</NavLink> </NavItem> </Nav> </div > );} export default App;", "e": 29477, "s": 28661, "text": null }, { "code": null, "e": 29592, "s": 29479, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 29602, "s": 29592, "text": "npm start" }, { "code": null, "e": 29701, "s": 29602, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 29842, "s": 29701, "text": "Example 2: Now write down the following code in the App.js file. Here, we have used the vertical props to display Nav in vertical alignment." }, { "code": null, "e": 29853, "s": 29842, "text": "Javascript" }, { "code": "import React from 'react'import 'bootstrap/dist/css/bootstrap.min.css';import { Nav, NavItem, NavLink } from \"reactstrap\" function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>ReactJS Reactstrap Nav Component</h4> <Nav vertical> <NavItem> <NavLink href=\"#\" active>Dashboard</NavLink> </NavItem> <NavItem> <NavLink href=\"#\">Login</NavLink> </NavItem> <NavItem> <NavLink href=\"#\">Signup</NavLink> </NavItem> <NavItem> <NavLink disabled href=\"#\">About us</NavLink> </NavItem> </Nav> </div > );} export default App;", "e": 30672, "s": 29853, "text": null }, { "code": null, "e": 30785, "s": 30672, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 30795, "s": 30785, "text": "npm start" }, { "code": null, "e": 30894, "s": 30795, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 30951, "s": 30894, "text": "Reference: https://reactstrap.github.io/components/navs/" }, { "code": null, "e": 30962, "s": 30951, "text": "Reactstrap" }, { "code": null, "e": 30973, "s": 30962, "text": "JavaScript" }, { "code": null, "e": 30981, "s": 30973, "text": "ReactJS" }, { "code": null, "e": 30998, "s": 30981, "text": "Web Technologies" }, { "code": null, "e": 31096, "s": 30998, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31136, "s": 31096, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 31197, "s": 31136, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 31238, "s": 31197, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 31260, "s": 31238, "text": "JavaScript | Promises" }, { "code": null, "e": 31314, "s": 31260, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 31357, "s": 31314, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 31402, "s": 31357, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 31467, "s": 31402, "text": "How to pass data from child component to its parent in ReactJS ?" }, { "code": null, "e": 31535, "s": 31467, "text": "How to pass data from one component to other component in ReactJS ?" } ]
p5.js | rectMode() Function - GeeksforGeeks
29 May, 2020 The rectMode() function in p5.js is used to change the way in which the parameters given to the rect() function are interpreted. This modifies the location from where the rectangle is drawn. This function can be given four modes: CORNER: This mode interprets the first two parameters as the upper-left corner of the shape. The third and fourth parameters are its width and height. It is the default mode. CORNERS:This mode interprets the first two parameters as the upper-left corner and the other two parameters as the location of the opposite corner. CENTER: This mode interprets the first two parameters as the shape’s center point. The third and fourth parameters specify the shape’s width and height. RADIUS:This mode interprets the first two parameters as the shape’s center point. The third and fourth parameters specify half of the shape’s width and height. Syntax: rectMode( mode ) Parameters: This function accepts a single parameter as mentioned above and described below. mode: It is a Constant which defines which mode to use. It can have the values of CORNER, CORNERS, CENTER, or RADIUS. The examples below illustrate the rectMode() function in p5.js: Example: let currMode; function setup() { createCanvas(500, 400); textSize(16); // Define all the rectModes() let rectModes = [CORNER, CORNERS, CENTER, RADIUS]; let index = 0; currMode = rectModes[index]; // Define a button to switch between the modes let closeBtn = createButton("Change rectMode"); closeBtn.position(220, 40); closeBtn.mouseClicked(() => { if (index < rectModes.length - 1) index++; else index = 0; currMode = rectModes[index]; });} function draw() { clear(); text("Click on the button to"+ " change the rectMode()", 20, 20); fill("green"); // Draw the first rectangle with default mode rectMode(CORNER); rect(100, 100, 100, 100); fill("red"); // Set the rectMode according to the defined mode rectMode(currMode); // Draw the second rectangle according to the // selected rectMode() and different dimensions rect(100, 100, 50, 50); // Draw circles to demonstrate corners of // the first rectangle circle(100, 100, 10); circle(200, 100, 10); circle(100, 200, 10); circle(200, 200, 10); fill("black"); text("Current Mode: " + currMode, 20, 250); // Show details of parameter according to selected mode switch (currMode) { case CORNER: text("1st Parameter: upper-left"+ " corner x coord", 20, 280); text("2nd Parameter: upper-left"+ " corner y coord", 20, 300); text("3rd Parameter: width", 20, 320); text("4th Parameter: height", 20, 340); break; case CORNERS: text("1st Parameter: upper-left corner"+ " x coord", 20, 280); text("2nd Parameter: upper-left corner"+ " y coord", 20, 300); text("3rd Parameter: opposite corner x", 20, 320); text("4th Parameter: opposite corner y", 20, 340); break; case CENTER: text("1st Parameter: shape's center"+ " point x coord", 20, 280); text("2nd Parameter: shape's center"+ " point y coord", 20, 300); text("3rd Parameter: width", 20, 320); text("4th Parameter: height", 20, 340); break; case RADIUS: text("1st Parameter: shape's center"+ " point x coord", 20, 280); text("2nd Parameter: shape's center"+ " point y coord", 20, 300); text("3rd Parameter: half of shape's"+ " width", 20, 320); text("4th Parameter: half of shape's"+ " height", 20, 340); break; default: break; }} Output: Online editor: https://editor.p5js.org/ Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/ Reference: https://p5js.org/reference/#/p5/rectMode JavaScript-p5.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to calculate the number of days between two dates in javascript? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 44937, "s": 44909, "text": "\n29 May, 2020" }, { "code": null, "e": 45128, "s": 44937, "text": "The rectMode() function in p5.js is used to change the way in which the parameters given to the rect() function are interpreted. This modifies the location from where the rectangle is drawn." }, { "code": null, "e": 45167, "s": 45128, "text": "This function can be given four modes:" }, { "code": null, "e": 45342, "s": 45167, "text": "CORNER: This mode interprets the first two parameters as the upper-left corner of the shape. The third and fourth parameters are its width and height. It is the default mode." }, { "code": null, "e": 45490, "s": 45342, "text": "CORNERS:This mode interprets the first two parameters as the upper-left corner and the other two parameters as the location of the opposite corner." }, { "code": null, "e": 45643, "s": 45490, "text": "CENTER: This mode interprets the first two parameters as the shape’s center point. The third and fourth parameters specify the shape’s width and height." }, { "code": null, "e": 45803, "s": 45643, "text": "RADIUS:This mode interprets the first two parameters as the shape’s center point. The third and fourth parameters specify half of the shape’s width and height." }, { "code": null, "e": 45811, "s": 45803, "text": "Syntax:" }, { "code": null, "e": 45828, "s": 45811, "text": "rectMode( mode )" }, { "code": null, "e": 45921, "s": 45828, "text": "Parameters: This function accepts a single parameter as mentioned above and described below." }, { "code": null, "e": 46039, "s": 45921, "text": "mode: It is a Constant which defines which mode to use. It can have the values of CORNER, CORNERS, CENTER, or RADIUS." }, { "code": null, "e": 46103, "s": 46039, "text": "The examples below illustrate the rectMode() function in p5.js:" }, { "code": null, "e": 46112, "s": 46103, "text": "Example:" }, { "code": "let currMode; function setup() { createCanvas(500, 400); textSize(16); // Define all the rectModes() let rectModes = [CORNER, CORNERS, CENTER, RADIUS]; let index = 0; currMode = rectModes[index]; // Define a button to switch between the modes let closeBtn = createButton(\"Change rectMode\"); closeBtn.position(220, 40); closeBtn.mouseClicked(() => { if (index < rectModes.length - 1) index++; else index = 0; currMode = rectModes[index]; });} function draw() { clear(); text(\"Click on the button to\"+ \" change the rectMode()\", 20, 20); fill(\"green\"); // Draw the first rectangle with default mode rectMode(CORNER); rect(100, 100, 100, 100); fill(\"red\"); // Set the rectMode according to the defined mode rectMode(currMode); // Draw the second rectangle according to the // selected rectMode() and different dimensions rect(100, 100, 50, 50); // Draw circles to demonstrate corners of // the first rectangle circle(100, 100, 10); circle(200, 100, 10); circle(100, 200, 10); circle(200, 200, 10); fill(\"black\"); text(\"Current Mode: \" + currMode, 20, 250); // Show details of parameter according to selected mode switch (currMode) { case CORNER: text(\"1st Parameter: upper-left\"+ \" corner x coord\", 20, 280); text(\"2nd Parameter: upper-left\"+ \" corner y coord\", 20, 300); text(\"3rd Parameter: width\", 20, 320); text(\"4th Parameter: height\", 20, 340); break; case CORNERS: text(\"1st Parameter: upper-left corner\"+ \" x coord\", 20, 280); text(\"2nd Parameter: upper-left corner\"+ \" y coord\", 20, 300); text(\"3rd Parameter: opposite corner x\", 20, 320); text(\"4th Parameter: opposite corner y\", 20, 340); break; case CENTER: text(\"1st Parameter: shape's center\"+ \" point x coord\", 20, 280); text(\"2nd Parameter: shape's center\"+ \" point y coord\", 20, 300); text(\"3rd Parameter: width\", 20, 320); text(\"4th Parameter: height\", 20, 340); break; case RADIUS: text(\"1st Parameter: shape's center\"+ \" point x coord\", 20, 280); text(\"2nd Parameter: shape's center\"+ \" point y coord\", 20, 300); text(\"3rd Parameter: half of shape's\"+ \" width\", 20, 320); text(\"4th Parameter: half of shape's\"+ \" height\", 20, 340); break; default: break; }}", "e": 48525, "s": 46112, "text": null }, { "code": null, "e": 48533, "s": 48525, "text": "Output:" }, { "code": null, "e": 48573, "s": 48533, "text": "Online editor: https://editor.p5js.org/" }, { "code": null, "e": 48671, "s": 48573, "text": "Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/" }, { "code": null, "e": 48723, "s": 48671, "text": "Reference: https://p5js.org/reference/#/p5/rectMode" }, { "code": null, "e": 48740, "s": 48723, "text": "JavaScript-p5.js" }, { "code": null, "e": 48751, "s": 48740, "text": "JavaScript" }, { "code": null, "e": 48768, "s": 48751, "text": "Web Technologies" }, { "code": null, "e": 48866, "s": 48768, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 48906, "s": 48866, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 48951, "s": 48906, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 49012, "s": 48951, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 49084, "s": 49012, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 49153, "s": 49084, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 49193, "s": 49153, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 49226, "s": 49193, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 49271, "s": 49226, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 49314, "s": 49271, "text": "How to fetch data from an API in ReactJS ?" } ]
Writing to CSV files in R - GeeksforGeeks
26 Mar, 2021 For Data Analysis sometimes creating CSV data file is required and do some operations on it as per our requirement. So, In this article we are going to learn that how to write data to CSV File using R Programming Language. To write to csv file write.csv() function is used. Syntax: write.csv(data, path) Parameter: data: data to be added to csv path: pathname of the file Approach: Create a DataFrame Pass required values to the function Write to file Let us first create a data frame. Example: R Country <- c("China", "India", "United States", "Indonesia", "Pakistan") Population_1_july_2018 <- c("1,427,647,786", "1,352,642,280", "327,096,265", "267,670,543", "212,228,286") Population_1_july_2019 <- c("1,433,783,686", "1,366,417,754", "329,064,917", "270,625,568", "216,565,318") change_in_percents <- c("+0.43%", "+1.02%", "+0.60%", "+1.10%", "+2.04%") data <- data.frame(Country, Population_1_july_2018, Population_1_july_2019, change_in_percents)print(data) Output: Our Data in console Now let us write this data to a csv file and save it to a required location. Example: R Country <- c("China", "India", "United States", "Indonesia", "Pakistan") Population_1_july_2018 <- c("1,427,647,786", "1,352,642,280", "327,096,265", "267,670,543", "212,228,286") Population_1_july_2019 <- c("1,433,783,686", "1,366,417,754", "329,064,917", "270,625,568", "216,565,318") change_in_percents <- c("+0.43%", "+1.02%", "+0.60%", "+1.10%", "+2.04%") data <- data.frame(Country, Population_1_july_2018, Population_1_july_2019, change_in_percents)print(data) write.csv(data,"C:\\Users\\...YOUR PATH...\\population.csv")print ('CSV file written Successfully :)') Output: CSV File with data Picked R-CSV R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Replace specific values in column in R DataFrame ? Filter data by multiple conditions in R using Dplyr Loops in R (for, while, repeat) How to change Row Names of DataFrame in R ? Change Color of Bars in Barchart using ggplot2 in R Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to Change Axis Scales in R Plots? K-Means Clustering in R Programming Creating a Data Frame from Vectors in R Programming
[ { "code": null, "e": 24761, "s": 24733, "text": "\n26 Mar, 2021" }, { "code": null, "e": 24984, "s": 24761, "text": "For Data Analysis sometimes creating CSV data file is required and do some operations on it as per our requirement. So, In this article we are going to learn that how to write data to CSV File using R Programming Language." }, { "code": null, "e": 25035, "s": 24984, "text": "To write to csv file write.csv() function is used." }, { "code": null, "e": 25065, "s": 25035, "text": "Syntax: write.csv(data, path)" }, { "code": null, "e": 25076, "s": 25065, "text": "Parameter:" }, { "code": null, "e": 25106, "s": 25076, "text": "data: data to be added to csv" }, { "code": null, "e": 25133, "s": 25106, "text": "path: pathname of the file" }, { "code": null, "e": 25143, "s": 25133, "text": "Approach:" }, { "code": null, "e": 25162, "s": 25143, "text": "Create a DataFrame" }, { "code": null, "e": 25199, "s": 25162, "text": "Pass required values to the function" }, { "code": null, "e": 25213, "s": 25199, "text": "Write to file" }, { "code": null, "e": 25247, "s": 25213, "text": "Let us first create a data frame." }, { "code": null, "e": 25256, "s": 25247, "text": "Example:" }, { "code": null, "e": 25258, "s": 25256, "text": "R" }, { "code": "Country <- c(\"China\", \"India\", \"United States\", \"Indonesia\", \"Pakistan\") Population_1_july_2018 <- c(\"1,427,647,786\", \"1,352,642,280\", \"327,096,265\", \"267,670,543\", \"212,228,286\") Population_1_july_2019 <- c(\"1,433,783,686\", \"1,366,417,754\", \"329,064,917\", \"270,625,568\", \"216,565,318\") change_in_percents <- c(\"+0.43%\", \"+1.02%\", \"+0.60%\", \"+1.10%\", \"+2.04%\") data <- data.frame(Country, Population_1_july_2018, Population_1_july_2019, change_in_percents)print(data)", "e": 25788, "s": 25258, "text": null }, { "code": null, "e": 25796, "s": 25788, "text": "Output:" }, { "code": null, "e": 25816, "s": 25796, "text": "Our Data in console" }, { "code": null, "e": 25893, "s": 25816, "text": "Now let us write this data to a csv file and save it to a required location." }, { "code": null, "e": 25902, "s": 25893, "text": "Example:" }, { "code": null, "e": 25904, "s": 25902, "text": "R" }, { "code": "Country <- c(\"China\", \"India\", \"United States\", \"Indonesia\", \"Pakistan\") Population_1_july_2018 <- c(\"1,427,647,786\", \"1,352,642,280\", \"327,096,265\", \"267,670,543\", \"212,228,286\") Population_1_july_2019 <- c(\"1,433,783,686\", \"1,366,417,754\", \"329,064,917\", \"270,625,568\", \"216,565,318\") change_in_percents <- c(\"+0.43%\", \"+1.02%\", \"+0.60%\", \"+1.10%\", \"+2.04%\") data <- data.frame(Country, Population_1_july_2018, Population_1_july_2019, change_in_percents)print(data) write.csv(data,\"C:\\\\Users\\\\...YOUR PATH...\\\\population.csv\")print ('CSV file written Successfully :)')", "e": 26538, "s": 25904, "text": null }, { "code": null, "e": 26546, "s": 26538, "text": "Output:" }, { "code": null, "e": 26565, "s": 26546, "text": "CSV File with data" }, { "code": null, "e": 26572, "s": 26565, "text": "Picked" }, { "code": null, "e": 26578, "s": 26572, "text": "R-CSV" }, { "code": null, "e": 26589, "s": 26578, "text": "R Language" }, { "code": null, "e": 26687, "s": 26589, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26745, "s": 26687, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 26797, "s": 26745, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 26829, "s": 26797, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 26873, "s": 26829, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 26925, "s": 26873, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 26960, "s": 26925, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 27018, "s": 26960, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 27056, "s": 27018, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 27092, "s": 27056, "text": "K-Means Clustering in R Programming" } ]
C# | Check if every List element matches the predicate conditions - GeeksforGeeks
01 Feb, 2019 List<T>.TrueForAll(Predicate<T>) is used to check whether every element in the List<T> matches the conditions defined by the specified predicate or not. Syntax: public bool TrueForAll (Predicate<T> match); Parameter: match: It is the Predicate<T> delegate which defines the conditions to check against the elements. Return Value: This method returns true if every element in the List<T> matches the conditions defined by the specified predicate otherwise it returns false. If the list has no elements, the return value is true. Exception: This method will give ArgumentNullException if the match is null. Below programs illustrate the use of List<T>.TrueForAll(Predicate<T>) Method: Example 1: // C# Program to check if every element // in the List matches the conditions // defined by the specified predicateusing System; using System.Collections; using System.Collections.Generic; class Geeks { // function which checks whether an // element is even or not. Or you can // say it is the specified condition private static bool isEven(int i) { return ((i % 2) == 0); } // Main Method public static void Main(String[] args) { // Creating a List<T> of Integers List<int> firstlist = new List<int>(); // Adding elements to List for (int i = 0; i <= 10; i+=2) { firstlist.Add(i); } Console.WriteLine("Elements Present in List:\n"); // Displaying the elements of List foreach(int k in firstlist) { Console.WriteLine(k); } Console.WriteLine(" "); Console.Write("Result: "); // Checks if all the elements of firstlist // matches the condition defined by predicate Console.WriteLine(firstlist.TrueForAll(isEven)); } } Elements Present in List: 0 2 4 6 8 10 Result: True Example 2: // C# Program to check if every element //in the List matches the conditions //defined by the specified predicateusing System;using System.Collections; using System.Collections.Generic; public class Example{ public static void Main() { List<string> lang = new List<string>(); lang.Add("C# language"); lang.Add("C++ language"); lang.Add("Java language"); lang.Add("Pyhton language"); lang.Add("Ruby language"); Console.WriteLine("Elements Present in List:\n"); foreach(string language in lang) { Console.WriteLine(language); } Console.WriteLine(" "); Console.Write("TrueForAll(EndsWithLanguage): "); // Checks if all the elements of lang // matches the condition defined by predicate Console.WriteLine(lang.TrueForAll(EndsWithLanguage)); } // Search predicate returns // true if a string ends in "language". private static bool EndsWithLanguage(String s) { return s.ToLower().EndsWith("language"); }} Elements Present in List: C# language C++ language Java language Pyhton language Ruby language TrueForAll(EndsWithLanguage): True Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.trueforall?view=netframework-4.7.2 CSharp-Generic-List CSharp-Generic-Namespace CSharp-method Picked C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Extension Method in C# HashSet in C# with Examples C# | Inheritance Partial Classes in C# C# | Generics - Introduction Top 50 C# Interview Questions & Answers Switch Statement in C# Convert String to Character Array in C# C# | How to insert an element in an Array? Lambda Expressions in C#
[ { "code": null, "e": 25547, "s": 25519, "text": "\n01 Feb, 2019" }, { "code": null, "e": 25700, "s": 25547, "text": "List<T>.TrueForAll(Predicate<T>) is used to check whether every element in the List<T> matches the conditions defined by the specified predicate or not." }, { "code": null, "e": 25708, "s": 25700, "text": "Syntax:" }, { "code": null, "e": 25753, "s": 25708, "text": "public bool TrueForAll (Predicate<T> match);" }, { "code": null, "e": 25764, "s": 25753, "text": "Parameter:" }, { "code": null, "e": 25863, "s": 25764, "text": "match: It is the Predicate<T> delegate which defines the conditions to check against the elements." }, { "code": null, "e": 26075, "s": 25863, "text": "Return Value: This method returns true if every element in the List<T> matches the conditions defined by the specified predicate otherwise it returns false. If the list has no elements, the return value is true." }, { "code": null, "e": 26152, "s": 26075, "text": "Exception: This method will give ArgumentNullException if the match is null." }, { "code": null, "e": 26230, "s": 26152, "text": "Below programs illustrate the use of List<T>.TrueForAll(Predicate<T>) Method:" }, { "code": null, "e": 26241, "s": 26230, "text": "Example 1:" }, { "code": "// C# Program to check if every element // in the List matches the conditions // defined by the specified predicateusing System; using System.Collections; using System.Collections.Generic; class Geeks { // function which checks whether an // element is even or not. Or you can // say it is the specified condition private static bool isEven(int i) { return ((i % 2) == 0); } // Main Method public static void Main(String[] args) { // Creating a List<T> of Integers List<int> firstlist = new List<int>(); // Adding elements to List for (int i = 0; i <= 10; i+=2) { firstlist.Add(i); } Console.WriteLine(\"Elements Present in List:\\n\"); // Displaying the elements of List foreach(int k in firstlist) { Console.WriteLine(k); } Console.WriteLine(\" \"); Console.Write(\"Result: \"); // Checks if all the elements of firstlist // matches the condition defined by predicate Console.WriteLine(firstlist.TrueForAll(isEven)); } } ", "e": 27369, "s": 26241, "text": null }, { "code": null, "e": 27425, "s": 27369, "text": "Elements Present in List:\n\n0\n2\n4\n6\n8\n10\n \nResult: True\n" }, { "code": null, "e": 27436, "s": 27425, "text": "Example 2:" }, { "code": "// C# Program to check if every element //in the List matches the conditions //defined by the specified predicateusing System;using System.Collections; using System.Collections.Generic; public class Example{ public static void Main() { List<string> lang = new List<string>(); lang.Add(\"C# language\"); lang.Add(\"C++ language\"); lang.Add(\"Java language\"); lang.Add(\"Pyhton language\"); lang.Add(\"Ruby language\"); Console.WriteLine(\"Elements Present in List:\\n\"); foreach(string language in lang) { Console.WriteLine(language); } Console.WriteLine(\" \"); Console.Write(\"TrueForAll(EndsWithLanguage): \"); // Checks if all the elements of lang // matches the condition defined by predicate Console.WriteLine(lang.TrueForAll(EndsWithLanguage)); } // Search predicate returns // true if a string ends in \"language\". private static bool EndsWithLanguage(String s) { return s.ToLower().EndsWith(\"language\"); }}", "e": 28510, "s": 27436, "text": null }, { "code": null, "e": 28644, "s": 28510, "text": "Elements Present in List:\n\nC# language\nC++ language\nJava language\nPyhton language\nRuby language\n \nTrueForAll(EndsWithLanguage): True\n" }, { "code": null, "e": 28655, "s": 28644, "text": "Reference:" }, { "code": null, "e": 28768, "s": 28655, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.trueforall?view=netframework-4.7.2" }, { "code": null, "e": 28788, "s": 28768, "text": "CSharp-Generic-List" }, { "code": null, "e": 28813, "s": 28788, "text": "CSharp-Generic-Namespace" }, { "code": null, "e": 28827, "s": 28813, "text": "CSharp-method" }, { "code": null, "e": 28834, "s": 28827, "text": "Picked" }, { "code": null, "e": 28837, "s": 28834, "text": "C#" }, { "code": null, "e": 28935, "s": 28837, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28958, "s": 28935, "text": "Extension Method in C#" }, { "code": null, "e": 28986, "s": 28958, "text": "HashSet in C# with Examples" }, { "code": null, "e": 29003, "s": 28986, "text": "C# | Inheritance" }, { "code": null, "e": 29025, "s": 29003, "text": "Partial Classes in C#" }, { "code": null, "e": 29054, "s": 29025, "text": "C# | Generics - Introduction" }, { "code": null, "e": 29094, "s": 29054, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 29117, "s": 29094, "text": "Switch Statement in C#" }, { "code": null, "e": 29157, "s": 29117, "text": "Convert String to Character Array in C#" }, { "code": null, "e": 29200, "s": 29157, "text": "C# | How to insert an element in an Array?" } ]
Using Currency Format in JFormattedTextField
Following example showcase how to create and use JFormattedTextField to specify a Currency format on Text Fields in Swing based application. We are using the following APIs. JFormattedTextField − To create a formatted text field. JFormattedTextField − To create a formatted text field. NumberFormat − To provide Percentage format to JFormattedTextField. NumberFormat − To provide Percentage format to JFormattedTextField. NumberFormat.getCurrencyInstance() − to get a currency format. NumberFormat.getCurrencyInstance() − to get a currency format. import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.LayoutManager; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.text.DateFormat; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.Date; import javax.swing.BorderFactory; import javax.swing.JFormattedTextField; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; public class SwingTester implements PropertyChangeListener { private static JFormattedTextField principleTextField; private static JFormattedTextField rateTextField; private static JFormattedTextField yearsTextField; private static JFormattedTextField amountTextField; public static void main(String[] args) { SwingTester tester = new SwingTester(); createWindow(tester); } private static void createWindow(SwingTester tester) { JFrame frame = new JFrame("Swing Tester"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); createUI(frame, tester); frame.setSize(560, 200); frame.setLocationRelativeTo(null); frame.setVisible(true); } private static void createUI(final JFrame frame, SwingTester tester) { JPanel panel = new JPanel(); LayoutManager layout = new GridLayout(6,2); panel.setLayout(layout); panel.setSize(300, 200); panel.setBorder(BorderFactory.createTitledBorder("Formats")); NumberFormat principleFormat = NumberFormat.getNumberInstance(); principleTextField = new JFormattedTextField(principleFormat); principleTextField.setName("Principle"); principleTextField.setColumns(10); JLabel principleLabel = new JLabel("Principle:"); principleLabel.setLabelFor(principleTextField); principleTextField.setValue(new Double(100000)); principleTextField.addPropertyChangeListener("value", tester); NumberFormat rateFormat = NumberFormat.getPercentInstance(); rateFormat.setMinimumFractionDigits(2); rateTextField = new JFormattedTextField(rateFormat); rateTextField.setName("Rate"); rateTextField.setColumns(10); JLabel rateLabel = new JLabel("Interest Rate:"); rateLabel.setLabelFor(rateTextField); rateTextField.setValue(new Double(0.1)); rateTextField.addPropertyChangeListener("value", tester); yearsTextField = new JFormattedTextField(); yearsTextField.setName("Years"); yearsTextField.setColumns(10); JLabel yearLabel = new JLabel("Year(s):"); yearLabel.setLabelFor(yearsTextField); yearsTextField.setValue(new Double(1)); yearsTextField.addPropertyChangeListener("value", tester); NumberFormat amountFormat = NumberFormat.getCurrencyInstance(); amountTextField = new JFormattedTextField(amountFormat); amountTextField.setName("Amount"); amountTextField.setColumns(10); amountTextField.setEditable(false); JLabel amountLabel = new JLabel("Amount:"); amountLabel.setLabelFor(amountTextField); amountTextField.setValue(new Double(110000)); DateFormat dateFormat = new SimpleDateFormat("dd MMM YYYY"); JFormattedTextField today = new JFormattedTextField(dateFormat); today.setName("Today"); today.setColumns(10); today.setEditable(false); JLabel todayLabel = new JLabel("Date:"); todayLabel.setLabelFor(today); today.setValue(new Date()); panel.add(principleLabel); panel.add(principleTextField); panel.add(rateLabel); panel.add(rateTextField); panel.add(yearLabel); panel.add(yearsTextField); panel.add(amountLabel); panel.add(amountTextField); panel.add(todayLabel); panel.add(today); JPanel mainPanel = new JPanel(); mainPanel.add(panel); frame.getContentPane().add(mainPanel, BorderLayout.CENTER); } @Override public void propertyChange(PropertyChangeEvent evt) { double amount, rate, years, principle; principle = ((Number)principleTextField.getValue()).doubleValue(); rate = ((Number)rateTextField.getValue()).doubleValue() * 100; years = ((Number)yearsTextField.getValue()).doubleValue(); amount = principle + principle * rate * years / 100; amountTextField.setValue(new Double(amount)); } } We can pass locale as well to NumberFormat.getCurrencyInstance() to get the currency symbol of required country. We can pass locale as well to NumberFormat.getCurrencyInstance() to get the currency symbol of required country. Print Add Notes Bookmark this page
[ { "code": null, "e": 2180, "s": 2039, "text": "Following example showcase how to create and use JFormattedTextField to specify a Currency format on Text Fields in Swing based application." }, { "code": null, "e": 2213, "s": 2180, "text": "We are using the following APIs." }, { "code": null, "e": 2269, "s": 2213, "text": "JFormattedTextField − To create a formatted text field." }, { "code": null, "e": 2325, "s": 2269, "text": "JFormattedTextField − To create a formatted text field." }, { "code": null, "e": 2393, "s": 2325, "text": "NumberFormat − To provide Percentage format to JFormattedTextField." }, { "code": null, "e": 2461, "s": 2393, "text": "NumberFormat − To provide Percentage format to JFormattedTextField." }, { "code": null, "e": 2524, "s": 2461, "text": "NumberFormat.getCurrencyInstance() − to get a currency format." }, { "code": null, "e": 2587, "s": 2524, "text": "NumberFormat.getCurrencyInstance() − to get a currency format." }, { "code": null, "e": 6938, "s": 2587, "text": "import java.awt.BorderLayout;\nimport java.awt.GridLayout;\nimport java.awt.LayoutManager;\nimport java.beans.PropertyChangeEvent;\nimport java.beans.PropertyChangeListener;\nimport java.text.DateFormat;\nimport java.text.NumberFormat;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\n\nimport javax.swing.BorderFactory;\nimport javax.swing.JFormattedTextField;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JPanel;\n\npublic class SwingTester implements PropertyChangeListener {\n\n private static JFormattedTextField principleTextField;\n private static JFormattedTextField rateTextField;\n private static JFormattedTextField yearsTextField;\n private static JFormattedTextField amountTextField;\n public static void main(String[] args) {\n SwingTester tester = new SwingTester();\n createWindow(tester);\n }\n\n private static void createWindow(SwingTester tester) {\n JFrame frame = new JFrame(\"Swing Tester\");\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n createUI(frame, tester);\n frame.setSize(560, 200);\n frame.setLocationRelativeTo(null);\n frame.setVisible(true);\n }\n\n private static void createUI(final JFrame frame, SwingTester tester) {\n JPanel panel = new JPanel();\n LayoutManager layout = new GridLayout(6,2);\n panel.setLayout(layout); \n panel.setSize(300, 200);\n panel.setBorder(BorderFactory.createTitledBorder(\"Formats\"));\n\n NumberFormat principleFormat = NumberFormat.getNumberInstance();\n principleTextField = new JFormattedTextField(principleFormat);\n principleTextField.setName(\"Principle\");\n principleTextField.setColumns(10);\n JLabel principleLabel = new JLabel(\"Principle:\");\n principleLabel.setLabelFor(principleTextField);\n principleTextField.setValue(new Double(100000));\n principleTextField.addPropertyChangeListener(\"value\", tester);\n\n NumberFormat rateFormat = NumberFormat.getPercentInstance();\n rateFormat.setMinimumFractionDigits(2);\n rateTextField = new JFormattedTextField(rateFormat);\n rateTextField.setName(\"Rate\");\n rateTextField.setColumns(10);\n JLabel rateLabel = new JLabel(\"Interest Rate:\");\n rateLabel.setLabelFor(rateTextField);\n rateTextField.setValue(new Double(0.1));\n rateTextField.addPropertyChangeListener(\"value\", tester);\n yearsTextField = new JFormattedTextField();\n yearsTextField.setName(\"Years\");\n yearsTextField.setColumns(10);\n JLabel yearLabel = new JLabel(\"Year(s):\");\n yearLabel.setLabelFor(yearsTextField);\n yearsTextField.setValue(new Double(1));\n yearsTextField.addPropertyChangeListener(\"value\", tester);\n\n NumberFormat amountFormat = NumberFormat.getCurrencyInstance();\n amountTextField = new JFormattedTextField(amountFormat);\n amountTextField.setName(\"Amount\");\n amountTextField.setColumns(10);\n amountTextField.setEditable(false);\n JLabel amountLabel = new JLabel(\"Amount:\");\n amountLabel.setLabelFor(amountTextField);\n amountTextField.setValue(new Double(110000));\n \n DateFormat dateFormat = new SimpleDateFormat(\"dd MMM YYYY\");\n JFormattedTextField today = new JFormattedTextField(dateFormat);\n today.setName(\"Today\");\n today.setColumns(10);\n today.setEditable(false);\n JLabel todayLabel = new JLabel(\"Date:\");\n todayLabel.setLabelFor(today);\n today.setValue(new Date());\n\n panel.add(principleLabel);\n panel.add(principleTextField); \n panel.add(rateLabel);\n panel.add(rateTextField);\n panel.add(yearLabel);\n panel.add(yearsTextField);\n panel.add(amountLabel);\n panel.add(amountTextField); \n panel.add(todayLabel);\n panel.add(today); \n JPanel mainPanel = new JPanel(); \n mainPanel.add(panel);\n\n frame.getContentPane().add(mainPanel, BorderLayout.CENTER);\n } \n\n @Override\n public void propertyChange(PropertyChangeEvent evt) {\n double amount, rate, years, principle;\n\n principle = ((Number)principleTextField.getValue()).doubleValue();\n rate = ((Number)rateTextField.getValue()).doubleValue() * 100;\n years = ((Number)yearsTextField.getValue()).doubleValue();\n \n amount = principle + principle * rate * years / 100;\n amountTextField.setValue(new Double(amount));\n } \n}" }, { "code": null, "e": 7051, "s": 6938, "text": "We can pass locale as well to NumberFormat.getCurrencyInstance() to get the currency symbol of required country." }, { "code": null, "e": 7164, "s": 7051, "text": "We can pass locale as well to NumberFormat.getCurrencyInstance() to get the currency symbol of required country." }, { "code": null, "e": 7171, "s": 7164, "text": " Print" }, { "code": null, "e": 7182, "s": 7171, "text": " Add Notes" } ]
PyQt5 - Create circular Push Button - GeeksforGeeks
22 Apr, 2020 In this article we will see how to create circular push button. By default, when we create a push button it is in rectangular form although we can also change it size to square. In order to create circular button we have to do following steps: 1. Create a push button.2. Change its size to make it square.3. Set radius of button to half of length or square button. Note : If we set radius greater then the half of the length then no change will occur as that shape would not be possible. Syntax : button.setStyleSheet(“border-radius : 50;”) Argument : It takes string as argument. Action performed : It sets the radius of button. Code : # importing librariesfrom PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a push button button = QPushButton("CLICK", self) # setting geometry of button button.setGeometry(200, 150, 100, 100) # setting radius and border button.setStyleSheet("border-radius : 50; border : 2px solid black") # adding action to a button button.clicked.connect(self.clickme) # action method def clickme(self): # printing pressed print("pressed") # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? Python OOPs Concepts Create a Pandas DataFrame from Lists *args and **kwargs in Python How to drop one or multiple columns in Pandas Dataframe Python | Get unique values from a list Python Classes and Objects Stack in Python Graph Plotting in Python | Set 1 Convert integer to string in Python
[ { "code": null, "e": 24786, "s": 24758, "text": "\n22 Apr, 2020" }, { "code": null, "e": 24964, "s": 24786, "text": "In this article we will see how to create circular push button. By default, when we create a push button it is in rectangular form although we can also change it size to square." }, { "code": null, "e": 25030, "s": 24964, "text": "In order to create circular button we have to do following steps:" }, { "code": null, "e": 25151, "s": 25030, "text": "1. Create a push button.2. Change its size to make it square.3. Set radius of button to half of length or square button." }, { "code": null, "e": 25274, "s": 25151, "text": "Note : If we set radius greater then the half of the length then no change will occur as that shape would not be possible." }, { "code": null, "e": 25327, "s": 25274, "text": "Syntax : button.setStyleSheet(“border-radius : 50;”)" }, { "code": null, "e": 25367, "s": 25327, "text": "Argument : It takes string as argument." }, { "code": null, "e": 25416, "s": 25367, "text": "Action performed : It sets the radius of button." }, { "code": null, "e": 25423, "s": 25416, "text": "Code :" }, { "code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a push button button = QPushButton(\"CLICK\", self) # setting geometry of button button.setGeometry(200, 150, 100, 100) # setting radius and border button.setStyleSheet(\"border-radius : 50; border : 2px solid black\") # adding action to a button button.clicked.connect(self.clickme) # action method def clickme(self): # printing pressed print(\"pressed\") # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 26533, "s": 25423, "text": null }, { "code": null, "e": 26542, "s": 26533, "text": "Output :" }, { "code": null, "e": 26553, "s": 26542, "text": "Python-gui" }, { "code": null, "e": 26565, "s": 26553, "text": "Python-PyQt" }, { "code": null, "e": 26572, "s": 26565, "text": "Python" }, { "code": null, "e": 26670, "s": 26572, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26679, "s": 26670, "text": "Comments" }, { "code": null, "e": 26692, "s": 26679, "text": "Old Comments" }, { "code": null, "e": 26724, "s": 26692, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26745, "s": 26724, "text": "Python OOPs Concepts" }, { "code": null, "e": 26782, "s": 26745, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 26811, "s": 26782, "text": "*args and **kwargs in Python" }, { "code": null, "e": 26867, "s": 26811, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26906, "s": 26867, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26933, "s": 26906, "text": "Python Classes and Objects" }, { "code": null, "e": 26949, "s": 26933, "text": "Stack in Python" }, { "code": null, "e": 26982, "s": 26949, "text": "Graph Plotting in Python | Set 1" } ]
Implementing TabNet in PyTorch. Deep Learning has taken over vision... | by Samrat Thapa | Towards Data Science
Deep Learning has taken over vision, natural language processing, speech recognition, and many other fields achieving astonishing results and even superhuman performance in some. However, the use of deep learning to model tabular data has been relatively limited. For tabular data, the most common approach is the use of tree-based models and their ensembles. The tree-based models globally select features which reduce the entropy the most. Ensemble methods like bagging, boosting improve these tree-based methods further by reducing the model variance. Recent tree-based ensembles like XGBoost and LightGBM have dominated Kaggle competitions. TabNet is a neural architecture developed by the research team at Google Cloud AI. It was able to achieve state of the art results on several datasets in both regression and classification problems. It combines the features of neural nets to fit very complex functions and the feature selection property of tree-based algorithms. In other words, the model learns to select only the relevant features during the training process. Moreover, contrary to tree-based models which can only do feature-selection globally, the feature selection process in TabNet is instance-wise. Another desirable feature of TabNet is interpretability. Contrary to most of deep learning, where the neural networks act like black boxes, we can interpret which features the models selects in case of TabNet. In this blog, I will take you through a step-wise beginner-friendly implementation of TabNet in PyTorch. Let’s get started!! The TabNet Architecture. Figure(1) was taken from the original TabNet paper. We will build each component of the image individually and assemble them in the end. First, let’s go through two essential concepts used in this model- Ghost Batch Normalization (GBN) , and Sparsemax. Ghost Batch Normalization(GBN):GBN allows us to train large batches of data and also generalize better at the same time. To put it simply, we split the input batch into equal-sized sub-batches(the virtual batch size) and apply the same Batch Normalization layer on them. All the batch normalization layers used in the model except the first batch normalization layer applied to the input features are GBN layers. It can be implemented in PyTorch as follows: class GBN(nn.Module): def __init__(self,inp,vbs=128,momentum=0.01): super().__init__() self.bn = nn.BatchNorm1d(inp,momentum=momentum) self.vbs = vbs def forward(self,x): chunk = torch.chunk(x,x.size(0)//self.vbs,0) res = [self.bn(y) for y in chunk] return torch.cat(res,0) Sparsemax: Sparsemax is a non-linear normalization function just like softmax but as the name suggests, the distribution is ‘sparser’. That is, compared to softmax some numbers in the output probability distribution are much closer to 1 while others are much closer to 0. This enables the model to select relevant features at each decision steps more effectively. We will use sparsemax to project the mask for the feature selection step onto a sparser space. The implementation of sparsemax can be found at: https://github.com/gokceneraslan/SparseMax.torch To further increase the sparsity in the mask, we will also add a sparsity regularization technique to penalize less-sparser masks. This can be implemented at each decision step as follows: (mask*torch.log(mask+1e-10)).mean() #F(x)= -∑xlog(x+eps) The sum of this value over all decision steps can be added to the total loss (after multiplying with a regularization constant λ ). Attention Transformer: This is where the models learns the relationship between relevant features and decides which features to pass on to the feature transformer of the current decision step. Each Attention Transformer consists of a fully connected layer, a Ghost Batch Normalization Layer, and a Sparsemax layer. The attention transformer in each decision step receives the input features, processed features from the previous step and prior information about used-features. The prior information is represented by a matrix of size batch_size x input_features. It is initialized with ones and passed to and updated at every decision step’s attention transformer. There is also a relaxation parameter that limits how many times a certain feature can be used in a forward pass. A greater value implies that the model can reuse the same feature several times. I think the code makes everything clear. class AttentionTransformer(nn.Module): def __init__(self,d_a,inp_dim,relax,vbs=128): super().__init__() self.fc = nn.Linear(d_a,inp_dim) self.bn = GBN(out_dim,vbs=vbs) self.smax = Sparsemax() self.r = relax #a:feature from previous decision step def forward(self,a,priors): a = self.bn(self.fc(a)) mask = self.smax(a*priors) priors =priors*(self.r-mask) #updating the prior return mask This mask is then multiplied(element-wise) to the normalized input features. Feature Transformer: The feature transformer is where all the selected features are processed to generate the final output. Each feature transformer is composed of multiple Gated Linear Unit Blocks. A GLU controls which information must be allowed to further flow through the network. To implement a GLU Block, first we double the dimension of the input features to the GLU using a fully connected layer. We normalize the resultant matrix using a GBN Layer . Then, we apply a sigmoid to the second half of the resultant features and multiply the results to the first half. The result is multiplied with a scaling factor(sqrt(0.5) in this case) and added to the input. This summed result is the input for the next GLU Block in the sequence. A certain number of GLU Blocks are shared among all the decision steps to promote model capacity and efficiency(Optional). The first shared GLU Block (or first independent block if no blocks are shared) is unique as it reduces the dimension of the input features to a dimension equal n_a+n_d. n_a is the dimension of the features input to the attention transformer of the next step and n_d is the dimension of the features used to calculate the final results. These features are processed together until they reach the splitter. The ReLU activation is applied on the n_d dimensioned vector. The outputs of all the decision steps are summed together and passed through a fully connected layer to map them to the output dimension. class GLU(nn.Module): def __init__(self,inp_dim,out_dim,fc=None,vbs=128): super().__init__() if fc: self.fc = fc else: self.fc = nn.Linear(inp_dim,out_dim*2) self.bn = GBN(out_dim*2,vbs=vbs) self.od = out_dim def forward(self,x): x = self.bn(self.fc(x)) return x[:,:self.od]*torch.sigmoid(x[:,self.od:])class FeatureTransformer(nn.Module): def __init__(self,inp_dim,out_dim,shared,n_ind,vbs=128): super().__init__() first = True self.shared = nn.ModuleList() if shared: self.shared.append(GLU(inp_dim,out_dim,shared[0],vbs=vbs)) first= False for fc in shared[1:]: self.shared.append(GLU(out_dim,out_dim,fc,vbs=vbs)) else: self.shared = None self.independ = nn.ModuleList() if first: self.independ.append(GLU(inp,out_dim,vbs=vbs)) for x in range(first, n_ind): self.independ.append(GLU(out_dim,out_dim,vbs=vbs)) self.scale = torch.sqrt(torch.tensor([.5],device=device)) def forward(self,x): if self.shared: x = self.shared[0](x) for glu in self.shared[1:]: x = torch.add(x, glu(x)) x = x*self.scale for glu in self.independ: x = torch.add(x, glu(x)) x = x*self.scale return x Next, let us combine the Attention Transformer and Feature Transformer into a decision step: class DecisionStep(nn.Module): def __init__(self,inp_dim,n_d,n_a,shared,n_ind,relax,vbs=128): super().__init__() self.fea_tran = FeatureTransformer(inp_dim,n_d+n_a,shared,n_ind,vbs) self.atten_tran = AttentionTransformer(n_a,inp_dim,relax,vbs) def forward(self,x,a,priors): mask = self.atten_tran(a,priors) sparse_loss = ((-1)*mask*torch.log(mask+1e-10)).mean() x = self.fea_tran(x*mask) return x,sparse_loss Finally, we can complete the model by combining several decision steps together: class TabNet(nn.Module): def __init__(self,inp_dim,final_out_dim,n_d=64,n_a=64,n_shared=2,n_ind=2,n_steps=5,relax=1.2,vbs=128): super().__init__() if n_shared>0: self.shared = nn.ModuleList() self.shared.append(nn.Linear(inp_dim,2*(n_d+n_a))) for x in range(n_shared-1): self.shared.append(nn.Linear(n_d+n_a,2*(n_d+n_a))) else: self.shared=None self.first_step = FeatureTransformer(inp_dim,n_d+n_a,self.shared,n_ind) self.steps = nn.ModuleList() for x in range(n_steps-1): self.steps.append(DecisionStep(inp_dim,n_d,n_a,self.shared,n_ind,relax,vbs)) self.fc = nn.Linear(n_d,final_out_dim) self.bn = nn.BatchNorm1d(inp_dim) self.n_d = n_d def forward(self,x): x = self.bn(x) x_a = self.first_step(x)[:,self.n_d:] sparse_loss = torch.zeros(1).to(x.device) out = torch.zeros(x.size(0),self.n_d).to(x.device) priors = torch.ones(x.shape).to(x.device) for step in self.steps: x_te,l = step(x,x_a,priors) out += F.relu(x_te[:,:self.n_d]) x_a = x_te[:,self.n_d:] sparse_loss += l return self.fc(out),sparse_loss Approximate Range of Model Hyperparameters:n_d, n_a: 8 to 512batch size: 256 to 32768virtual batch size: 128 to 2048sparsity regularization constant: 0 to 0.00001number of shared GLU Blocks: 2 to 10number of independent decision Blocks: 2 to 10relaxation constant: 1 to 2.5number of decision steps: 2 to 10batch normalization momentum: 0.5 to 0.98(Note: These hyperparameters are based on the paper and also my personal experience.) This TabNet module can be extended for classification as well as regression tasks. You can add embeddings for your categorical variables, apply a Sigmoid or Softmax function to the output, and much more. Experiment and see what works best for you. In the example notebook, I tried replacing the Sparsemax with a Sigmoid and was able to get a slightly better accuracy. For a use case example on the Mechanisms of Actions(MoA) Prediction dataset, you can find my notebook here:https://www.kaggle.com/samratthapa/drug-prediction. It is the dataset of a competition currently being held on Kaggle. My implementation of TabNet is a short adaptation of the work of the generous people at DreamQuark. Their complete implementation of TabNet can be found at :https://github.com/dreamquark-ai/tabnet/tree/develop/pytorch_tabnet.You should consider reading the paper for a more detailed description of TabNet. Thank you for reading. I hope I was able to help. References:1) Sercan O. Arık, Tomas Pfister. 2020.TabNet: Attentive Interpretable Tabular Learning https://arxiv.org/abs/1908.07442v42) Yann N. Dauphin, Angela Fan, Michael Auli, and David Grangier. 2016. Language Modeling with Gated Convolutional Networks.https://arxiv.org/pdf/1612.08083.pdf3) Elad Hoffer, Itay Hubara, and Daniel Soudry. 2017. Train longer, generalize better: closing the generalization gap in large batch training of neural networks.https://arxiv.org/pdf/1705.08741.pdf4)Andre F. T. Martins and Ramon Fernandez Astudillo. 2016. From Softmax to Sparsemax: A Sparse Model of Attention and Multi-Label Classification.https://arxiv.org/abs/1602.020685)Sparsemax implementation https://github.com/gokceneraslan/SparseMax.torch6)Complete PyTorch TabNet implementation https://github.com/dreamquark-ai/tabnet/tree/develop/pytorch_tabnet
[ { "code": null, "e": 436, "s": 172, "text": "Deep Learning has taken over vision, natural language processing, speech recognition, and many other fields achieving astonishing results and even superhuman performance in some. However, the use of deep learning to model tabular data has been relatively limited." }, { "code": null, "e": 817, "s": 436, "text": "For tabular data, the most common approach is the use of tree-based models and their ensembles. The tree-based models globally select features which reduce the entropy the most. Ensemble methods like bagging, boosting improve these tree-based methods further by reducing the model variance. Recent tree-based ensembles like XGBoost and LightGBM have dominated Kaggle competitions." }, { "code": null, "e": 1600, "s": 817, "text": "TabNet is a neural architecture developed by the research team at Google Cloud AI. It was able to achieve state of the art results on several datasets in both regression and classification problems. It combines the features of neural nets to fit very complex functions and the feature selection property of tree-based algorithms. In other words, the model learns to select only the relevant features during the training process. Moreover, contrary to tree-based models which can only do feature-selection globally, the feature selection process in TabNet is instance-wise. Another desirable feature of TabNet is interpretability. Contrary to most of deep learning, where the neural networks act like black boxes, we can interpret which features the models selects in case of TabNet." }, { "code": null, "e": 1725, "s": 1600, "text": "In this blog, I will take you through a step-wise beginner-friendly implementation of TabNet in PyTorch. Let’s get started!!" }, { "code": null, "e": 1750, "s": 1725, "text": "The TabNet Architecture." }, { "code": null, "e": 2003, "s": 1750, "text": "Figure(1) was taken from the original TabNet paper. We will build each component of the image individually and assemble them in the end. First, let’s go through two essential concepts used in this model- Ghost Batch Normalization (GBN) , and Sparsemax." }, { "code": null, "e": 2461, "s": 2003, "text": "Ghost Batch Normalization(GBN):GBN allows us to train large batches of data and also generalize better at the same time. To put it simply, we split the input batch into equal-sized sub-batches(the virtual batch size) and apply the same Batch Normalization layer on them. All the batch normalization layers used in the model except the first batch normalization layer applied to the input features are GBN layers. It can be implemented in PyTorch as follows:" }, { "code": null, "e": 2783, "s": 2461, "text": "class GBN(nn.Module): def __init__(self,inp,vbs=128,momentum=0.01): super().__init__() self.bn = nn.BatchNorm1d(inp,momentum=momentum) self.vbs = vbs def forward(self,x): chunk = torch.chunk(x,x.size(0)//self.vbs,0) res = [self.bn(y) for y in chunk] return torch.cat(res,0)" }, { "code": null, "e": 2794, "s": 2783, "text": "Sparsemax:" }, { "code": null, "e": 3340, "s": 2794, "text": "Sparsemax is a non-linear normalization function just like softmax but as the name suggests, the distribution is ‘sparser’. That is, compared to softmax some numbers in the output probability distribution are much closer to 1 while others are much closer to 0. This enables the model to select relevant features at each decision steps more effectively. We will use sparsemax to project the mask for the feature selection step onto a sparser space. The implementation of sparsemax can be found at: https://github.com/gokceneraslan/SparseMax.torch" }, { "code": null, "e": 3529, "s": 3340, "text": "To further increase the sparsity in the mask, we will also add a sparsity regularization technique to penalize less-sparser masks. This can be implemented at each decision step as follows:" }, { "code": null, "e": 3586, "s": 3529, "text": "(mask*torch.log(mask+1e-10)).mean() #F(x)= -∑xlog(x+eps)" }, { "code": null, "e": 3718, "s": 3586, "text": "The sum of this value over all decision steps can be added to the total loss (after multiplying with a regularization constant λ )." }, { "code": null, "e": 4618, "s": 3718, "text": "Attention Transformer: This is where the models learns the relationship between relevant features and decides which features to pass on to the feature transformer of the current decision step. Each Attention Transformer consists of a fully connected layer, a Ghost Batch Normalization Layer, and a Sparsemax layer. The attention transformer in each decision step receives the input features, processed features from the previous step and prior information about used-features. The prior information is represented by a matrix of size batch_size x input_features. It is initialized with ones and passed to and updated at every decision step’s attention transformer. There is also a relaxation parameter that limits how many times a certain feature can be used in a forward pass. A greater value implies that the model can reuse the same feature several times. I think the code makes everything clear." }, { "code": null, "e": 5080, "s": 4618, "text": "class AttentionTransformer(nn.Module): def __init__(self,d_a,inp_dim,relax,vbs=128): super().__init__() self.fc = nn.Linear(d_a,inp_dim) self.bn = GBN(out_dim,vbs=vbs) self.smax = Sparsemax() self.r = relax #a:feature from previous decision step def forward(self,a,priors): a = self.bn(self.fc(a)) mask = self.smax(a*priors) priors =priors*(self.r-mask) #updating the prior return mask" }, { "code": null, "e": 5157, "s": 5080, "text": "This mask is then multiplied(element-wise) to the normalized input features." }, { "code": null, "e": 5178, "s": 5157, "text": "Feature Transformer:" }, { "code": null, "e": 5897, "s": 5178, "text": "The feature transformer is where all the selected features are processed to generate the final output. Each feature transformer is composed of multiple Gated Linear Unit Blocks. A GLU controls which information must be allowed to further flow through the network. To implement a GLU Block, first we double the dimension of the input features to the GLU using a fully connected layer. We normalize the resultant matrix using a GBN Layer . Then, we apply a sigmoid to the second half of the resultant features and multiply the results to the first half. The result is multiplied with a scaling factor(sqrt(0.5) in this case) and added to the input. This summed result is the input for the next GLU Block in the sequence." }, { "code": null, "e": 6626, "s": 5897, "text": "A certain number of GLU Blocks are shared among all the decision steps to promote model capacity and efficiency(Optional). The first shared GLU Block (or first independent block if no blocks are shared) is unique as it reduces the dimension of the input features to a dimension equal n_a+n_d. n_a is the dimension of the features input to the attention transformer of the next step and n_d is the dimension of the features used to calculate the final results. These features are processed together until they reach the splitter. The ReLU activation is applied on the n_d dimensioned vector. The outputs of all the decision steps are summed together and passed through a fully connected layer to map them to the output dimension." }, { "code": null, "e": 8028, "s": 6626, "text": "class GLU(nn.Module): def __init__(self,inp_dim,out_dim,fc=None,vbs=128): super().__init__() if fc: self.fc = fc else: self.fc = nn.Linear(inp_dim,out_dim*2) self.bn = GBN(out_dim*2,vbs=vbs) self.od = out_dim def forward(self,x): x = self.bn(self.fc(x)) return x[:,:self.od]*torch.sigmoid(x[:,self.od:])class FeatureTransformer(nn.Module): def __init__(self,inp_dim,out_dim,shared,n_ind,vbs=128): super().__init__() first = True self.shared = nn.ModuleList() if shared: self.shared.append(GLU(inp_dim,out_dim,shared[0],vbs=vbs)) first= False for fc in shared[1:]: self.shared.append(GLU(out_dim,out_dim,fc,vbs=vbs)) else: self.shared = None self.independ = nn.ModuleList() if first: self.independ.append(GLU(inp,out_dim,vbs=vbs)) for x in range(first, n_ind): self.independ.append(GLU(out_dim,out_dim,vbs=vbs)) self.scale = torch.sqrt(torch.tensor([.5],device=device)) def forward(self,x): if self.shared: x = self.shared[0](x) for glu in self.shared[1:]: x = torch.add(x, glu(x)) x = x*self.scale for glu in self.independ: x = torch.add(x, glu(x)) x = x*self.scale return x" }, { "code": null, "e": 8121, "s": 8028, "text": "Next, let us combine the Attention Transformer and Feature Transformer into a decision step:" }, { "code": null, "e": 8586, "s": 8121, "text": "class DecisionStep(nn.Module): def __init__(self,inp_dim,n_d,n_a,shared,n_ind,relax,vbs=128): super().__init__() self.fea_tran = FeatureTransformer(inp_dim,n_d+n_a,shared,n_ind,vbs) self.atten_tran = AttentionTransformer(n_a,inp_dim,relax,vbs) def forward(self,x,a,priors): mask = self.atten_tran(a,priors) sparse_loss = ((-1)*mask*torch.log(mask+1e-10)).mean() x = self.fea_tran(x*mask) return x,sparse_loss" }, { "code": null, "e": 8667, "s": 8586, "text": "Finally, we can complete the model by combining several decision steps together:" }, { "code": null, "e": 9905, "s": 8667, "text": "class TabNet(nn.Module): def __init__(self,inp_dim,final_out_dim,n_d=64,n_a=64,n_shared=2,n_ind=2,n_steps=5,relax=1.2,vbs=128): super().__init__() if n_shared>0: self.shared = nn.ModuleList() self.shared.append(nn.Linear(inp_dim,2*(n_d+n_a))) for x in range(n_shared-1): self.shared.append(nn.Linear(n_d+n_a,2*(n_d+n_a))) else: self.shared=None self.first_step = FeatureTransformer(inp_dim,n_d+n_a,self.shared,n_ind) self.steps = nn.ModuleList() for x in range(n_steps-1): self.steps.append(DecisionStep(inp_dim,n_d,n_a,self.shared,n_ind,relax,vbs)) self.fc = nn.Linear(n_d,final_out_dim) self.bn = nn.BatchNorm1d(inp_dim) self.n_d = n_d def forward(self,x): x = self.bn(x) x_a = self.first_step(x)[:,self.n_d:] sparse_loss = torch.zeros(1).to(x.device) out = torch.zeros(x.size(0),self.n_d).to(x.device) priors = torch.ones(x.shape).to(x.device) for step in self.steps: x_te,l = step(x,x_a,priors) out += F.relu(x_te[:,:self.n_d]) x_a = x_te[:,self.n_d:] sparse_loss += l return self.fc(out),sparse_loss" }, { "code": null, "e": 10338, "s": 9905, "text": "Approximate Range of Model Hyperparameters:n_d, n_a: 8 to 512batch size: 256 to 32768virtual batch size: 128 to 2048sparsity regularization constant: 0 to 0.00001number of shared GLU Blocks: 2 to 10number of independent decision Blocks: 2 to 10relaxation constant: 1 to 2.5number of decision steps: 2 to 10batch normalization momentum: 0.5 to 0.98(Note: These hyperparameters are based on the paper and also my personal experience.)" }, { "code": null, "e": 10706, "s": 10338, "text": "This TabNet module can be extended for classification as well as regression tasks. You can add embeddings for your categorical variables, apply a Sigmoid or Softmax function to the output, and much more. Experiment and see what works best for you. In the example notebook, I tried replacing the Sparsemax with a Sigmoid and was able to get a slightly better accuracy." }, { "code": null, "e": 10932, "s": 10706, "text": "For a use case example on the Mechanisms of Actions(MoA) Prediction dataset, you can find my notebook here:https://www.kaggle.com/samratthapa/drug-prediction. It is the dataset of a competition currently being held on Kaggle." }, { "code": null, "e": 11238, "s": 10932, "text": "My implementation of TabNet is a short adaptation of the work of the generous people at DreamQuark. Their complete implementation of TabNet can be found at :https://github.com/dreamquark-ai/tabnet/tree/develop/pytorch_tabnet.You should consider reading the paper for a more detailed description of TabNet." }, { "code": null, "e": 11288, "s": 11238, "text": "Thank you for reading. I hope I was able to help." } ]
Transformer for Language Modeling | Towards Data Science
Recent trends in Natural Language Processing have been building upon one of the biggest breakthroughs in the history of the field: the Transformer. The Transformer is a model architecture researched mainly by Google Brain and Google Research. It was initially shown to achieve state-of-the-art in the translation task but was later shown to be effective in just about any NLP task when it became massively adopted. The transformer architecture consists of a stack of encoders and decoders with self-attention layers that help the model pay attention to respective inputs. You can learn more about transformers in the original paper here. In this post, we will be showing you how to implement the transformer for the language modeling task. Language modeling is the task of assigning probability to sentences in a language. The goal for language modeling is for the model to assign high probability to real sentences in our dataset so that it will be able to generate fluent sentences that are close to human-level through a decoder scheme. We will be using the Fairseq library for implementing the transformer. towardsdatascience.com In this article, we will be again using the CMU Book Summary Dataset to train the Transformer model. You can refer to Step 1 of the blog post to acquire and prepare the dataset. After preparing the dataset, you should have the train.txt, valid.txt, and test.txt files ready that correspond to the three partitions of the dataset. If you haven’t heard of Fairseq, it is a popular NLP library developed by Facebook AI for implementing custom models for translation, summarization, language modeling, and other generation tasks. You can check out my comments on Fairseq here. Now, in order to download and install Fairseq, run the following commands: git clone https://github.com/pytorch/fairseqcd fairseqpip install --editable ./ You can also choose to install NVIDIA’s apex library to enable faster training if your GPU allows: git clone https://github.com/NVIDIA/apexcd apexpip install -v --no-cache-dir --global-option="--cpp_ext" --global-option="--cuda_ext" \ --global-option="--deprecated_fused_adam" --global-option="--xentropy" \ --global-option="--fast_multihead_attn" ./ Now, you have successfully installed Fairseq and finally we are all good to go! To preprocess the dataset, we can use the fairseq command-line tool, which makes it easy for developers and researchers to directly run operations from the terminal. To preprocess our data, we can use fairseq-preprocess to build our vocabulary and also binarize the training data. cd fairseq/DATASET=/path/to/datasetfairseq-preprocess \--only-source \--trainpref $DATASET/train.txt \--validpref $DATASET/valid.txt \--testpref $DATASET/test.txt \--destdir data-bin/summary \--workers 20 After executing the above commands, the preprocessed data will be saved in the directory specified by the --destdir . Finally, we can start training the transformer! To train a model, we can use the fairseq-train command: CUDA_VISIBLE_DEVICES=0 fairseq-train --task language_modeling \data-bin/summary \--save-dir checkpoints/transformer_summary \--arch transformer_lm --share-decoder-input-output-embed \--dropout 0.1 \--optimizer adam --adam-betas '(0.9, 0.98)' --weight-decay 0.01 --clip-norm 0.0 \--lr 0.0005 --lr-scheduler inverse_sqrt --warmup-updates 4000 --warmup-init-lr 1e-07 \--tokens-per-sample 512 --sample-break-mode none \--max-tokens 2048 --update-freq 16 \--fp16 \--max-update 50000 \--max-epoch 12 In our case, we specify the GPU to use as the 0th (CUDA_VISIBLE_DEVICES), task as language modeling (--task), the data in data-bin/summary , the architecture as a transformer language model (--arch ), the number of epochs to train as 12 (--max-epoch ) , and other hyperparameters. After training, the best checkpoint of the model will be saved in the directory specified by --save-dir . 12 epochs will take a while, so sit back while your model trains! Of course, you can also reduce the number of epochs to train according to your needs. The following output is shown when the training is complete: Note that in each epoch, the relevant numbers are shown, such as loss and perplexity. These could be helpful for evaluating the model during the training process. After your model finishes training, you can evaluate the resulting language model using fairseq-eval-lm : fairseq-eval-lm data-bin/summary \--path checkpoints/transformer_summary/checkpoint_best.pt \--max-sentences 2 \--tokens-per-sample 512 \--context-window 400 Here the test data will be evaluated to score the language model (the train and validation data are used in the training phase to find the optimized hyperparameters for the model). The following shows the command output after evaluation: As you can see, the loss of our model is 9.8415 and perplexity is 917.48 (in base 2). After training the model, we can try to generate some samples using our language model. To generate, we can use the fairseq-interactive command to create an interactive session for generation: fairseq-interactive data-bin/summary \--task language_modeling \--path checkpoints/transformer_summary/checkpoint_best.pt \--beam 5 During the interactive session, the program will prompt you an input text to enter. After the input text is entered, the model will generate tokens after the input. A generation sample given The book takes place as input is this: The book takes place in the story of the story of the story of the story of the story of the story of the story of the story of the story of the story of the characters... The generation is repetitive which means the model needs to be trained with better parameters. The above command uses beam search with beam size of 5. We can also use sampling techniques like top-k sampling: fairseq-interactive data-bin/summary \--task language_modeling \--path checkpoints/transformer_summary/checkpoint_best.pt \--sampling --beam 1 --sampling-topk 10 and top-p sampling: fairseq-interactive data-bin/summary \--task language_modeling \--path checkpoints/transformer_summary/checkpoint_best.pt \--sampling --beam 1 --sampling-topp 0.8 Note that when using top-k or top-sampling, we have to add the beam=1 to suppress the error that arises when --beam does not equal to--nbest . This seems to be a bug. In this blog post, we have trained a classic transformer model on book summaries using the popular Fairseq library! Although the generation sample is repetitive, this article serves as a guide to walk you through running a transformer on language modeling. Take a look at my other posts if interested :D towardsdatascience.com towardsdatascience.com towardsdatascience.com towardsdatascience.com [1] A. Vaswani, N. Shazeer, N. Parmar, etc., Attention Is All You Need (2017), 31st Conference on Neural Information Processing Systems [2] L. Shao, S. Gouws, D. Britz, etc., Generating High-Quality and Informative Conversation Responses with Sequence-to-Sequence Models (2017), Empirical Methods in Natural Language Processing [3] A. Fan, M. Lewis, Y. Dauphin, Hierarchical Neural Story Generation (2018), Association of Computational Linguistics [4] A. Holtzman, J. Buys, L. Du, etc., The Curious Case of Neural Text Degeneration (2019), International Conference on Learning Representations [5] Fairseq Github, Facebook AI Research [6] Fairseq Documentation, Facebook AI Research
[ { "code": null, "e": 810, "s": 172, "text": "Recent trends in Natural Language Processing have been building upon one of the biggest breakthroughs in the history of the field: the Transformer. The Transformer is a model architecture researched mainly by Google Brain and Google Research. It was initially shown to achieve state-of-the-art in the translation task but was later shown to be effective in just about any NLP task when it became massively adopted. The transformer architecture consists of a stack of encoders and decoders with self-attention layers that help the model pay attention to respective inputs. You can learn more about transformers in the original paper here." }, { "code": null, "e": 1283, "s": 810, "text": "In this post, we will be showing you how to implement the transformer for the language modeling task. Language modeling is the task of assigning probability to sentences in a language. The goal for language modeling is for the model to assign high probability to real sentences in our dataset so that it will be able to generate fluent sentences that are close to human-level through a decoder scheme. We will be using the Fairseq library for implementing the transformer." }, { "code": null, "e": 1306, "s": 1283, "text": "towardsdatascience.com" }, { "code": null, "e": 1636, "s": 1306, "text": "In this article, we will be again using the CMU Book Summary Dataset to train the Transformer model. You can refer to Step 1 of the blog post to acquire and prepare the dataset. After preparing the dataset, you should have the train.txt, valid.txt, and test.txt files ready that correspond to the three partitions of the dataset." }, { "code": null, "e": 1879, "s": 1636, "text": "If you haven’t heard of Fairseq, it is a popular NLP library developed by Facebook AI for implementing custom models for translation, summarization, language modeling, and other generation tasks. You can check out my comments on Fairseq here." }, { "code": null, "e": 1954, "s": 1879, "text": "Now, in order to download and install Fairseq, run the following commands:" }, { "code": null, "e": 2034, "s": 1954, "text": "git clone https://github.com/pytorch/fairseqcd fairseqpip install --editable ./" }, { "code": null, "e": 2133, "s": 2034, "text": "You can also choose to install NVIDIA’s apex library to enable faster training if your GPU allows:" }, { "code": null, "e": 2387, "s": 2133, "text": "git clone https://github.com/NVIDIA/apexcd apexpip install -v --no-cache-dir --global-option=\"--cpp_ext\" --global-option=\"--cuda_ext\" \\ --global-option=\"--deprecated_fused_adam\" --global-option=\"--xentropy\" \\ --global-option=\"--fast_multihead_attn\" ./" }, { "code": null, "e": 2467, "s": 2387, "text": "Now, you have successfully installed Fairseq and finally we are all good to go!" }, { "code": null, "e": 2748, "s": 2467, "text": "To preprocess the dataset, we can use the fairseq command-line tool, which makes it easy for developers and researchers to directly run operations from the terminal. To preprocess our data, we can use fairseq-preprocess to build our vocabulary and also binarize the training data." }, { "code": null, "e": 2953, "s": 2748, "text": "cd fairseq/DATASET=/path/to/datasetfairseq-preprocess \\--only-source \\--trainpref $DATASET/train.txt \\--validpref $DATASET/valid.txt \\--testpref $DATASET/test.txt \\--destdir data-bin/summary \\--workers 20" }, { "code": null, "e": 3071, "s": 2953, "text": "After executing the above commands, the preprocessed data will be saved in the directory specified by the --destdir ." }, { "code": null, "e": 3175, "s": 3071, "text": "Finally, we can start training the transformer! To train a model, we can use the fairseq-train command:" }, { "code": null, "e": 3669, "s": 3175, "text": "CUDA_VISIBLE_DEVICES=0 fairseq-train --task language_modeling \\data-bin/summary \\--save-dir checkpoints/transformer_summary \\--arch transformer_lm --share-decoder-input-output-embed \\--dropout 0.1 \\--optimizer adam --adam-betas '(0.9, 0.98)' --weight-decay 0.01 --clip-norm 0.0 \\--lr 0.0005 --lr-scheduler inverse_sqrt --warmup-updates 4000 --warmup-init-lr 1e-07 \\--tokens-per-sample 512 --sample-break-mode none \\--max-tokens 2048 --update-freq 16 \\--fp16 \\--max-update 50000 \\--max-epoch 12" }, { "code": null, "e": 4056, "s": 3669, "text": "In our case, we specify the GPU to use as the 0th (CUDA_VISIBLE_DEVICES), task as language modeling (--task), the data in data-bin/summary , the architecture as a transformer language model (--arch ), the number of epochs to train as 12 (--max-epoch ) , and other hyperparameters. After training, the best checkpoint of the model will be saved in the directory specified by --save-dir ." }, { "code": null, "e": 4269, "s": 4056, "text": "12 epochs will take a while, so sit back while your model trains! Of course, you can also reduce the number of epochs to train according to your needs. The following output is shown when the training is complete:" }, { "code": null, "e": 4432, "s": 4269, "text": "Note that in each epoch, the relevant numbers are shown, such as loss and perplexity. These could be helpful for evaluating the model during the training process." }, { "code": null, "e": 4538, "s": 4432, "text": "After your model finishes training, you can evaluate the resulting language model using fairseq-eval-lm :" }, { "code": null, "e": 4696, "s": 4538, "text": "fairseq-eval-lm data-bin/summary \\--path checkpoints/transformer_summary/checkpoint_best.pt \\--max-sentences 2 \\--tokens-per-sample 512 \\--context-window 400" }, { "code": null, "e": 4934, "s": 4696, "text": "Here the test data will be evaluated to score the language model (the train and validation data are used in the training phase to find the optimized hyperparameters for the model). The following shows the command output after evaluation:" }, { "code": null, "e": 5020, "s": 4934, "text": "As you can see, the loss of our model is 9.8415 and perplexity is 917.48 (in base 2)." }, { "code": null, "e": 5213, "s": 5020, "text": "After training the model, we can try to generate some samples using our language model. To generate, we can use the fairseq-interactive command to create an interactive session for generation:" }, { "code": null, "e": 5345, "s": 5213, "text": "fairseq-interactive data-bin/summary \\--task language_modeling \\--path checkpoints/transformer_summary/checkpoint_best.pt \\--beam 5" }, { "code": null, "e": 5575, "s": 5345, "text": "During the interactive session, the program will prompt you an input text to enter. After the input text is entered, the model will generate tokens after the input. A generation sample given The book takes place as input is this:" }, { "code": null, "e": 5747, "s": 5575, "text": "The book takes place in the story of the story of the story of the story of the story of the story of the story of the story of the story of the story of the characters..." }, { "code": null, "e": 5955, "s": 5747, "text": "The generation is repetitive which means the model needs to be trained with better parameters. The above command uses beam search with beam size of 5. We can also use sampling techniques like top-k sampling:" }, { "code": null, "e": 6117, "s": 5955, "text": "fairseq-interactive data-bin/summary \\--task language_modeling \\--path checkpoints/transformer_summary/checkpoint_best.pt \\--sampling --beam 1 --sampling-topk 10" }, { "code": null, "e": 6137, "s": 6117, "text": "and top-p sampling:" }, { "code": null, "e": 6300, "s": 6137, "text": "fairseq-interactive data-bin/summary \\--task language_modeling \\--path checkpoints/transformer_summary/checkpoint_best.pt \\--sampling --beam 1 --sampling-topp 0.8" }, { "code": null, "e": 6467, "s": 6300, "text": "Note that when using top-k or top-sampling, we have to add the beam=1 to suppress the error that arises when --beam does not equal to--nbest . This seems to be a bug." }, { "code": null, "e": 6771, "s": 6467, "text": "In this blog post, we have trained a classic transformer model on book summaries using the popular Fairseq library! Although the generation sample is repetitive, this article serves as a guide to walk you through running a transformer on language modeling. Take a look at my other posts if interested :D" }, { "code": null, "e": 6794, "s": 6771, "text": "towardsdatascience.com" }, { "code": null, "e": 6817, "s": 6794, "text": "towardsdatascience.com" }, { "code": null, "e": 6840, "s": 6817, "text": "towardsdatascience.com" }, { "code": null, "e": 6863, "s": 6840, "text": "towardsdatascience.com" }, { "code": null, "e": 6999, "s": 6863, "text": "[1] A. Vaswani, N. Shazeer, N. Parmar, etc., Attention Is All You Need (2017), 31st Conference on Neural Information Processing Systems" }, { "code": null, "e": 7191, "s": 6999, "text": "[2] L. Shao, S. Gouws, D. Britz, etc., Generating High-Quality and Informative Conversation Responses with Sequence-to-Sequence Models (2017), Empirical Methods in Natural Language Processing" }, { "code": null, "e": 7311, "s": 7191, "text": "[3] A. Fan, M. Lewis, Y. Dauphin, Hierarchical Neural Story Generation (2018), Association of Computational Linguistics" }, { "code": null, "e": 7456, "s": 7311, "text": "[4] A. Holtzman, J. Buys, L. Du, etc., The Curious Case of Neural Text Degeneration (2019), International Conference on Learning Representations" }, { "code": null, "e": 7497, "s": 7456, "text": "[5] Fairseq Github, Facebook AI Research" } ]
How to remove characters except digits from string in Python?
We have a variety of ways to achieve this. We can filter out non digit characters using for ... if statement. For example: >>> s = "H3ll0 P30P13" >>> ''.join(i for i in s if i.isdigit()) '303013' We can also use filter and a lambda function to filter out the characters. For example: >>> s = "H3ll0 P30P13" >>> filter(lambda x: x.isdigit(), s) '303013' Though an overkill for such a simple task, we can also use a regex for achieving the same thing. The \D character(non digit) can be replaced by an empty string. For example: >>> import re >>> s = "H3ll0 P30P13" >>> re.sub("\D", "", s) '303013'
[ { "code": null, "e": 1185, "s": 1062, "text": "We have a variety of ways to achieve this. We can filter out non digit characters using for ... if statement. For example:" }, { "code": null, "e": 1258, "s": 1185, "text": ">>> s = \"H3ll0 P30P13\"\n>>> ''.join(i for i in s if i.isdigit())\n'303013'" }, { "code": null, "e": 1346, "s": 1258, "text": "We can also use filter and a lambda function to filter out the characters. For example:" }, { "code": null, "e": 1415, "s": 1346, "text": ">>> s = \"H3ll0 P30P13\"\n>>> filter(lambda x: x.isdigit(), s)\n'303013'" }, { "code": null, "e": 1589, "s": 1415, "text": "Though an overkill for such a simple task, we can also use a regex for achieving the same thing. The \\D character(non digit) can be replaced by an empty string. For example:" }, { "code": null, "e": 1659, "s": 1589, "text": ">>> import re\n>>> s = \"H3ll0 P30P13\"\n>>> re.sub(\"\\D\", \"\", s)\n'303013'" } ]
Environment & Package Management. Beginner’s Guide To Anaconda | by Ujjwal Dalmia | Towards Data Science
A good handle on Package and Environment management ensures that we continue to avail the benefits of the latest package functionalities while ensuring that projects running on older package releases do not break down. This tutorial is a beginner’s guide to learn both package and environment management using Conda that comes bundled with Anaconda distribution. If you are new to Python and don’t have Anaconda setup on your system, we recommend that you read through this tutorial before proceeding further. Conda is known to be a complete environment and package management tool. It does wonders when it comes to cross-platform package installation and environment management. Following is the list of benefits that one experiences when working with it. Conda installs packages that are in binary format. A binary package format means that all the package dependencies, whether Python or Non-Python based, are kept pre-compiled in the package bundle and hence ensures smooth and faster package installations. At the heart of Conda is SAT solver. SAT solver guarantees that any version update of an existing Python package is in line with the environmental requirements, which means that there is no impact on existing Python codes. Conda is a complete manager. It not only supports package management but also handles environments efficiently. Consider a scenario where you are working on multiple Python projects. These projects are working on a shared Python environment and are using the same packages. If one project warrants the need to update one of the shared packages, there is a possibility that post update, the other project might not function as expected. It is because the updated package might modify/ deprecate functionalities that were supported by earlier versions. To ensure that the projects’ functionalities don’t interfere with each other, maintaining separate environments for these projects is highly recommended. This section will go through a few of the most common tasks associated with Python environment management. A list of these is as follows: New environment creation Listing existing environments Using a specific environment Deleting a specific environment Sharing environment with others using .yml files Creating a new Python environment using .yml files To create a new Python environment, open the Anaconda prompt, and use the following command: #### Syntaxconda create --name environment_name packages#### Sample Commandconda create --name new_env pandas=0.22 numpy Explanation The syntax to create the new Python environment starts with the keyword conda followed by another keyword, create. We then pass the argument --name and the actual environment name. Finally, we add the list of packages we want to install. If we do not provide any package name, the environment creation will be blank, which means that even the python instance will not be available in this environment. When working on multiple projects, it is common for one to forget the name of the various environment they have created. Use the following command on the command line to get the list of the existing environment: #### Syntax/ Commandconda env list Notice that this command is a keyword-based command starting with conda followed by env and list. To activate a specific environment or to switch from one to another, use the following command: #### Syntaxconda activate environment_name#### Sample Commandconda activate new_env Explanation Notice the presence of the activated environment name before the command prompt. It indicates that the environment is now active. Conda, by default, activates the base environment if the environment name is not there. Any python script executed using the command prompt will get executed in the activated environment. Removing environments using Conda is very simple. We can use the following command for the same: #### Syntaxconda env remove --name environment_name#### Sample Commandconda env remove --name new_env When sharing your Python project with others, it is also necessary to share the complete environment used by your Python project. Conda provides an option to export the environment details into a .yml file. We can then share this file along with the project folders. #### Syntaxconda env export --name environment_name --file file_name#### Sample Commandconda env export --name new_env --file new_env.yml Explanation In the command, we use the keyword export after conda and env The --name argument is optional. Without it, Conda exports the currently active environment. Argument --file provides the option to name the exported file. Setting up the Python environment using the .yml file is simple. Replace the keyword export with keyword create. Refer to the sample command below: #### Syntaxconda env create --name environment_name --file file_name#### Sample Commandconda env create --name new_env --file new_env.yml Explanation Just like the export command, we have used arguments - -name & --file to indicate the name of the new environment to be created and the .yml file which contains the package details. Without the --name argument, the new environment will have the same name as the name of the .yml file. This section will go through a few of the most common tasks associated with package management. A list of these is as follows: Listing packages in a specific environment Installing new package Installing a package from a specific channel Updating an existing package Removing packages To get a list of all the packages in a specific Python environment, activate it first(refer to point 3 in environment management). Once done, use the following command on the command prompt: #### Activate the preferred environmentconda activate new_env#### Get a list of all the packagesconda list Use the following command to install a new package in your python environment: #### Syntaxconda install package_name#### Sample commandconda install numpy After we enter the command, Conda will resolve the environment requirements and will identify package dependencies. It then prompts us to check if we want to proceed with these additional dependencies. When prompted, press the letter y and press enter. The package will get installed. Just like pip uses python package index (PyPI) for sourcing the package wheels, Conda has a base channel that is its default source of package binaries. If working behind a firewall (in a secure corporate environment) or if the required package is not available in the base channel, we are required to source them from alternate channels. In the corporate setups, these channels are custom built by IT support teams. One of the commonly used alternate channels is conda-forge. The process of installation remains the same. The only change is the addition of a command argument that indicates the use of a specific channel for package installation. #### Syntaxconda install -c channel_name package_name#### Sample commandconda install -c conda-forge geopandas Notice the use of command-line argument -c and the channel name conda-forge used just before specifying the package name, geopandas For this, replace the install keyword with another keyword update. Sample command below: #### Syntaxconda update package_name#### Sample Commandconda update pandas To remove an existing package, replace the keyword update with another keyword remove. Sample code added below: #### Syntaxconda remove package_name#### Sample commandconda remove pandas I hope this tutorial was informative, and you now have a ready guide for your package and environment management needs. I will keep adding more to the getting started guides. Till then: HAPPY LEARNING ! ! !
[ { "code": null, "e": 681, "s": 171, "text": "A good handle on Package and Environment management ensures that we continue to avail the benefits of the latest package functionalities while ensuring that projects running on older package releases do not break down. This tutorial is a beginner’s guide to learn both package and environment management using Conda that comes bundled with Anaconda distribution. If you are new to Python and don’t have Anaconda setup on your system, we recommend that you read through this tutorial before proceeding further." }, { "code": null, "e": 928, "s": 681, "text": "Conda is known to be a complete environment and package management tool. It does wonders when it comes to cross-platform package installation and environment management. Following is the list of benefits that one experiences when working with it." }, { "code": null, "e": 1183, "s": 928, "text": "Conda installs packages that are in binary format. A binary package format means that all the package dependencies, whether Python or Non-Python based, are kept pre-compiled in the package bundle and hence ensures smooth and faster package installations." }, { "code": null, "e": 1406, "s": 1183, "text": "At the heart of Conda is SAT solver. SAT solver guarantees that any version update of an existing Python package is in line with the environmental requirements, which means that there is no impact on existing Python codes." }, { "code": null, "e": 1518, "s": 1406, "text": "Conda is a complete manager. It not only supports package management but also handles environments efficiently." }, { "code": null, "e": 2111, "s": 1518, "text": "Consider a scenario where you are working on multiple Python projects. These projects are working on a shared Python environment and are using the same packages. If one project warrants the need to update one of the shared packages, there is a possibility that post update, the other project might not function as expected. It is because the updated package might modify/ deprecate functionalities that were supported by earlier versions. To ensure that the projects’ functionalities don’t interfere with each other, maintaining separate environments for these projects is highly recommended." }, { "code": null, "e": 2249, "s": 2111, "text": "This section will go through a few of the most common tasks associated with Python environment management. A list of these is as follows:" }, { "code": null, "e": 2274, "s": 2249, "text": "New environment creation" }, { "code": null, "e": 2304, "s": 2274, "text": "Listing existing environments" }, { "code": null, "e": 2333, "s": 2304, "text": "Using a specific environment" }, { "code": null, "e": 2365, "s": 2333, "text": "Deleting a specific environment" }, { "code": null, "e": 2414, "s": 2365, "text": "Sharing environment with others using .yml files" }, { "code": null, "e": 2465, "s": 2414, "text": "Creating a new Python environment using .yml files" }, { "code": null, "e": 2558, "s": 2465, "text": "To create a new Python environment, open the Anaconda prompt, and use the following command:" }, { "code": null, "e": 2680, "s": 2558, "text": "#### Syntaxconda create --name environment_name packages#### Sample Commandconda create --name new_env pandas=0.22 numpy " }, { "code": null, "e": 2692, "s": 2680, "text": "Explanation" }, { "code": null, "e": 2807, "s": 2692, "text": "The syntax to create the new Python environment starts with the keyword conda followed by another keyword, create." }, { "code": null, "e": 2873, "s": 2807, "text": "We then pass the argument --name and the actual environment name." }, { "code": null, "e": 2930, "s": 2873, "text": "Finally, we add the list of packages we want to install." }, { "code": null, "e": 3094, "s": 2930, "text": "If we do not provide any package name, the environment creation will be blank, which means that even the python instance will not be available in this environment." }, { "code": null, "e": 3306, "s": 3094, "text": "When working on multiple projects, it is common for one to forget the name of the various environment they have created. Use the following command on the command line to get the list of the existing environment:" }, { "code": null, "e": 3341, "s": 3306, "text": "#### Syntax/ Commandconda env list" }, { "code": null, "e": 3439, "s": 3341, "text": "Notice that this command is a keyword-based command starting with conda followed by env and list." }, { "code": null, "e": 3535, "s": 3439, "text": "To activate a specific environment or to switch from one to another, use the following command:" }, { "code": null, "e": 3619, "s": 3535, "text": "#### Syntaxconda activate environment_name#### Sample Commandconda activate new_env" }, { "code": null, "e": 3631, "s": 3619, "text": "Explanation" }, { "code": null, "e": 3761, "s": 3631, "text": "Notice the presence of the activated environment name before the command prompt. It indicates that the environment is now active." }, { "code": null, "e": 3849, "s": 3761, "text": "Conda, by default, activates the base environment if the environment name is not there." }, { "code": null, "e": 3949, "s": 3849, "text": "Any python script executed using the command prompt will get executed in the activated environment." }, { "code": null, "e": 4046, "s": 3949, "text": "Removing environments using Conda is very simple. We can use the following command for the same:" }, { "code": null, "e": 4148, "s": 4046, "text": "#### Syntaxconda env remove --name environment_name#### Sample Commandconda env remove --name new_env" }, { "code": null, "e": 4415, "s": 4148, "text": "When sharing your Python project with others, it is also necessary to share the complete environment used by your Python project. Conda provides an option to export the environment details into a .yml file. We can then share this file along with the project folders." }, { "code": null, "e": 4553, "s": 4415, "text": "#### Syntaxconda env export --name environment_name --file file_name#### Sample Commandconda env export --name new_env --file new_env.yml" }, { "code": null, "e": 4565, "s": 4553, "text": "Explanation" }, { "code": null, "e": 4627, "s": 4565, "text": "In the command, we use the keyword export after conda and env" }, { "code": null, "e": 4720, "s": 4627, "text": "The --name argument is optional. Without it, Conda exports the currently active environment." }, { "code": null, "e": 4783, "s": 4720, "text": "Argument --file provides the option to name the exported file." }, { "code": null, "e": 4931, "s": 4783, "text": "Setting up the Python environment using the .yml file is simple. Replace the keyword export with keyword create. Refer to the sample command below:" }, { "code": null, "e": 5069, "s": 4931, "text": "#### Syntaxconda env create --name environment_name --file file_name#### Sample Commandconda env create --name new_env --file new_env.yml" }, { "code": null, "e": 5081, "s": 5069, "text": "Explanation" }, { "code": null, "e": 5263, "s": 5081, "text": "Just like the export command, we have used arguments - -name & --file to indicate the name of the new environment to be created and the .yml file which contains the package details." }, { "code": null, "e": 5366, "s": 5263, "text": "Without the --name argument, the new environment will have the same name as the name of the .yml file." }, { "code": null, "e": 5493, "s": 5366, "text": "This section will go through a few of the most common tasks associated with package management. A list of these is as follows:" }, { "code": null, "e": 5536, "s": 5493, "text": "Listing packages in a specific environment" }, { "code": null, "e": 5559, "s": 5536, "text": "Installing new package" }, { "code": null, "e": 5604, "s": 5559, "text": "Installing a package from a specific channel" }, { "code": null, "e": 5633, "s": 5604, "text": "Updating an existing package" }, { "code": null, "e": 5651, "s": 5633, "text": "Removing packages" }, { "code": null, "e": 5842, "s": 5651, "text": "To get a list of all the packages in a specific Python environment, activate it first(refer to point 3 in environment management). Once done, use the following command on the command prompt:" }, { "code": null, "e": 5949, "s": 5842, "text": "#### Activate the preferred environmentconda activate new_env#### Get a list of all the packagesconda list" }, { "code": null, "e": 6028, "s": 5949, "text": "Use the following command to install a new package in your python environment:" }, { "code": null, "e": 6104, "s": 6028, "text": "#### Syntaxconda install package_name#### Sample commandconda install numpy" }, { "code": null, "e": 6389, "s": 6104, "text": "After we enter the command, Conda will resolve the environment requirements and will identify package dependencies. It then prompts us to check if we want to proceed with these additional dependencies. When prompted, press the letter y and press enter. The package will get installed." }, { "code": null, "e": 6542, "s": 6389, "text": "Just like pip uses python package index (PyPI) for sourcing the package wheels, Conda has a base channel that is its default source of package binaries." }, { "code": null, "e": 7037, "s": 6542, "text": "If working behind a firewall (in a secure corporate environment) or if the required package is not available in the base channel, we are required to source them from alternate channels. In the corporate setups, these channels are custom built by IT support teams. One of the commonly used alternate channels is conda-forge. The process of installation remains the same. The only change is the addition of a command argument that indicates the use of a specific channel for package installation." }, { "code": null, "e": 7148, "s": 7037, "text": "#### Syntaxconda install -c channel_name package_name#### Sample commandconda install -c conda-forge geopandas" }, { "code": null, "e": 7280, "s": 7148, "text": "Notice the use of command-line argument -c and the channel name conda-forge used just before specifying the package name, geopandas" }, { "code": null, "e": 7369, "s": 7280, "text": "For this, replace the install keyword with another keyword update. Sample command below:" }, { "code": null, "e": 7444, "s": 7369, "text": "#### Syntaxconda update package_name#### Sample Commandconda update pandas" }, { "code": null, "e": 7556, "s": 7444, "text": "To remove an existing package, replace the keyword update with another keyword remove. Sample code added below:" }, { "code": null, "e": 7631, "s": 7556, "text": "#### Syntaxconda remove package_name#### Sample commandconda remove pandas" }, { "code": null, "e": 7751, "s": 7631, "text": "I hope this tutorial was informative, and you now have a ready guide for your package and environment management needs." }, { "code": null, "e": 7817, "s": 7751, "text": "I will keep adding more to the getting started guides. Till then:" } ]
Creating Baseline Machine Learning Models | by Himanshu Sharma | Towards Data Science
Creating a Machine Learning model includes a lot of preprocessing where we manipulate features and target variables to make data ready for a machine learning model. This preprocessing includes checking the data for any missing values, cleaning the junk values, and also visualizing the data for exploratory data analysis. After performing all these operations on the data we begin with a new hustle to create a machine learning model that has higher accuracy and good performance. In order to do this, we start by creating different machine learning models and after that, we select the best performing model as the baseline model. What if I tell you that you can do all these in a few lines of code and save your time and effort to optimize your model? Yes, Dabl can do all this. It is an open-source python library that is used to perform data preprocessing, data visualization, and creating the baseline model. Let’s get started... We will start by installing Dabl using pip. The command given below will do that. pip install dabl In this step, we will import the required libraries for loading the data, performing EDA, and creating a baseline model for that dataset. import dablimport pandas as pdfrom sklearn.model_selection import train_test_splitfrom sklearn.datasets import load_digits For this article, we will be using the famous Diabetes dataset which can be downloaded easily from online sources. df = pd.read_csv("Diabetes.csv") In this step, we will clean the data using the clean function of the Dabl and also find out the data types of all the features and target variables. dia_clean = dabl.clean(df, verbose=0) types = dabl.detect_types(dia_clean)types In this step, we will create visualizations to see data patterns and gather some initial insights about the data. dabl.plot(dia_clean, 'Outcome') This is the final step, where we will find out a baseline model for our data in a single line of code. Dabl runs different models in the backend and finds out the best-performing model. features = ['Pregnancies', 'Glucose','BloodPressure','SkinThickness','Insulin','BMI','DiabetesPedigreeFunction','Age']Y = df['Outcome']X = df[features]X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.2)sc = dabl.SimpleClassifier().fit(X_train, Y_train)print("Accuracy score", sc.score(X_test, Y_test)) Here you can see how Dabl shows us the best performing model with its accuracy score. We can select this model for further tuning and optimization. In this article, we saw how Dabl is useful for Data preprocessing, performing EDA, and creating a baseline model. Go ahead try this with a different dataset and let me know your comments in the response section. This article is in collaboration with Piyush Ingale. Thanks for reading! If you want to get in touch with me, feel free to reach me at [email protected] or my LinkedIn Profile. You can view my Github profile for different data science projects and packages tutorials. Also, feel free to explore my profile and read different articles I have written related to Data Science.
[ { "code": null, "e": 494, "s": 172, "text": "Creating a Machine Learning model includes a lot of preprocessing where we manipulate features and target variables to make data ready for a machine learning model. This preprocessing includes checking the data for any missing values, cleaning the junk values, and also visualizing the data for exploratory data analysis." }, { "code": null, "e": 804, "s": 494, "text": "After performing all these operations on the data we begin with a new hustle to create a machine learning model that has higher accuracy and good performance. In order to do this, we start by creating different machine learning models and after that, we select the best performing model as the baseline model." }, { "code": null, "e": 1086, "s": 804, "text": "What if I tell you that you can do all these in a few lines of code and save your time and effort to optimize your model? Yes, Dabl can do all this. It is an open-source python library that is used to perform data preprocessing, data visualization, and creating the baseline model." }, { "code": null, "e": 1107, "s": 1086, "text": "Let’s get started..." }, { "code": null, "e": 1189, "s": 1107, "text": "We will start by installing Dabl using pip. The command given below will do that." }, { "code": null, "e": 1206, "s": 1189, "text": "pip install dabl" }, { "code": null, "e": 1344, "s": 1206, "text": "In this step, we will import the required libraries for loading the data, performing EDA, and creating a baseline model for that dataset." }, { "code": null, "e": 1467, "s": 1344, "text": "import dablimport pandas as pdfrom sklearn.model_selection import train_test_splitfrom sklearn.datasets import load_digits" }, { "code": null, "e": 1582, "s": 1467, "text": "For this article, we will be using the famous Diabetes dataset which can be downloaded easily from online sources." }, { "code": null, "e": 1615, "s": 1582, "text": "df = pd.read_csv(\"Diabetes.csv\")" }, { "code": null, "e": 1764, "s": 1615, "text": "In this step, we will clean the data using the clean function of the Dabl and also find out the data types of all the features and target variables." }, { "code": null, "e": 1802, "s": 1764, "text": "dia_clean = dabl.clean(df, verbose=0)" }, { "code": null, "e": 1844, "s": 1802, "text": "types = dabl.detect_types(dia_clean)types" }, { "code": null, "e": 1958, "s": 1844, "text": "In this step, we will create visualizations to see data patterns and gather some initial insights about the data." }, { "code": null, "e": 1990, "s": 1958, "text": "dabl.plot(dia_clean, 'Outcome')" }, { "code": null, "e": 2176, "s": 1990, "text": "This is the final step, where we will find out a baseline model for our data in a single line of code. Dabl runs different models in the backend and finds out the best-performing model." }, { "code": null, "e": 2502, "s": 2176, "text": "features = ['Pregnancies', 'Glucose','BloodPressure','SkinThickness','Insulin','BMI','DiabetesPedigreeFunction','Age']Y = df['Outcome']X = df[features]X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.2)sc = dabl.SimpleClassifier().fit(X_train, Y_train)print(\"Accuracy score\", sc.score(X_test, Y_test))" }, { "code": null, "e": 2650, "s": 2502, "text": "Here you can see how Dabl shows us the best performing model with its accuracy score. We can select this model for further tuning and optimization." }, { "code": null, "e": 2862, "s": 2650, "text": "In this article, we saw how Dabl is useful for Data preprocessing, performing EDA, and creating a baseline model. Go ahead try this with a different dataset and let me know your comments in the response section." }, { "code": null, "e": 2915, "s": 2862, "text": "This article is in collaboration with Piyush Ingale." } ]
Find the column name with the largest value for each row in an R data frame.
To find the column name that has the largest value for each row in an R data frame, we can use colnames function along with apply function. For Example, if we have a data frame called df then we can find column name that has the largest value for each row by using the command as follows − df$Largest_Column<-colnames(df)[apply(df,1,which.max)] Following snippet creates a sample data frame − x1<-rnorm(20) x2<-rnorm(20) x3<-rnorm(20) df1<-data.frame(x1,x2,x3) df1 The following dataframe is created x1 x2 x3 1 -0.305888032 1.42530072 -0.60397460 2 0.077412581 1.33102088 1.09897001 3 -0.001797155 1.85365113 0.59881492 4 -0.235863387 -0.11476965 -0.23914040 5 0.641954539 -0.80069293 1.78915326 6 1.662750089 -0.48168001 -1.63141513 7 1.393413983 -0.21044222 -0.36966594 8 0.387820650 0.04998259 -0.88707049 9 -0.982245543 -1.04089646 1.51510464 10 1.540251727 -0.24360161 -0.72272136 11 0.871043177 -1.61258877 -0.08300941 12 0.894436819 1.22285505 0.25353571 13 -0.706468609 0.37879788 1.09617879 14 1.366866702 -2.36429211 0.47667869 15 0.827015705 -0.29348558 2.57175974 16 -0.709173752 -0.68338183 -0.15060505 17 0.464121383 -0.41577526 -1.52947993 18 -0.322493725 0.46212973 1.38418790 19 0.588932732 -1.98841476 0.43082069 20 -0.775650742 -0.45247281 0.62378543 To find the column name that has the largest value for each row in df1 on the above created data frame, add the following code to the above snippet − x1<-rnorm(20) x2<-rnorm(20) x3<-rnorm(20) df1<-data.frame(x1,x2,x3) df1$Largest_Column<-colnames(df1)[apply(df1,1,which.max)] df1 If you execute all the above given snippets as a single program, it generates the following Output − x1 x2 x3 Largest_Column 1 -0.305888032 1.42530072 -0.60397460 x2 2 0.077412581 1.33102088 1.09897001 x2 3 -0.001797155 1.85365113 0.59881492 x2 4 -0.235863387 -0.11476965 -0.23914040 x2 5 0.641954539 -0.80069293 1.78915326 x3 6 1.662750089 -0.48168001 -1.63141513 x1 7 1.393413983 -0.21044222 -0.36966594 x1 8 0.387820650 0.04998259 -0.88707049 x1 9 -0.982245543 -1.04089646 1.51510464 x3 10 1.540251727 -0.24360161 -0.72272136 x1 11 0.871043177 -1.61258877 -0.08300941 x1 12 0.894436819 1.22285505 0.25353571 x2 13 -0.706468609 0.37879788 1.09617879 x3 14 1.366866702 -2.36429211 0.47667869 x1 15 0.827015705 -0.29348558 2.57175974 x3 16 -0.709173752 -0.68338183 -0.15060505 x3 17 0.464121383 -0.41577526 -1.52947993 x1 18 -0.322493725 0.46212973 1.38418790 x3 19 0.588932732 -1.98841476 0.43082069 x1 20 -0.775650742 -0.45247281 0.62378543 x3 Following snippet creates a sample data frame − y1<-rpois(20,5) y2<-rpois(20,5) y3<-rpois(20,5) y4<-rpois(20,5) df2<-data.frame(y1,y2,y3,y4) df2 The following dataframe is created y1 y2 y3 y4 1 4 5 4 8 2 6 6 8 5 3 4 7 5 4 4 8 2 7 7 5 3 6 5 0 6 4 5 4 7 7 6 1 2 9 8 5 4 3 5 9 9 5 6 5 10 8 3 7 9 11 5 14 7 5 12 4 7 4 4 13 9 3 1 2 14 5 8 9 4 15 2 7 2 5 16 4 3 3 5 17 4 6 4 4 18 7 6 4 4 19 12 6 8 4 20 6 6 4 5 To find the column name that has the largest value for each row in df2 on the above created data frame, add the following code to the above snippet − y1<-rpois(20,5) y2<-rpois(20,5) y3<-rpois(20,5) y4<-rpois(20,5) df2<-data.frame(y1,y2,y3,y4) df2$Largest_Col<-colnames(df2)[apply(df2,1,which.max)] df2 If you execute all the above given snippets as a single program, it generates the following Output − y1 y2 y3 y4 Largest_Col 1 4 5 4 8 y4 2 6 6 8 5 y3 3 4 7 5 4 y2 4 8 2 7 7 y1 5 3 6 5 0 y2 6 4 5 4 7 y4 7 6 1 2 9 y4 8 5 4 3 5 y1 9 9 5 6 5 y1 10 8 3 7 9 y4 11 5 14 7 5 y2 12 4 7 4 4 y2 13 9 3 1 2 y1 14 5 8 9 4 y3 15 2 7 2 5 y2 16 4 3 3 5 y4 17 4 6 4 4 y2 18 7 6 4 4 y1 19 12 6 8 4 y1 20 6 6 4 5 y1
[ { "code": null, "e": 1202, "s": 1062, "text": "To find the column name that has the largest value for each row in an R data frame, we can use colnames function along with apply function." }, { "code": null, "e": 1352, "s": 1202, "text": "For Example, if we have a data frame called df then we can find column name that has the largest value for each row by using the command as follows −" }, { "code": null, "e": 1407, "s": 1352, "text": "df$Largest_Column<-colnames(df)[apply(df,1,which.max)]" }, { "code": null, "e": 1455, "s": 1407, "text": "Following snippet creates a sample data frame −" }, { "code": null, "e": 1527, "s": 1455, "text": "x1<-rnorm(20)\nx2<-rnorm(20)\nx3<-rnorm(20)\ndf1<-data.frame(x1,x2,x3)\ndf1" }, { "code": null, "e": 1562, "s": 1527, "text": "The following dataframe is created" }, { "code": null, "e": 2401, "s": 1562, "text": " x1 x2 x3\n1 -0.305888032 1.42530072 -0.60397460\n2 0.077412581 1.33102088 1.09897001\n3 -0.001797155 1.85365113 0.59881492\n4 -0.235863387 -0.11476965 -0.23914040\n5 0.641954539 -0.80069293 1.78915326\n6 1.662750089 -0.48168001 -1.63141513\n7 1.393413983 -0.21044222 -0.36966594\n8 0.387820650 0.04998259 -0.88707049\n9 -0.982245543 -1.04089646 1.51510464\n10 1.540251727 -0.24360161 -0.72272136\n11 0.871043177 -1.61258877 -0.08300941\n12 0.894436819 1.22285505 0.25353571\n13 -0.706468609 0.37879788 1.09617879\n14 1.366866702 -2.36429211 0.47667869\n15 0.827015705 -0.29348558 2.57175974\n16 -0.709173752 -0.68338183 -0.15060505\n17 0.464121383 -0.41577526 -1.52947993\n18 -0.322493725 0.46212973 1.38418790\n19 0.588932732 -1.98841476 0.43082069\n20 -0.775650742 -0.45247281 0.62378543" }, { "code": null, "e": 2551, "s": 2401, "text": "To find the column name that has the largest value for each row in df1 on the above created data frame, add the following code to the above snippet −" }, { "code": null, "e": 2681, "s": 2551, "text": "x1<-rnorm(20)\nx2<-rnorm(20)\nx3<-rnorm(20)\ndf1<-data.frame(x1,x2,x3)\ndf1$Largest_Column<-colnames(df1)[apply(df1,1,which.max)]\ndf1" }, { "code": null, "e": 2782, "s": 2681, "text": "If you execute all the above given snippets as a single program, it generates the following Output −" }, { "code": null, "e": 3917, "s": 2782, "text": " x1 x2 x3 Largest_Column\n1 -0.305888032 1.42530072 -0.60397460 x2\n2 0.077412581 1.33102088 1.09897001 x2\n3 -0.001797155 1.85365113 0.59881492 x2\n4 -0.235863387 -0.11476965 -0.23914040 x2\n5 0.641954539 -0.80069293 1.78915326 x3\n6 1.662750089 -0.48168001 -1.63141513 x1\n7 1.393413983 -0.21044222 -0.36966594 x1\n8 0.387820650 0.04998259 -0.88707049 x1\n9 -0.982245543 -1.04089646 1.51510464 x3\n10 1.540251727 -0.24360161 -0.72272136 x1\n11 0.871043177 -1.61258877 -0.08300941 x1\n12 0.894436819 1.22285505 0.25353571 x2\n13 -0.706468609 0.37879788 1.09617879 x3\n14 1.366866702 -2.36429211 0.47667869 x1\n15 0.827015705 -0.29348558 2.57175974 x3\n16 -0.709173752 -0.68338183 -0.15060505 x3\n17 0.464121383 -0.41577526 -1.52947993 x1\n18 -0.322493725 0.46212973 1.38418790 x3\n19 0.588932732 -1.98841476 0.43082069 x1\n20 -0.775650742 -0.45247281 0.62378543 x3" }, { "code": null, "e": 3965, "s": 3917, "text": "Following snippet creates a sample data frame −" }, { "code": null, "e": 4062, "s": 3965, "text": "y1<-rpois(20,5)\ny2<-rpois(20,5)\ny3<-rpois(20,5)\ny4<-rpois(20,5)\ndf2<-data.frame(y1,y2,y3,y4)\ndf2" }, { "code": null, "e": 4097, "s": 4062, "text": "The following dataframe is created" }, { "code": null, "e": 4412, "s": 4097, "text": " y1 y2 y3 y4\n1 4 5 4 8\n2 6 6 8 5\n3 4 7 5 4\n4 8 2 7 7\n5 3 6 5 0\n6 4 5 4 7\n7 6 1 2 9\n8 5 4 3 5\n9 9 5 6 5\n10 8 3 7 9\n11 5 14 7 5\n12 4 7 4 4\n13 9 3 1 2\n14 5 8 9 4\n15 2 7 2 5\n16 4 3 3 5\n17 4 6 4 4\n18 7 6 4 4\n19 12 6 8 4\n20 6 6 4 5" }, { "code": null, "e": 4562, "s": 4412, "text": "To find the column name that has the largest value for each row in df2 on the above created data frame, add the following code to the above snippet −" }, { "code": null, "e": 4714, "s": 4562, "text": "y1<-rpois(20,5)\ny2<-rpois(20,5)\ny3<-rpois(20,5)\ny4<-rpois(20,5)\ndf2<-data.frame(y1,y2,y3,y4)\ndf2$Largest_Col<-colnames(df2)[apply(df2,1,which.max)]\ndf2" }, { "code": null, "e": 4815, "s": 4714, "text": "If you execute all the above given snippets as a single program, it generates the following Output −" }, { "code": null, "e": 5382, "s": 4815, "text": " y1 y2 y3 y4 Largest_Col\n1 4 5 4 8 y4\n2 6 6 8 5 y3\n3 4 7 5 4 y2\n4 8 2 7 7 y1\n5 3 6 5 0 y2\n6 4 5 4 7 y4\n7 6 1 2 9 y4\n8 5 4 3 5 y1\n9 9 5 6 5 y1\n10 8 3 7 9 y4\n11 5 14 7 5 y2\n12 4 7 4 4 y2\n13 9 3 1 2 y1\n14 5 8 9 4 y3\n15 2 7 2 5 y2\n16 4 3 3 5 y4\n17 4 6 4 4 y2\n18 7 6 4 4 y1\n19 12 6 8 4 y1\n20 6 6 4 5 y1" } ]
What are user defined data types in C#?
The User defined data types in C# are structures and enumeration. In C#, a structure is a value type data type. It helps you to make a single variable hold related data of various data types. The struct keyword is used for creating a structure. The C# structures have the following features − Structures can have methods, fields, indexers, properties, operator methods, and events. Structures can have defined constructors, but not destructors. However, you cannot define a default constructor for a structure. The default constructor is automatically defined and cannot be changed. Unlike classes, structures cannot inherit other structures or classes. Structures cannot be used as a base for other structures or classes. A structure can implement one or more interfaces. Structure members cannot be specified as abstract, virtual, or protected. Enum is Enumeration to store a set of named constants like year, product, month, season, etc. The default value of Enum constants starts from 0 and increments. It has fixed set of constants and can be traversed easily. Let us see an example. We have set the enum like this − public enum Vehicle { Car, Bus, Truck }
[ { "code": null, "e": 1128, "s": 1062, "text": "The User defined data types in C# are structures and enumeration." }, { "code": null, "e": 1307, "s": 1128, "text": "In C#, a structure is a value type data type. It helps you to make a single variable hold related data of various data types. The struct keyword is used for creating a structure." }, { "code": null, "e": 1355, "s": 1307, "text": "The C# structures have the following features −" }, { "code": null, "e": 1444, "s": 1355, "text": "Structures can have methods, fields, indexers, properties, operator methods, and events." }, { "code": null, "e": 1645, "s": 1444, "text": "Structures can have defined constructors, but not destructors. However, you cannot define a default constructor for a structure. The default constructor is automatically defined and cannot be changed." }, { "code": null, "e": 1716, "s": 1645, "text": "Unlike classes, structures cannot inherit other structures or classes." }, { "code": null, "e": 1785, "s": 1716, "text": "Structures cannot be used as a base for other structures or classes." }, { "code": null, "e": 1835, "s": 1785, "text": "A structure can implement one or more interfaces." }, { "code": null, "e": 1909, "s": 1835, "text": "Structure members cannot be specified as abstract, virtual, or protected." }, { "code": null, "e": 2003, "s": 1909, "text": "Enum is Enumeration to store a set of named constants like year, product, month, season, etc." }, { "code": null, "e": 2128, "s": 2003, "text": "The default value of Enum constants starts from 0 and increments. It has fixed set of constants and can be traversed easily." }, { "code": null, "e": 2151, "s": 2128, "text": "Let us see an example." }, { "code": null, "e": 2184, "s": 2151, "text": "We have set the enum like this −" }, { "code": null, "e": 2224, "s": 2184, "text": "public enum Vehicle { Car, Bus, Truck }" } ]
C++ Program to Implement Sorted Array
A sorted array is an array in which each of the elements are sorted in some order such as numerical, alphabetical etc. There are many algorithms to sort a numerical array such as bubble sort, insertion sort, selection sort, merge sort, quick sort, heap sort etc. More details about sorting the array using selection sort are given below. The selection sort is a sorting method that yields a sorted array. It does so by repeatedly finding the smallest element in the array and interchanging it with the element at the starting of the unsorted part. A program that implements a sorted array using selection sort is given as follows. Live Demo #include<iostream> using namespace std; void selectionSort(int a[], int n) { int i, j, min, temp; for (i = 0; i < n - 1; i++) { min = i; for (j = i + 1; j < n; j++) if (a[j] < a[min]) min = j; temp = a[i]; a[i] = a[min]; a[min] = temp; } } int main() { int a[] = { 22, 91, 35, 78, 10, 8, 75, 99, 1, 67 }; int n = sizeof(a)/ sizeof(a[0]); int i; cout<<"Given array is:"<<endl; for (i = 0; i < n; i++) cout<< a[i] <<" "; cout<<endl; selectionSort(a, n); printf("\nSorted array is: \n"); for (i = 0; i < n; i++) cout<< a[i] <<" "; return 0; } Given array is: 22 91 35 78 10 8 75 99 1 67 Sorted array is: 1 8 10 22 35 67 75 78 91 99 In the above program, selectionSort() is a function that sorts the array a[] using selection sort. There are two for loops in selectionSort(). In each iteration of the outer for loop, the minimum element in the remaining array after i is found and then interchanged with the element currently at i. This is repeated until the array is sorted. This is shown below. void selectionSort(int a[], int n) { int i, j, min, temp; for (i = 0; i < n - 1; i++) { min = i; for (j = i + 1; j < n; j++) if (a[j] < a[min]) min = j; temp = a[i]; a[i] = a[min]; a[min] = temp; } } In the main() function, the array a[] is defined. Then the function selectionSort() is called with the array a[] and its size n. Finally, the sorted array is displayed. This is shown below. int main() { int a[] = { 22, 91, 35, 78, 10, 8, 75, 99, 1, 67 }; int n = sizeof(a)/ sizeof(a[0]); int i; cout<<"Given array is:"<<endl; for (i = 0; i < n; i++) cout<< a[i] <<" "; cout<<endl; selectionSort(a, n); printf("\nSorted array is: \n"); for (i = 0; i < n; i++) cout<< a[i] <<" "; return 0; }
[ { "code": null, "e": 1400, "s": 1062, "text": "A sorted array is an array in which each of the elements are sorted in some order such as numerical, alphabetical etc. There are many algorithms to sort a numerical array such as bubble sort, insertion sort, selection sort, merge sort, quick sort, heap sort etc. More details about sorting the array using selection sort are given below." }, { "code": null, "e": 1610, "s": 1400, "text": "The selection sort is a sorting method that yields a sorted array. It does so by repeatedly finding the smallest element in the array and interchanging it with the element at the starting of the unsorted part." }, { "code": null, "e": 1693, "s": 1610, "text": "A program that implements a sorted array using selection sort is given as follows." }, { "code": null, "e": 1704, "s": 1693, "text": " Live Demo" }, { "code": null, "e": 2331, "s": 1704, "text": "#include<iostream>\nusing namespace std;\nvoid selectionSort(int a[], int n) {\n int i, j, min, temp;\n for (i = 0; i < n - 1; i++) {\n min = i;\n for (j = i + 1; j < n; j++)\n if (a[j] < a[min])\n min = j;\n temp = a[i];\n a[i] = a[min];\n a[min] = temp;\n }\n}\nint main() {\n int a[] = { 22, 91, 35, 78, 10, 8, 75, 99, 1, 67 };\n int n = sizeof(a)/ sizeof(a[0]);\n int i;\n cout<<\"Given array is:\"<<endl;\n for (i = 0; i < n; i++)\n cout<< a[i] <<\" \";\n cout<<endl;\n selectionSort(a, n);\n printf(\"\\nSorted array is: \\n\");\n for (i = 0; i < n; i++)\n cout<< a[i] <<\" \";\n return 0;\n}" }, { "code": null, "e": 2420, "s": 2331, "text": "Given array is:\n22 91 35 78 10 8 75 99 1 67\nSorted array is:\n1 8 10 22 35 67 75 78 91 99" }, { "code": null, "e": 2784, "s": 2420, "text": "In the above program, selectionSort() is a function that sorts the array a[] using selection sort. There are two for loops in selectionSort(). In each iteration of the outer for loop, the minimum element in the remaining array after i is found and then interchanged with the element currently at i. This is repeated until the array is sorted. This is shown below." }, { "code": null, "e": 3035, "s": 2784, "text": "void selectionSort(int a[], int n) {\n int i, j, min, temp;\n for (i = 0; i < n - 1; i++) {\n min = i;\n for (j = i + 1; j < n; j++)\n if (a[j] < a[min])\n min = j;\n temp = a[i];\n a[i] = a[min];\n a[min] = temp;\n }\n}" }, { "code": null, "e": 3225, "s": 3035, "text": "In the main() function, the array a[] is defined. Then the function selectionSort() is called with the array a[] and its size n. Finally, the sorted array is displayed. This is shown below." }, { "code": null, "e": 3561, "s": 3225, "text": "int main() {\n int a[] = { 22, 91, 35, 78, 10, 8, 75, 99, 1, 67 };\n int n = sizeof(a)/ sizeof(a[0]);\n int i;\n cout<<\"Given array is:\"<<endl;\n for (i = 0; i < n; i++)\n cout<< a[i] <<\" \";\n cout<<endl;\n selectionSort(a, n);\n printf(\"\\nSorted array is: \\n\");\n for (i = 0; i < n; i++)\n cout<< a[i] <<\" \";\n return 0;\n}" } ]
Deleting from temporary table in SAP HANA
The temporary tables are session specific. So you would require to use truncate instead of delete as follows truncate table #temptable; Also, could you please check your release? In the recent releases, delete also works fine. Here is an example: Drop table #temptable; Create local temporary table #temptable(id integer, str nvarchar(30)); Insert into #temptable values (1,'abc'); Insert into #temptable values (2,'xyz'); Select * from #temptable; --> returns 3 rows Delete from #temptable; Select * from #temptable;--> returns 0 rows
[ { "code": null, "e": 1171, "s": 1062, "text": "The temporary tables are session specific. So you would require to use truncate instead of delete as follows" }, { "code": null, "e": 1198, "s": 1171, "text": "truncate table #temptable;" }, { "code": null, "e": 1309, "s": 1198, "text": "Also, could you please check your release? In the recent releases, delete also works fine. Here is an example:" }, { "code": null, "e": 1599, "s": 1309, "text": "Drop table #temptable;\nCreate local temporary table #temptable(id integer, str nvarchar(30));\nInsert into #temptable values (1,'abc');\nInsert into #temptable values (2,'xyz');\nSelect * from #temptable; --> returns 3 rows\nDelete from #temptable;\nSelect * from #temptable;--> returns 0 rows" } ]
Automating AWS Server Shut-Down for Deep Learning | by Harrison Jansma | Towards Data Science
Lately, I have been working with an AWS EC2 server for a machine learning project. Every article I have come across has said the same thing... “Don't forget to shutdown your EC2 instance”. Reading this gives me anxiety. Just the thought of leaving a GPU on to burn a hole in my pocket makes me irrationally sweaty. So I decided to make a Bash script to spin up a server, SSH in so I can work on my project, then shut down the server when I log out. I even saved a shortcut for the script on my Desktop so that I can start working with two clicks. Unfortunately, the process to get the script working was not straightforward and mildly infuriating. So I decided to write a quick post so the community can have the same peace of mind. *My work station is a Windows 10 PC, so these steps may be different for a Mac.* You will need to have an AWS account as well as have instantiated an AWS EC2 instance. FastAI has a tutorial on how to do this here. If this is your first time creating a GPU instance, you may have to request a limit increase for “p-type” instances. For me, this took about two days to hear back from AWS. You will need the AWS CLI so the Bash script can make calls to spin-up/shut-down the server. You can download the CLI from here. In the next few steps, we will create a User for yourself in AWS IAM and then generate and save security credentials so we can use the AWS CLI. If you have a User in your IAM console, you do not need a new one. Just make sure that you have your user's “security credentials.” If you create a user, make sure to give it “Programmatic Access”. Next, you will generate security keys for the user. In the Windows command prompt, you will need to run aws configure and follow the prompts. Fill in the Access Key ID and Secret Access Key with the key you got from the IAM console. Set your default region to the region your server is located in. With these steps completed, you should be able to access your AWS instances from the command line. Try running aws ec2 describe-instances, you should see a list of your EC2 instances. If you haven’t already, install Git-Bash from here. You will need this to run the Bash Script. The next step is to connect Git-Bash to the AWS CLI. To do this, you need to create a .bashrc file in the root directory of bash. Open up a Git-Bash terminal and do the following. cd ~vim .bashrc This will open up a text editor. Where you can paste the following. #!/bin/bashalias aws=”winpty -Xallow-non-tty -Xplain C://Program\ Files/Amazon/AWSCLI/bin/aws.exe” Now the Git-Bash terminal will recognize the command aws. If you skip this step, you will get the error bash: aws: command not found. Make sure that the file-path inserted above directs to aws.exe in your file directory. Once completed, exit the vim terminal by typing esc then:wq then hit enter. For the changes to take effect, you will need to close and re-open Git-Bash. Do this and execute aws . You should see the following. With that, we are very close to our goal. Making a Bash script that automates spinning-up, logging into, and shutting down an EC2 server. Now we can finish up and write that script. In your bash terminal navigate to wherever you want the script (for me cd C://Users/harrison/Desktop ) then run vim aws.sh #!/bin/bashINSTANCE_ID=<YOUR EC2 INSTANCE-ID HERE>SSH_KEY=<path/to/sshkey.pem>echo "Starting AWS Server."aws ec2 start-instances --instance-ids $INSTANCE_ID#Wait for server to come onlineSTARTED=Falsewhile [ "$STARTED" != "True" ]; do SERVER_STATUS=$(aws ec2 describe-instance-status --include-all-instances --instance-ids $INSTANCE_ID --output text --query 'InstanceStatuses[].InstanceState.Name') if [ "$SERVER_STATUS" == "running" ]; then STARTED=True else sleep 3 fi doneSERVER_PUBLIC_DNS=$(aws ec2 describe-instances — instance-ids $INSTANCE_ID — output text — query ‘Reservations[].Instances[].PublicDnsName’)echo “Attempting to log into server.”ssh -L localhost:8888:localhost:8888 -i $SSH_KEY ubuntu@$SERVER_PUBLIC_DNSecho “Shutting down server.”aws ec2 stop-instances — instance-ids $INSTANCE_IDecho "Sent shutdown command."sleep 1echo "Querying instance status..."aws ec2 describe-instance-status --include-all-instances --instance-ids $INSTANCE_ID --output text --query 'InstanceStatuses[]'sleep 5 *Note: I will periodically make improvements to this script.* Fill in INSTANCE_ID with the instance-id of your EC2 instance. Fill in SSH_KEY with the path to your SSH key. Now when you want to start working in your EC2 server, just run the bash script and you will be connected to your server. From there, you can run a jupyter notebook or load in python scripts from GitHub. When you exit out of the instance, the script will continue running and turn-off the server for you. aws ec2 start-instances — instance-ids $INSTANCE_ID starts the EC2 instance. You need the server’s public DNS to log-in. Unfortunately, the DNS can change when you turn the server off. The below code queries for the server’s public DNS. SERVER_PUBLIC_DNS=$(aws ec2 describe-instances — instance-ids $INSTANCE_ID — output text — query ‘Reservations[].Instances[].PublicDnsName’) Log in to the EC2 instance with ssh -L localhost:8888:localhost:8888 -i $SSH_KEY ubuntu@$SERVER_PUBLIC_DNS aws ec2 stop-instances — instance-ids $INSTANCE_ID stops the EC2 instance.
[ { "code": null, "e": 487, "s": 172, "text": "Lately, I have been working with an AWS EC2 server for a machine learning project. Every article I have come across has said the same thing... “Don't forget to shutdown your EC2 instance”. Reading this gives me anxiety. Just the thought of leaving a GPU on to burn a hole in my pocket makes me irrationally sweaty." }, { "code": null, "e": 719, "s": 487, "text": "So I decided to make a Bash script to spin up a server, SSH in so I can work on my project, then shut down the server when I log out. I even saved a shortcut for the script on my Desktop so that I can start working with two clicks." }, { "code": null, "e": 905, "s": 719, "text": "Unfortunately, the process to get the script working was not straightforward and mildly infuriating. So I decided to write a quick post so the community can have the same peace of mind." }, { "code": null, "e": 986, "s": 905, "text": "*My work station is a Windows 10 PC, so these steps may be different for a Mac.*" }, { "code": null, "e": 1292, "s": 986, "text": "You will need to have an AWS account as well as have instantiated an AWS EC2 instance. FastAI has a tutorial on how to do this here. If this is your first time creating a GPU instance, you may have to request a limit increase for “p-type” instances. For me, this took about two days to hear back from AWS." }, { "code": null, "e": 1421, "s": 1292, "text": "You will need the AWS CLI so the Bash script can make calls to spin-up/shut-down the server. You can download the CLI from here." }, { "code": null, "e": 1565, "s": 1421, "text": "In the next few steps, we will create a User for yourself in AWS IAM and then generate and save security credentials so we can use the AWS CLI." }, { "code": null, "e": 1697, "s": 1565, "text": "If you have a User in your IAM console, you do not need a new one. Just make sure that you have your user's “security credentials.”" }, { "code": null, "e": 1815, "s": 1697, "text": "If you create a user, make sure to give it “Programmatic Access”. Next, you will generate security keys for the user." }, { "code": null, "e": 2061, "s": 1815, "text": "In the Windows command prompt, you will need to run aws configure and follow the prompts. Fill in the Access Key ID and Secret Access Key with the key you got from the IAM console. Set your default region to the region your server is located in." }, { "code": null, "e": 2245, "s": 2061, "text": "With these steps completed, you should be able to access your AWS instances from the command line. Try running aws ec2 describe-instances, you should see a list of your EC2 instances." }, { "code": null, "e": 2340, "s": 2245, "text": "If you haven’t already, install Git-Bash from here. You will need this to run the Bash Script." }, { "code": null, "e": 2520, "s": 2340, "text": "The next step is to connect Git-Bash to the AWS CLI. To do this, you need to create a .bashrc file in the root directory of bash. Open up a Git-Bash terminal and do the following." }, { "code": null, "e": 2536, "s": 2520, "text": "cd ~vim .bashrc" }, { "code": null, "e": 2604, "s": 2536, "text": "This will open up a text editor. Where you can paste the following." }, { "code": null, "e": 2703, "s": 2604, "text": "#!/bin/bashalias aws=”winpty -Xallow-non-tty -Xplain C://Program\\ Files/Amazon/AWSCLI/bin/aws.exe”" }, { "code": null, "e": 2924, "s": 2703, "text": "Now the Git-Bash terminal will recognize the command aws. If you skip this step, you will get the error bash: aws: command not found. Make sure that the file-path inserted above directs to aws.exe in your file directory." }, { "code": null, "e": 3133, "s": 2924, "text": "Once completed, exit the vim terminal by typing esc then:wq then hit enter. For the changes to take effect, you will need to close and re-open Git-Bash. Do this and execute aws . You should see the following." }, { "code": null, "e": 3271, "s": 3133, "text": "With that, we are very close to our goal. Making a Bash script that automates spinning-up, logging into, and shutting down an EC2 server." }, { "code": null, "e": 3438, "s": 3271, "text": "Now we can finish up and write that script. In your bash terminal navigate to wherever you want the script (for me cd C://Users/harrison/Desktop ) then run vim aws.sh" }, { "code": null, "e": 4453, "s": 3438, "text": "#!/bin/bashINSTANCE_ID=<YOUR EC2 INSTANCE-ID HERE>SSH_KEY=<path/to/sshkey.pem>echo \"Starting AWS Server.\"aws ec2 start-instances --instance-ids $INSTANCE_ID#Wait for server to come onlineSTARTED=Falsewhile [ \"$STARTED\" != \"True\" ]; do SERVER_STATUS=$(aws ec2 describe-instance-status --include-all-instances --instance-ids $INSTANCE_ID --output text --query 'InstanceStatuses[].InstanceState.Name') if [ \"$SERVER_STATUS\" == \"running\" ]; then STARTED=True else sleep 3 fi doneSERVER_PUBLIC_DNS=$(aws ec2 describe-instances — instance-ids $INSTANCE_ID — output text — query ‘Reservations[].Instances[].PublicDnsName’)echo “Attempting to log into server.”ssh -L localhost:8888:localhost:8888 -i $SSH_KEY ubuntu@$SERVER_PUBLIC_DNSecho “Shutting down server.”aws ec2 stop-instances — instance-ids $INSTANCE_IDecho \"Sent shutdown command.\"sleep 1echo \"Querying instance status...\"aws ec2 describe-instance-status --include-all-instances --instance-ids $INSTANCE_ID --output text --query 'InstanceStatuses[]'sleep 5" }, { "code": null, "e": 4515, "s": 4453, "text": "*Note: I will periodically make improvements to this script.*" }, { "code": null, "e": 4625, "s": 4515, "text": "Fill in INSTANCE_ID with the instance-id of your EC2 instance. Fill in SSH_KEY with the path to your SSH key." }, { "code": null, "e": 4930, "s": 4625, "text": "Now when you want to start working in your EC2 server, just run the bash script and you will be connected to your server. From there, you can run a jupyter notebook or load in python scripts from GitHub. When you exit out of the instance, the script will continue running and turn-off the server for you." }, { "code": null, "e": 5007, "s": 4930, "text": "aws ec2 start-instances — instance-ids $INSTANCE_ID starts the EC2 instance." }, { "code": null, "e": 5167, "s": 5007, "text": "You need the server’s public DNS to log-in. Unfortunately, the DNS can change when you turn the server off. The below code queries for the server’s public DNS." }, { "code": null, "e": 5308, "s": 5167, "text": "SERVER_PUBLIC_DNS=$(aws ec2 describe-instances — instance-ids $INSTANCE_ID — output text — query ‘Reservations[].Instances[].PublicDnsName’)" }, { "code": null, "e": 5415, "s": 5308, "text": "Log in to the EC2 instance with ssh -L localhost:8888:localhost:8888 -i $SSH_KEY ubuntu@$SERVER_PUBLIC_DNS" } ]
ASP.NET - Security
Implementing security in a site has the following aspects: Authentication : It is the process of ensuring the user's identity and authenticity. ASP.NET allows four types of authentications: Windows Authentication Forms Authentication Passport Authentication Custom Authentication Authentication : It is the process of ensuring the user's identity and authenticity. ASP.NET allows four types of authentications: Windows Authentication Forms Authentication Passport Authentication Custom Authentication Authorization : It is the process of defining and allotting specific roles to specific users. Authorization : It is the process of defining and allotting specific roles to specific users. Confidentiality : It involves encrypting the channel between the client browser and the web server. Confidentiality : It involves encrypting the channel between the client browser and the web server. Integrity : It involves maintaining the integrity of data. For example, implementing digital signature. Integrity : It involves maintaining the integrity of data. For example, implementing digital signature. Traditionally, forms-based authentication involves editing the web.config file and adding a login page with appropriate authentication code. The web.config file could be edited and the following codes written on it: <configuration> <system.web> <authentication mode="Forms"> <forms loginUrl ="login.aspx"/> </authentication> <authorization> <deny users="?"/> </authorization> </system.web> ... ... </configuration> The login.aspx page mentioned in the above code snippet could have the following code behind file with the usernames and passwords for authentication hard coded into it. protected bool authenticate(String uname, String pass) { if(uname == "Tom") { if(pass == "tom123") return true; } if(uname == "Dick") { if(pass == "dick123") return true; } if(uname == "Harry") { if(pass == "har123") return true; } return false; } public void OnLogin(Object src, EventArgs e) { if (authenticate(txtuser.Text, txtpwd.Text)) { FormsAuthentication.RedirectFromLoginPage(txtuser.Text, chkrem.Checked); } else { Response.Write("Invalid user name or password"); } } Observe that the FormsAuthentication class is responsible for the process of authentication. However, Visual Studio allows you to implement user creation, authentication, and authorization with seamless ease without writing any code, through the Web Site Administration tool. This tool allows creating users and roles. Apart from this, ASP.NET comes with readymade login controls set, which has controls performing all the jobs for you. To set up forms-based authentication, you need the following: A database of users to support the authentication process A website that uses the database User accounts Roles Restriction of users and group activities A default page, to display the login status of the users and other information. A login page, to allow users to log in, retrieve password, or change password To create users, take the following steps: Step (1) : Choose Website -> ASP.NET Configuration to open the Web Application Administration Tool. Step (2) : Click on the Security tab. Step (3) : Select the authentication type to 'Forms based authentication' by selecting the 'From the Internet' radio button. Step (4) : Click on 'Create Users' link to create some users. If you already had created roles, you could assign roles to the user, right at this stage. Step (5) : Create a web site and add the following pages: Welcome.aspx Login.aspx CreateAccount.aspx PasswordRecovery.aspx ChangePassword.aspx Step (6) : Place a LoginStatus control on the Welcome.aspx from the login section of the toolbox. It has two templates: LoggedIn and LoggedOut. In LoggedOut template, there is a login link and in the LoggedIn template, there is a logout link on the control. You can change the login and logout text properties of the control from the Properties window. Step (7) : Place a LoginView control from the toolbox below the LoginStatus control. Here, you can put texts and other controls (hyperlinks, buttons etc.), which are displayed based on whether the user is logged in or not. This control has two view templates: Anonymous template and LoggedIn template. Select each view and write some text for the users to be displayed for each template. The text should be placed on the area marked red. Step (8) : The users for the application are created by the developer. You might want to allow a visitor to create a user account. For this, add a link beneath the LoginView control, which should link to the CreateAccount.aspx page. Step (9) : Place a CreateUserWizard control on the create account page. Set the ContinueDestinationPageUrl property of this control to Welcome.aspx. Step (10) : Create the Login page. Place a Login control on the page. The LoginStatus control automatically links to the Login.aspx. To change this default, make the following changes in the web.config file. For example, if you want to name your log in page as signup.aspx, add the following lines to the <authentication> section of the web.config: <configuration> <system.web> <authentication mode="Forms"> <forms loginUrl ="signup.aspx" defaultUrl = “Welcome.aspx” /> </authentication> </system.web> </configuration> Step (11) : Users often forget passwords. The PasswordRecovery control helps the user gain access to the account. Select the Login control. Open its smart tag and click 'Convert to Template'. Customize the UI of the control to place a hyperlink control under the login button, which should link to the PassWordRecovery.aspx. Step (12) : Place a PasswordRecovery control on the password recovery page. This control needs an email server to send the passwords to the users. Step (13) : Create a link to the ChangePassword.aspx page in the LoggedIn template of the LoginView control in Welcome.aspx. Step (14) : Place a ChangePassword control on the change password page. This control also has two views. Now run the application and observe different security operations. To create roles, go back to the Web Application Administration Tools and click on the Security tab. Click on 'Create Roles' and create some roles for the application. Click on the 'Manage Users' link and assign roles to the users. The Secure Socket Layer or SSL is the protocol used to ensure a secure connection. With SSL enabled, the browser encrypts all data sent to the server and decrypts all data coming from the server. At the same time, the server encrypts and decrypts all data to and from browser. The URL for a secure connection starts with HTTPS instead of HTTP. A small lock is displayed by a browser using a secure connection. When a browser makes an initial attempt to communicate with a server over a secure connection using SSL, the server authenticates itself by sending its digital certificate. To use the SSL, you need to buy a digital secure certificate from a trusted Certification Authority (CA) and install it in the web server. Following are some of the trusted and reputed certification authorities: www.verisign.com www.geotrust.com www.thawte.com SSL is built into all major browsers and servers. To enable SSL, you need to install the digital certificate. The strength of various digital certificates varies depending upon the length of the key generated during encryption. More the length, more secure is the certificate, hence the connection. 51 Lectures 5.5 hours Anadi Sharma 44 Lectures 4.5 hours Kaushik Roy Chowdhury 42 Lectures 18 hours SHIVPRASAD KOIRALA 57 Lectures 3.5 hours University Code 40 Lectures 2.5 hours University Code 138 Lectures 9 hours Bhrugen Patel Print Add Notes Bookmark this page
[ { "code": null, "e": 2406, "s": 2347, "text": "Implementing security in a site has the following aspects:" }, { "code": null, "e": 2630, "s": 2406, "text": "Authentication : It is the process of ensuring the user's identity and authenticity. ASP.NET allows four types of authentications:\n\nWindows Authentication\nForms Authentication\nPassport Authentication\nCustom Authentication\n\n" }, { "code": null, "e": 2761, "s": 2630, "text": "Authentication : It is the process of ensuring the user's identity and authenticity. ASP.NET allows four types of authentications:" }, { "code": null, "e": 2784, "s": 2761, "text": "Windows Authentication" }, { "code": null, "e": 2805, "s": 2784, "text": "Forms Authentication" }, { "code": null, "e": 2829, "s": 2805, "text": "Passport Authentication" }, { "code": null, "e": 2851, "s": 2829, "text": "Custom Authentication" }, { "code": null, "e": 2945, "s": 2851, "text": "Authorization : It is the process of defining and allotting specific roles to specific users." }, { "code": null, "e": 3039, "s": 2945, "text": "Authorization : It is the process of defining and allotting specific roles to specific users." }, { "code": null, "e": 3139, "s": 3039, "text": "Confidentiality : It involves encrypting the channel between the client browser and the web server." }, { "code": null, "e": 3239, "s": 3139, "text": "Confidentiality : It involves encrypting the channel between the client browser and the web server." }, { "code": null, "e": 3343, "s": 3239, "text": "Integrity : It involves maintaining the integrity of data. For example, implementing digital signature." }, { "code": null, "e": 3447, "s": 3343, "text": "Integrity : It involves maintaining the integrity of data. For example, implementing digital signature." }, { "code": null, "e": 3588, "s": 3447, "text": "Traditionally, forms-based authentication involves editing the web.config file and adding a login page with appropriate authentication code." }, { "code": null, "e": 3663, "s": 3588, "text": "The web.config file could be edited and the following codes written on it:" }, { "code": null, "e": 3891, "s": 3663, "text": "<configuration>\n\n<system.web>\n <authentication mode=\"Forms\">\n <forms loginUrl =\"login.aspx\"/>\n </authentication>\n \n <authorization>\n <deny users=\"?\"/>\n </authorization>\n</system.web>\n...\n...\n</configuration>" }, { "code": null, "e": 4061, "s": 3891, "text": "The login.aspx page mentioned in the above code snippet could have the following code behind file with the usernames and passwords for authentication hard coded into it." }, { "code": null, "e": 4656, "s": 4061, "text": "protected bool authenticate(String uname, String pass)\n{\n if(uname == \"Tom\")\n {\n if(pass == \"tom123\")\n return true;\n }\n \n if(uname == \"Dick\")\n {\n if(pass == \"dick123\")\n return true;\n }\n \n if(uname == \"Harry\")\n {\n if(pass == \"har123\")\n return true;\n }\n \n return false;\n}\n\npublic void OnLogin(Object src, EventArgs e)\n{\n if (authenticate(txtuser.Text, txtpwd.Text))\n {\n FormsAuthentication.RedirectFromLoginPage(txtuser.Text, chkrem.Checked);\n }\n else\n {\n Response.Write(\"Invalid user name or password\");\n }\n}" }, { "code": null, "e": 4749, "s": 4656, "text": "Observe that the FormsAuthentication class is responsible for the process of authentication." }, { "code": null, "e": 4975, "s": 4749, "text": "However, Visual Studio allows you to implement user creation, authentication, and authorization with seamless ease without writing any code, through the Web Site Administration tool. This tool allows creating users and roles." }, { "code": null, "e": 5093, "s": 4975, "text": "Apart from this, ASP.NET comes with readymade login controls set, which has controls performing all the jobs for you." }, { "code": null, "e": 5155, "s": 5093, "text": "To set up forms-based authentication, you need the following:" }, { "code": null, "e": 5213, "s": 5155, "text": "A database of users to support the authentication process" }, { "code": null, "e": 5246, "s": 5213, "text": "A website that uses the database" }, { "code": null, "e": 5260, "s": 5246, "text": "User accounts" }, { "code": null, "e": 5266, "s": 5260, "text": "Roles" }, { "code": null, "e": 5308, "s": 5266, "text": "Restriction of users and group activities" }, { "code": null, "e": 5388, "s": 5308, "text": "A default page, to display the login status of the users and other information." }, { "code": null, "e": 5466, "s": 5388, "text": "A login page, to allow users to log in, retrieve password, or change password" }, { "code": null, "e": 5509, "s": 5466, "text": "To create users, take the following steps:" }, { "code": null, "e": 5609, "s": 5509, "text": "Step (1) : Choose Website -> ASP.NET Configuration to open the Web Application Administration Tool." }, { "code": null, "e": 5647, "s": 5609, "text": "Step (2) : Click on the Security tab." }, { "code": null, "e": 5773, "s": 5647, "text": "Step (3) : Select the authentication type to 'Forms based authentication' by selecting the 'From the Internet' radio button." }, { "code": null, "e": 5926, "s": 5773, "text": "Step (4) : Click on 'Create Users' link to create some users. If you already had created roles, you could assign roles to the user, right at this stage." }, { "code": null, "e": 5984, "s": 5926, "text": "Step (5) : Create a web site and add the following pages:" }, { "code": null, "e": 5997, "s": 5984, "text": "Welcome.aspx" }, { "code": null, "e": 6008, "s": 5997, "text": "Login.aspx" }, { "code": null, "e": 6027, "s": 6008, "text": "CreateAccount.aspx" }, { "code": null, "e": 6049, "s": 6027, "text": "PasswordRecovery.aspx" }, { "code": null, "e": 6069, "s": 6049, "text": "ChangePassword.aspx" }, { "code": null, "e": 6213, "s": 6069, "text": "Step (6) : Place a LoginStatus control on the Welcome.aspx from the login section of the toolbox. It has two templates: LoggedIn and LoggedOut." }, { "code": null, "e": 6422, "s": 6213, "text": "In LoggedOut template, there is a login link and in the LoggedIn template, there is a logout link on the control. You can change the login and logout text properties of the control from the Properties window." }, { "code": null, "e": 6646, "s": 6422, "text": "Step (7) : Place a LoginView control from the toolbox below the LoginStatus control. Here,\t you can put texts and other controls (hyperlinks, buttons etc.), which are displayed based on whether the user is logged in or not." }, { "code": null, "e": 6861, "s": 6646, "text": "This control has two view templates: Anonymous template and LoggedIn template. Select each view and write some text for the users to be displayed for each template. The text should be placed on the area marked red." }, { "code": null, "e": 7095, "s": 6861, "text": "Step (8) : The users for the application are created by the developer. You might want to allow a visitor to create a user account. For this, add a link beneath the LoginView control, which should link to the CreateAccount.aspx page. " }, { "code": null, "e": 7244, "s": 7095, "text": "Step (9) : Place a CreateUserWizard control on the create account page. Set the ContinueDestinationPageUrl property of this control to Welcome.aspx." }, { "code": null, "e": 7452, "s": 7244, "text": "Step (10) : Create the Login page. Place a Login control on the page. The LoginStatus control automatically links to the Login.aspx. To change this default, make the following changes in the web.config file." }, { "code": null, "e": 7593, "s": 7452, "text": "For example, if you want to name your log in page as signup.aspx, add the following lines to the <authentication> section of the web.config:" }, { "code": null, "e": 7796, "s": 7593, "text": "<configuration>\n <system.web>\n <authentication mode=\"Forms\">\n <forms loginUrl =\"signup.aspx\" defaultUrl = “Welcome.aspx” />\n </authentication>\n </system.web>\n</configuration>" }, { "code": null, "e": 7988, "s": 7796, "text": "Step (11) : Users often forget passwords. The PasswordRecovery control helps the user gain access to the account. Select the Login control. Open its smart tag and click 'Convert to Template'." }, { "code": null, "e": 8121, "s": 7988, "text": "Customize the UI of the control to place a hyperlink control under the login button, which should link to the PassWordRecovery.aspx." }, { "code": null, "e": 8268, "s": 8121, "text": "Step (12) : Place a PasswordRecovery control on the password recovery page. This control needs an email server to send the passwords to the users." }, { "code": null, "e": 8393, "s": 8268, "text": "Step (13) : Create a link to the ChangePassword.aspx page in the LoggedIn template of the LoginView control in Welcome.aspx." }, { "code": null, "e": 8498, "s": 8393, "text": "Step (14) : Place a ChangePassword control on the change password page. This control also has two views." }, { "code": null, "e": 8565, "s": 8498, "text": "Now run the application and observe different security operations." }, { "code": null, "e": 8732, "s": 8565, "text": "To create roles, go back to the Web Application Administration Tools and click on the Security tab. Click on 'Create Roles' and create some roles for the application." }, { "code": null, "e": 8796, "s": 8732, "text": "Click on the 'Manage Users' link and assign roles to the users." }, { "code": null, "e": 9073, "s": 8796, "text": "The Secure Socket Layer or SSL is the protocol used to ensure a secure connection. With SSL enabled, the browser encrypts all data sent to the server and decrypts all data coming from the server. At the same time, the server encrypts and decrypts all data to and from browser." }, { "code": null, "e": 9379, "s": 9073, "text": "The URL for a secure connection starts with HTTPS instead of HTTP. A small lock is displayed by a browser using a secure connection. When a browser makes an initial attempt to communicate with a server over a secure connection using SSL, the server authenticates itself by sending its digital certificate." }, { "code": null, "e": 9591, "s": 9379, "text": "To use the SSL, you need to buy a digital secure certificate from a trusted Certification Authority (CA) and install it in the web server. Following are some of the trusted and reputed certification authorities:" }, { "code": null, "e": 9608, "s": 9591, "text": "www.verisign.com" }, { "code": null, "e": 9625, "s": 9608, "text": "www.geotrust.com" }, { "code": null, "e": 9640, "s": 9625, "text": "www.thawte.com" }, { "code": null, "e": 9939, "s": 9640, "text": "SSL is built into all major browsers and servers. To enable SSL, you need to install the digital certificate. The strength of various digital certificates varies depending upon the length of the key generated during encryption. More the length, more secure is the certificate, hence the connection." }, { "code": null, "e": 9974, "s": 9939, "text": "\n 51 Lectures \n 5.5 hours \n" }, { "code": null, "e": 9988, "s": 9974, "text": " Anadi Sharma" }, { "code": null, "e": 10023, "s": 9988, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 10046, "s": 10023, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 10080, "s": 10046, "text": "\n 42 Lectures \n 18 hours \n" }, { "code": null, "e": 10100, "s": 10080, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 10135, "s": 10100, "text": "\n 57 Lectures \n 3.5 hours \n" }, { "code": null, "e": 10152, "s": 10135, "text": " University Code" }, { "code": null, "e": 10187, "s": 10152, "text": "\n 40 Lectures \n 2.5 hours \n" }, { "code": null, "e": 10204, "s": 10187, "text": " University Code" }, { "code": null, "e": 10238, "s": 10204, "text": "\n 138 Lectures \n 9 hours \n" }, { "code": null, "e": 10253, "s": 10238, "text": " Bhrugen Patel" }, { "code": null, "e": 10260, "s": 10253, "text": " Print" }, { "code": null, "e": 10271, "s": 10260, "text": " Add Notes" } ]
ASP.NET WP - Working with Files
In this chapter, we will cover how you can work with text files in your website. You can use text files as a simple way to store data for your website. Text files can be in different formats, such as *.txt, *.xml, or *.csv. Text files can be in different formats, such as *.txt, *.xml, or *.csv. You can use the File.WriteAllText method to specify the file to create and then write data to it. You can use the File.WriteAllText method to specify the file to create and then write data to it. You can read/write and move data from/to the text file. You can read/write and move data from/to the text file. Let’s have a look into a simple example in which we will write a student information into a text file. First we need to create a new CSHTML file Enter TextData.cshtml in the name field and click OK to continue. In this example, we will create a simple form in which the user can enter Student information like first name, last name and marks. We also need to create a text file in the App_Data folder with Data.txt name Let’s replace the following code in the TextData.cshtml file. @{ var result = ""; if (IsPost){ var firstName = Request["FirstName"]; var lastName = Request["LastName"]; var marks = Request["Marks"]; var userData = firstName + "," + lastName + "," + marks + Environment.NewLine; var dataFile = Server.MapPath("~/App_Data/Data.txt"); File.WriteAllText(@dataFile, userData); result = "Information saved."; } } <!DOCTYPE html> <html> <head> <title>Write Data to a File</title> </head> <body> <form id = "form1" method = "post"> <div> <table> <tr> <td>First Name:</td> <td><input id = "FirstName" name = "FirstName" type = "text" /></td> </tr> <tr> <td>Last Name:</td> <td><input id = "LastName" name = "LastName" type = "text" /></td> </tr> <tr> <td>Marks:</td> <td><input id = "Marks" name = "Marks" type = "text" /></td> </tr> <tr> <td></td> <td><input type="submit" value="Submit"/></td> </tr> </table> </div> <div> @if(result != ""){ <p>Result: @result</p> } </div> </form> </body> </html> In the code, we have used the IsPost property to determine whether the page has been submitted before it starts processing. The WriteAllText method of the File object takes two parameters, the file name path and the actual data to write to the file. Now let’s run this application and specify the following url − http://localhost:36905/TextData and you will see the following web page. Let’s enter some data in all the fields. Now click on the submit button. As you can see the information is saved, now let’s open the Data.txt file and you will see that data is written to the file. For writing data to the text file we have used WriteAllText. If you call this method again and pass it with the same file name, then it will overwrite the existing file completely. But in most cases, we often want to add new data to the end of the file, so we can do that by using the AppendAllText method of the file object. Let’s have a look into the same example, we will just change the WriteAllText() to AppendAllText () as shown in the following program. @{ var result = ""; if (IsPost){ var firstName = Request["FirstName"]; var lastName = Request["LastName"]; var marks = Request["Marks"]; var userData = firstName + "," + lastName + "," + marks + Environment.NewLine; var dataFile = Server.MapPath("~/App_Data/Data.txt"); File.AppendAllText(@dataFile, userData); result = "Information saved."; } } <!DOCTYPE html> <html> <head> <title>Write Data to a File</title> </head> <body> <form id = "form1" method = "post"> <div> <table> <tr> <td>First Name:</td> <td><input id = "FirstName" name = "FirstName" type = "text" /></td> </tr> <tr> <td>Last Name:</td> <td><input id = "LastName" name = "LastName" type = "text" /></td> </tr> <tr> <td>Marks:</td> <td><input id = "Marks" name = "Marks" type = "text" /></td> </tr> <tr> <td></td> <td><input type = "submit" value = "Submit"/></td> </tr> </table> </div> <div> @if(result != ""){ <p>Result: @result</p> } </div> </form> </body> </html> Now let’s run the application and specify the following url http://localhost:36905/TextData and you will see the following web page. Enter some data and click the submit button. Now when you open the Data.txt file then you will see that the data is appended at the end of this file. To read the data from a file, you can use the File object and then call ReadAllLines(), which will read all the lines from the file. To do so, let’s create a new CSHTML file. Enter ReadData.cshtml in the Name field and click OK. Now replace the following code in the ReadData.cshtml file. @{ var result = ""; Array userData = null; char[] delimiterChar = {','}; var dataFile = Server.MapPath("~/App_Data/Data.txt"); if (File.Exists(dataFile)) { userData = File.ReadAllLines(dataFile); if (userData == null) { // Empty file. result = "The file is empty."; } } else { // File does not exist. result = "The file does not exist."; } } <!DOCTYPE html> <html> <head> <title>Reading Data from a File</title> </head> <body> <div> <h1>Reading Data from a File</h1> @result @if (result == "") { <ol> @foreach (string dataLine in userData) { <li> Student <ul> @foreach (string dataItem in dataLine.Split(delimiterChar)) { <li>@dataItem</li > } </ul> </li> } </ol> } </div> </body> </html> Now let’s run the application again and specify the following url http://localhost:36905/ReadData and you will see the following web page. 51 Lectures 5.5 hours Anadi Sharma 44 Lectures 4.5 hours Kaushik Roy Chowdhury 42 Lectures 18 hours SHIVPRASAD KOIRALA 57 Lectures 3.5 hours University Code 40 Lectures 2.5 hours University Code 138 Lectures 9 hours Bhrugen Patel Print Add Notes Bookmark this page
[ { "code": null, "e": 2437, "s": 2285, "text": "In this chapter, we will cover how you can work with text files in your website. You can use text files as a simple way to store data for your website." }, { "code": null, "e": 2509, "s": 2437, "text": "Text files can be in different formats, such as *.txt, *.xml, or *.csv." }, { "code": null, "e": 2581, "s": 2509, "text": "Text files can be in different formats, such as *.txt, *.xml, or *.csv." }, { "code": null, "e": 2679, "s": 2581, "text": "You can use the File.WriteAllText method to specify the file to create and then write data to it." }, { "code": null, "e": 2777, "s": 2679, "text": "You can use the File.WriteAllText method to specify the file to create and then write data to it." }, { "code": null, "e": 2833, "s": 2777, "text": "You can read/write and move data from/to the text file." }, { "code": null, "e": 2889, "s": 2833, "text": "You can read/write and move data from/to the text file." }, { "code": null, "e": 3034, "s": 2889, "text": "Let’s have a look into a simple example in which we will write a student information into a text file. First we need to create a new CSHTML file" }, { "code": null, "e": 3232, "s": 3034, "text": "Enter TextData.cshtml in the name field and click OK to continue. In this example, we will create a simple form in which the user can enter Student information like first name, last name and marks." }, { "code": null, "e": 3309, "s": 3232, "text": "We also need to create a text file in the App_Data folder with Data.txt name" }, { "code": null, "e": 3371, "s": 3309, "text": "Let’s replace the following code in the TextData.cshtml file." }, { "code": null, "e": 4847, "s": 3371, "text": "@{\n var result = \"\";\n \n if (IsPost){\n var firstName = Request[\"FirstName\"];\n var lastName = Request[\"LastName\"];\n var marks = Request[\"Marks\"];\n var userData = firstName + \",\" + lastName + \",\" + marks + Environment.NewLine;\n var dataFile = Server.MapPath(\"~/App_Data/Data.txt\");\n File.WriteAllText(@dataFile, userData);\n result = \"Information saved.\";\n }\n}\n\n<!DOCTYPE html>\n<html>\n \n <head>\n <title>Write Data to a File</title>\n </head>\n \n <body>\n <form id = \"form1\" method = \"post\">\n \n <div>\n <table>\n <tr>\n <td>First Name:</td>\n <td><input id = \"FirstName\" name = \"FirstName\" type = \"text\" /></td>\n </tr>\n \n <tr>\n <td>Last Name:</td>\n <td><input id = \"LastName\" name = \"LastName\" type = \"text\" /></td>\n </tr>\n \n <tr>\n <td>Marks:</td>\n <td><input id = \"Marks\" name = \"Marks\" type = \"text\" /></td>\n </tr>\n \n <tr>\n <td></td>\n <td><input type=\"submit\" value=\"Submit\"/></td>\n </tr>\n </table>\n \n </div>\n \n <div>\n @if(result != \"\"){\n <p>Result: @result</p>\n }\n </div>\n \n </form>\n \n </body>\n</html>" }, { "code": null, "e": 5097, "s": 4847, "text": "In the code, we have used the IsPost property to determine whether the page has been submitted before it starts processing. The WriteAllText method of the File object takes two parameters, the file name path and the actual data to write to the file." }, { "code": null, "e": 5233, "s": 5097, "text": "Now let’s run this application and specify the following url − http://localhost:36905/TextData and you will see the following web page." }, { "code": null, "e": 5274, "s": 5233, "text": "Let’s enter some data in all the fields." }, { "code": null, "e": 5306, "s": 5274, "text": "Now click on the submit button." }, { "code": null, "e": 5431, "s": 5306, "text": "As you can see the information is saved, now let’s open the Data.txt file and you will see that data is written to the file." }, { "code": null, "e": 5757, "s": 5431, "text": "For writing data to the text file we have used WriteAllText. If you call this method again and pass it with the same file name, then it will overwrite the existing file completely. But in most cases, we often want to add new data to the end of the file, so we can do that by using the AppendAllText method of the file object." }, { "code": null, "e": 5892, "s": 5757, "text": "Let’s have a look into the same example, we will just change the WriteAllText() to AppendAllText () as shown in the following program." }, { "code": null, "e": 7367, "s": 5892, "text": "@{\n var result = \"\";\n \n if (IsPost){\n var firstName = Request[\"FirstName\"];\n var lastName = Request[\"LastName\"];\n var marks = Request[\"Marks\"];\n var userData = firstName + \",\" + lastName + \",\" + marks + Environment.NewLine;\n var dataFile = Server.MapPath(\"~/App_Data/Data.txt\");\n File.AppendAllText(@dataFile, userData);\n result = \"Information saved.\";\n }\n}\n\n<!DOCTYPE html>\n<html>\n \n <head>\n <title>Write Data to a File</title>\n </head>\n \n <body>\n <form id = \"form1\" method = \"post\">\n <div>\n \n <table>\n <tr>\n <td>First Name:</td>\n <td><input id = \"FirstName\" name = \"FirstName\" type = \"text\" /></td>\n </tr>\n \n <tr>\n <td>Last Name:</td>\n <td><input id = \"LastName\" name = \"LastName\" type = \"text\" /></td>\n </tr>\n \n <tr>\n <td>Marks:</td>\n <td><input id = \"Marks\" name = \"Marks\" type = \"text\" /></td>\n </tr>\n \n <tr>\n <td></td>\n <td><input type = \"submit\" value = \"Submit\"/></td>\n </tr>\n </table>\n </div>\n \n <div>\n @if(result != \"\"){\n <p>Result: @result</p>\n }\n </div>\n \n </form>\n \n </body>\n</html>" }, { "code": null, "e": 7500, "s": 7367, "text": "Now let’s run the application and specify the following url http://localhost:36905/TextData and you will see the following web page." }, { "code": null, "e": 7545, "s": 7500, "text": "Enter some data and click the submit button." }, { "code": null, "e": 7650, "s": 7545, "text": "Now when you open the Data.txt file then you will see that the data is appended at the end of this file." }, { "code": null, "e": 7825, "s": 7650, "text": "To read the data from a file, you can use the File object and then call ReadAllLines(), which will read all the lines from the file. To do so, let’s create a new CSHTML file." }, { "code": null, "e": 7879, "s": 7825, "text": "Enter ReadData.cshtml in the Name field and click OK." }, { "code": null, "e": 7939, "s": 7879, "text": "Now replace the following code in the ReadData.cshtml file." }, { "code": null, "e": 9018, "s": 7939, "text": "@{\n var result = \"\";\n Array userData = null;\n char[] delimiterChar = {','};\n var dataFile = Server.MapPath(\"~/App_Data/Data.txt\");\n \n if (File.Exists(dataFile)) {\n userData = File.ReadAllLines(dataFile);\n if (userData == null) {\n // Empty file.\n result = \"The file is empty.\";\n }\n } else {\n // File does not exist.\n result = \"The file does not exist.\";\n }\n}\n\n<!DOCTYPE html>\n<html>\n \n <head>\n <title>Reading Data from a File</title>\n </head>\n \n <body>\n <div>\n <h1>Reading Data from a File</h1>\n @result\n \n @if (result == \"\") {\n <ol>\n @foreach (string dataLine in userData) {\n <li>\n Student\n <ul>\n @foreach (string dataItem in dataLine.Split(delimiterChar)) {\n <li>@dataItem</li >\n }\n </ul>\n </li>\n }\n </ol>\n }\n </div>\n \n </body>\n</html>" }, { "code": null, "e": 9157, "s": 9018, "text": "Now let’s run the application again and specify the following url http://localhost:36905/ReadData and you will see the following web page." }, { "code": null, "e": 9192, "s": 9157, "text": "\n 51 Lectures \n 5.5 hours \n" }, { "code": null, "e": 9206, "s": 9192, "text": " Anadi Sharma" }, { "code": null, "e": 9241, "s": 9206, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 9264, "s": 9241, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 9298, "s": 9264, "text": "\n 42 Lectures \n 18 hours \n" }, { "code": null, "e": 9318, "s": 9298, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 9353, "s": 9318, "text": "\n 57 Lectures \n 3.5 hours \n" }, { "code": null, "e": 9370, "s": 9353, "text": " University Code" }, { "code": null, "e": 9405, "s": 9370, "text": "\n 40 Lectures \n 2.5 hours \n" }, { "code": null, "e": 9422, "s": 9405, "text": " University Code" }, { "code": null, "e": 9456, "s": 9422, "text": "\n 138 Lectures \n 9 hours \n" }, { "code": null, "e": 9471, "s": 9456, "text": " Bhrugen Patel" }, { "code": null, "e": 9478, "s": 9471, "text": " Print" }, { "code": null, "e": 9489, "s": 9478, "text": " Add Notes" } ]
Autonomous Driving Dataset Visualization with Python and VizViewer | by Jose Rojas | Towards Data Science
As part of a recently published paper and Kaggle competition, Lyft has made public a dataset for building autonomous driving path prediction algorithms. The dataset includes a semantic map, ego vehicle data, and dynamic observational data for moving objects in the vehicle's vicinity. The challenge presented by Lyft with this dataset is to use this data to build a model that can predict the paths of moving objects and the path an autonomous vehicle (“AV”) should take based on the observations made by the AV sensors and perception stack. In more specific terms, the challenge is, given a set of information about the current vehicle state and its surroundings, to predict the best plan — a set of actions and behaviors — for the vehicle to safely navigate autonomously. Lyft provides a large volume of training data in the L5 Prediction dataset; tens of thousands of 25-second sequences of data are available in over 100GB. Along with the data, Lyft has also offered a set of tools for parsing and visualizing the data. This article will explore the details of the L5 Prediction dataset with these tools and a novel data visualization platform called VizViewer (or “VV” for short). Utilizing the VizViewer platform, we’ll uncover insights about the data while discussing the benefits of the visualization techniques for dataset tuning and feature engineering. To wrap up, we’ll preview a lane prediction visualization that could be used to solve the general path planning problem. Within the context of autonomous driving, there are two general subsets of data to consider: the static environment and the dynamic environment. The former would include data that mostly remain relatively fixed over time, such as the road network paths, the number of lanes in the current road, traffic signs and traffic lights, etc. The latter includes data about the varying driving conditions such as the location and speeds of pedestrians or vehicles nearby, or the color of an upcoming traffic light. The L5 Dataset provides data for both of these data types. One form is a semantic map, sometimes referred to as an HD map [1], which encodes details about the static driving environment. The second is a voluminous “scene” database for dynamic time-series data. The L5 Kit provided by Lyft includes tools for extracting data from both these sources. Within the dataset, the static environment is defined by the semantic map. This can be thought of as an environmental 2D map that has been densely annotated with information appropriate for the driving context. The semantic map offers a predefinition of the expected driving environment; without a semantic map, this static information would need to be continuously perceived and interpreted by the vehicle's sensors and CPUs. Thus, a semantic map is a powerful tool for pre-computing and offloading much of the work involved in AV planning and prediction problems. The semantic map itself contains these various attributes: a directed graph of roads and their lanes the physical position of the lane lines of a road, down to the centimeter the physical position of the stop lines, stop signs, traffic lights, crosswalks, and other traffic control elements speed limits the possible states for a given traffic light (e.g., red, green, yellow) and the lanes for which they control traffic (e.g., left turns, through lanes, right turns) parking zones (specifically if they share a lane) The dynamic features encoded in the dataset include the spatial information of the “ego” vehicle (the AV collecting the data), the “agents” (freely moving observed objects), and the traffic light states (“red”, “green”, “yellow”). Each agent also has a “class” label, describing it as a set of probabilities of common object types such as cars, pedestrians, cyclists, etc. These three data sources are encoded and indexed separately into tabular form. The spatial features of the ego and agents contain the “pose” of the objects (their x, y, z cartesian coordinates, and orientation) and for agents, their “extent” (size of the object). Each data sample has a timestamp, and all observations with a common timestamp represent a “frame” of data. A “scene” consists of a contiguous sequence of observation frames with respect to time. The scene links frames from each of the other three data tables using a list of indexes to each record in the table. The motivation behind this scene-centric structure is important to note. In many machine learning problems, each time-based data sample is used independently as examples to train a model. However, in this dataset, the entire scene — as a collection of data samples — are the atomic units of data used to train a machine-learned model. The reasons for this should be fairly intuitive; to make predictions about the paths a set of objects can take, the samples must be coherent and causally linked across time to build an accurate description of motion. If an amalgam of data samples from different scenes is used to generate a path, the resulting path would most likely be completely inconsistent; the objects would move in impossible ways from the ground truth. Given the need for coherency across time for accuracy in path planning, scenes are the building blocks of data that we will examine holistically using VizViewer. VizViewer is a web application and platform for collaboration and visualization of complex, multi-modal datasets. It consists of a suite of communication, data processing, and visualization components bundled into an accessible and easy to use dashboard UI. VV provides tools for interpreting data and accelerating productivity in data analysis workflows. It achieves these goals through a cohesive, configurable, interactive, and versatile toolset for analyzing datasets of different modalities while interoperating with Python and the Jupyter Notebooks. In short, VizViewer is a helpful extension of coding tools for data exploration and insights into dense datasets with different types of content. In the next sections, we’ll explore the characteristics of the L5 Prediction dataset using VizViewer to understand the data better, build improved training sets, and utilize it to debug and evaluate models. The L5 Prediction Dataset Kit comes with a simple tool for visualizing the semantic map and scene data together. The tool can take a specific set of coordinates and dimensions to generate an image of the roads, lane lines, and other labeled elements. It can also render the traffic lanes' dynamic state by marking specific lanes a certain color if the lane’s traffic is affected by the traffic light, i.e., when a traffic light is red, the lanes it controls are also marked red. These images can be merged to make a short movie clip of the scene, shown below. As an alternative, VizViewer has an interactive 3D rendering toolkit that can render the semantic map with free form exploration along with a scene-specific view. The map can be zoomed similarly to other online mapping tools and has support for satellite and vector map layers. With VV, the map can be navigated and examined for details that might be interesting for training our models. For example, if we are looking for samples related to left turns onto a multilane street, we can examine the map for street intersections that fit this case and then filter our samples by the coordinates of this region of interest. To assist with the exploration, the map elements can also be selected by clicking them to expose more details about the element. VV integrates with Python, allowing data to be aggregated and processed using Python code, then sending data to VV for rendering via a Python API. For example, VV has data querying features that allow objects to be highlighted in the 3D view based on features of interest. A feature query can be defined in Python; then, with an API call, the VV dashboard will update, find, and select the features that satisfy these conditions. The image below shows the semantic map search results by highlighting roads with a decreasing minimum number of lanes criteria. This could help identify areas where samples might be gathered for specific driving scenarios (e.g., highways, residential streets, driveways, parking lots). # example query command for marking roads with 3 to 5 lanesvv.semantic_query({ "where": "msg.kind == 'road' && msg.num_lanes >= 3 && msg.num_lanes <= 5" }) To summarize, VizViewer’s 3D interactive mapping tool features allow a data modeler to examine the contextual information within the semantic map easily. Furthermore, visual searches for specific attributes within the semantic map can assist with training set selection and modeling workflows. As mentioned, the scene database contains spatial and orientation coordinates for objects in a scene organized into a time-series of frames. The coordinates describe absolute values relative to the origin of the semantic map. We’ll explore how we can convert this raw data into additional information that is more beneficial for data interpretation and creating a machine learning model. Below is a VV chart showing various spatial features of a vehicle driving down a left curve within a particular scene. The top chart uses the raw data from the dataset, plotting X and Y positions on the primary vertical axis, and yaw (orientation) on another. The bottom chart offers more noticeable detail in the changes of the X and Y values by plotting the delta from the first frame in the scene’s data series. The yaw values change equally in both charts, showing that the vehicle was turning through a curve during the initial 10 seconds. In the context of machine learning, feature augmentation and data engineering are the processes of molding the data into a form that improves model convergence and accuracy. For example, models could converge faster if their feature values are rescaled into a smaller range. This example above illustrates that raw data could be transformed to accentuate more underlying details in the data within a smaller range of values. In the case above, changing the plot from absolute values to deltas of the values made the change in the time series more obvious with a plot of the same size. Additionally, adjusting the data so it is contextual to a scene provides for easier interpretation. For our case above, using relative values from the initial frame of a scene will yield standardized plots for easier comparison when examining different scenes. A few helpful features can be derived from spatial data about the motion of the objects. These can be used to build a motion model for a given object type. For example, because cars have wheels, they should move mostly forward and backward, but not freely from side to side (non-holonomic motion). Therefore, a motion model that independently tracks orientation, longitudinal, and lateral motion would be desirable. With a motion model, an object type’s appropriate dynamics can be trained, simulated, and tested for validity. Below are some of the augmentation values that can be calculated to assist with describing a motion model. longitudinal (forward/backward) velocity, acceleration, and jerk (the 1st derivative of acceleration) lateral (side-to-side) velocity, acceleration, and jerk yaw rate (change in orientation), yaw acceleration, yaw jerk Another set of derived features can model the relationships between two objects. These features will help train the model to understand how to generate a planned path given the dynamics between objects (e.g., slow down if you are approaching an object) and the environment (e.g., slow down when approaching a turn or stop sign). distances and relative speed between objects (ego and agents) distances between objects and semantic maps features (traffic lights, stop lines, crosswalks) the orientation of the current or desired lane lines position within the current or desired lane Above is a plot from VV that shows some of these augmented features, such as velocity and acceleration. What is noteworthy is the use of filtering and smoothing in calculating these derived values. The dotted lines represent the unfiltered values, while the solid lines represent the smoothed values derived from spline-based interpolation methods. The smoothing is applied via Python code to assist with the convergence of a trained model using these features. The code below shows an example of how the augmented values were smoothed. Having described the data features in detail, exploring and visualizing these features is a helpful part of building training and validation sets for an ML model. We’ll dive into some explorations and insights about the data, describing how VizViewer assists with these tasks. For exploration, we’ll set up a dashboard that will allow for easy viewing of the data with different modalities. VizViewer offers a configurable dashboard to build a data-viz layout best suited for a data exploration task. While this paradigm is different from inline visualization in Jupyter Notebooks, this alternative UI offers additional comprehensiveness, customization, and interaction beyond the confines of the Notebook’s code cells. This is desirable when a task requires comparing and synthesizing multiple streams of feature data into one cohesive representation, which we’ll examine further. Furthermore, the dashboard can be configured to arrange panels of visual components in an optimal manner of a user’s choosing. For example, to view spatial dataset patterns, the 3D mapping components and charting components are chosen to provide a holistic view. The charts can be configured to present data in various forms; time-series charts and histograms are used for this particular task. An example of a composite view of the map and histogram is shown below. Examining the visualization above, the map shows the paths (magenta) taken by the ego vehicle across all the sample dataset scenes. Below, the larger histogram view shows the distribution of the feature data across all scenes. We can see the data is concentrated down one particular predetermined path. The data follows a normal distribution for most features, but not in all cases; speed follows a bimodal distribution pattern, with most of the data samples either being near zero or a near 13 m/s (30 mph), a common speed limit for most city streets. The graph below shows normalized histograms for multiple features across 100 bins and an un-normalized histogram plotting the probability distribution of speed values. Having a holistic view of the data is useful, yet it is equally useful to drill into specific scenes to explore whether there is coherence in our derived calculations across the dataset. With VV’s configurable selection features, a specific scene can be selected on the map by clicking the path, revealing more details about the scene’s time-series data. In the example below, the graphs of the ego vehicle’s motion of the right are updated when a section of the scene’s path is selected on the map to the left. Using this feature, a data engineer can quickly validate the consistency of these motion values across varying sections of the semantic map. For example, velocity/acceleration should slow down on sharp turns, so the map would assist with isolating those potential scenes for validation. We can see details about the vehicle's longitudinal and lateral velocity for a selected scene within the image above. For scenes with data samples along straight paths, the lateral velocity and yaw rate will remain close to zero. However, if a path along a turn or a curve is selected, the expected visualized result is an increase in lateral velocity and yaw rate. The image confirms both of these outcomes across different sections of the map. To examine how speed is influenced by location, aggregated data statistics can be analyzed using a heatmap feature. The heatmap collects data into a grid, then assigns a color set to the data distribution. The heatmap shows where the data samples are located by coloring the region, while the color itself represents the feature’s magnitude. For example, below is a heatmap of ego vehicle speed. We can see a pattern with high-velocity samples (brighter shades) collected down specific roads on the map. In comparison, lower-velocity (darker shades) samples are collected on smaller side streets. This can indicate regions of the map with fast-moving traffic vs. slower, more regulated traffic. An important topic to discuss is the consistency of the agent observations. Within each scene, a set of agents can be observed; however, many agent observations could be short-lived or sporadic, only being labeled and tracked across a short time span and not the entire scene length. The following heatmap illustrates this point, showing a decreasing number of samples as the minimum number of sequential frames is raised from 0 to 9 seconds in 3-second intervals. Given 25 seconds as the scene length, scenes with longer sequences of agent tracking will be relatively sparse; therefore, any robust prediction model will have to make inferences across non-sequential data frames. Regardless of the sparseness, scenes with higher agent frame continuity will be more valuable agent data examples for training. The longer the number of observed frames, the more accurate the predictions will be for paths at longer time horizons. To avoid bias based on location, it would be important to gather these less common examples from as many sections of the map as possible, so using the heatmap would be helpful for this task. Another interesting insight we can observe visually is the inverse correlation of speed with the number of observations. The image below shows two heatmaps overlaid, ego vehicle speed (blue) and agent observation density (red). Areas where the speed is low will likely result in an increase in the agent observation count. While this might not be obvious at first, the reason for this should be clear when we observe where on the map these correlations best occur; these occur at intersections, where speed is likely to decrease due to traffic lights or stop signs, and thus yields a higher likelihood for additional agent observations from traffic across both streets. To summarize, we discovered some useful insights about the data, which is an essential step in the model building process. To review the data holistically, we can employ tools like heatmaps and histograms at different scales to identify spatial patterns that may be advantageous to capture in our models. Being able to easily access data at a high-level and low-level through interactive selection was also helpful. The insights learned through the exploration process will lead to a better determination of what correlations and biases may exist in the dataset. It will also provide better information about the availability, distribution, and quality of particular data samples. Equipped with this knowledge, we can better feature engineer training sets and avoid overfitting or underfitting a certain subset of model-driven behavior. Transitioning from data exploration to model development, we’ll switch focus from a global view of the data to a local scene. We will explore aspects of visualizing scene data and path data for debugging and evaluation. As shown above, the local scene view within VizViewer offers a 3D simulation of the vehicle and its semantic environment, along with labels for agents, lane states, traffic light states, annotated bounding boxes for agents (yellow and blue boxes), and the annotated planned path of travel (blue). Plots of the various features are synchronized with the model simulation in one unified layout. VV also offers a UI for controlling the simulation's state, such as a play and pause button, rate controls, and discrete timestamp adjustments. The scene camera is fully interactive, allowing for visualizing different perspectives of the scene. These features are beneficial while debugging the model’s behavior within a scene. As part of a path prediction model, one subproblem is determining the current lane of a given vehicle. If we can accurately detect the lane a vehicle is in, we can build a model to predict where a vehicle will travel confidently, given the pose and derived motion features. Additionally, the semantic map will be needed to determine the possible lane paths in the environment through which vehicles would likely travel. During the course of this exploration, I was able to train a neural network with various pose features and the semantic map data to determine an estimate of the current lane and possible next lane. Using VizViewer, the lane lines and lane candidates can be visualized and annotated with additional data from the SVM network (e.g., raw regression values, confidence scores). By loading a scene, running the visual simulation, and using the interactive 3D view, the resulting paths can be examined and tested. The blue lane segments highlight the possible prediction paths, with a darker color representing a higher degree of confidence in the path. Additionally, the paths can be clicked to expose the underlying data, such as the confidence score. In the example scene above, the vehicle approaches a 3-way stop sign. The prediction that the vehicle would continue to move forward was fairly high as it came to a stop. As the vehicle began to move forward, the prediction began to change to a left turn and the confidence values increased as it moved through the turn. With an improved model that includes more data, such as considering the pedestrian motion and the delay between stopping and turning, a left turn prediction could be made much sooner. As the model is further developed, visualization can help determine how well the planned paths are performing. Deviations from a lane can be reviewed, potential collisions with other objects can be detected and highlighted for display. This evaluation can be performed for both ego and agents, detecting when paths intersect. Smoothness is also important for accurate behavior modeling. Using the chart functionality to display attributes such as speed and acceleration will also help evaluate how smooth a predicted path is. For achieving these goals, VV offers a beneficial UI for model tuning and assessment. The Lyft Prediction Dataset proved to be a massive dataset with the potential for some interesting patterns for research and prediction algorithms. The inclusion of free form agent observational data for motion prediction is beneficial and valuable. Additionally, the SDK offers useful tools for extracting the data; yet the dataset's structure is easy to navigate with a subset of the SDK. There are a few critiques about the dataset package. One downside is this dataset only includes a pre-planned path for the ego vehicle on a limited set of street types. Hopefully, in the future, Lyft will expand the dataset to include samples collected across a heterogeneous set of streets. Another point is the quality of agent labels are poor at times; labels are incorrectly assigned or unusual motion in the agents is apparent, but that should be expected for a small percentage of data samples. Additionally, while useful as a starting point, the visualization tools provided in the L5 Kit are far less helpful for data exploration. The visualization tool is provided, ostensively, as a way to generate training data for a possible convolutional neural network (CNN) based inference model, not necessarily for data exploration [2]. Through the use of the L5 Kit, VizViewer and Jupyter Notebooks, we explored and visualized the dataset in both novel and useful ways. Specifically, VV offered the ability to create a custom dashboard that can receive data from Python code for contextual visualization. The interactive charts, maps, 3D visualizations, and simulations were synthesized and synchronized to facilitate data discovery, exploration, and model debugging processes. Additionally, VV's interactive visualization features offered ways to perform these tasks with more freedom and efficacy than traditional Notebook based UI tools like Matplotlib. So how would approach analyzing a large dataset as the one reviewed here? What other interesting data points would you like to explore? If you found this article interesting, please leave a comment and follow me for similar content. For information about VizViewer, please check out VizViewer.com, where you can sign-up to request access to the chat community and updates about the platform. [1] Lyft Level 5, Rethinking Maps for Self Driving, (2018), Lyft Level 5 Blog. [2] Houston, Zuidhof, Bergamini, et al., One Thousand and One Hours: Self-driving Motion Prediction Dataset (2020). Baseline motion prediction solution (page 6). Attribution: the images displayed in this article used data from the Lyft L5 Prediction Dataset. The article provides educational content about this dataset and a critical review.
[ { "code": null, "e": 714, "s": 172, "text": "As part of a recently published paper and Kaggle competition, Lyft has made public a dataset for building autonomous driving path prediction algorithms. The dataset includes a semantic map, ego vehicle data, and dynamic observational data for moving objects in the vehicle's vicinity. The challenge presented by Lyft with this dataset is to use this data to build a model that can predict the paths of moving objects and the path an autonomous vehicle (“AV”) should take based on the observations made by the AV sensors and perception stack." }, { "code": null, "e": 946, "s": 714, "text": "In more specific terms, the challenge is, given a set of information about the current vehicle state and its surroundings, to predict the best plan — a set of actions and behaviors — for the vehicle to safely navigate autonomously." }, { "code": null, "e": 1196, "s": 946, "text": "Lyft provides a large volume of training data in the L5 Prediction dataset; tens of thousands of 25-second sequences of data are available in over 100GB. Along with the data, Lyft has also offered a set of tools for parsing and visualizing the data." }, { "code": null, "e": 1657, "s": 1196, "text": "This article will explore the details of the L5 Prediction dataset with these tools and a novel data visualization platform called VizViewer (or “VV” for short). Utilizing the VizViewer platform, we’ll uncover insights about the data while discussing the benefits of the visualization techniques for dataset tuning and feature engineering. To wrap up, we’ll preview a lane prediction visualization that could be used to solve the general path planning problem." }, { "code": null, "e": 2163, "s": 1657, "text": "Within the context of autonomous driving, there are two general subsets of data to consider: the static environment and the dynamic environment. The former would include data that mostly remain relatively fixed over time, such as the road network paths, the number of lanes in the current road, traffic signs and traffic lights, etc. The latter includes data about the varying driving conditions such as the location and speeds of pedestrians or vehicles nearby, or the color of an upcoming traffic light." }, { "code": null, "e": 2512, "s": 2163, "text": "The L5 Dataset provides data for both of these data types. One form is a semantic map, sometimes referred to as an HD map [1], which encodes details about the static driving environment. The second is a voluminous “scene” database for dynamic time-series data. The L5 Kit provided by Lyft includes tools for extracting data from both these sources." }, { "code": null, "e": 3078, "s": 2512, "text": "Within the dataset, the static environment is defined by the semantic map. This can be thought of as an environmental 2D map that has been densely annotated with information appropriate for the driving context. The semantic map offers a predefinition of the expected driving environment; without a semantic map, this static information would need to be continuously perceived and interpreted by the vehicle's sensors and CPUs. Thus, a semantic map is a powerful tool for pre-computing and offloading much of the work involved in AV planning and prediction problems." }, { "code": null, "e": 3137, "s": 3078, "text": "The semantic map itself contains these various attributes:" }, { "code": null, "e": 3179, "s": 3137, "text": "a directed graph of roads and their lanes" }, { "code": null, "e": 3253, "s": 3179, "text": "the physical position of the lane lines of a road, down to the centimeter" }, { "code": null, "e": 3369, "s": 3253, "text": "the physical position of the stop lines, stop signs, traffic lights, crosswalks, and other traffic control elements" }, { "code": null, "e": 3382, "s": 3369, "text": "speed limits" }, { "code": null, "e": 3547, "s": 3382, "text": "the possible states for a given traffic light (e.g., red, green, yellow) and the lanes for which they control traffic (e.g., left turns, through lanes, right turns)" }, { "code": null, "e": 3597, "s": 3547, "text": "parking zones (specifically if they share a lane)" }, { "code": null, "e": 4049, "s": 3597, "text": "The dynamic features encoded in the dataset include the spatial information of the “ego” vehicle (the AV collecting the data), the “agents” (freely moving observed objects), and the traffic light states (“red”, “green”, “yellow”). Each agent also has a “class” label, describing it as a set of probabilities of common object types such as cars, pedestrians, cyclists, etc. These three data sources are encoded and indexed separately into tabular form." }, { "code": null, "e": 4547, "s": 4049, "text": "The spatial features of the ego and agents contain the “pose” of the objects (their x, y, z cartesian coordinates, and orientation) and for agents, their “extent” (size of the object). Each data sample has a timestamp, and all observations with a common timestamp represent a “frame” of data. A “scene” consists of a contiguous sequence of observation frames with respect to time. The scene links frames from each of the other three data tables using a list of indexes to each record in the table." }, { "code": null, "e": 4882, "s": 4547, "text": "The motivation behind this scene-centric structure is important to note. In many machine learning problems, each time-based data sample is used independently as examples to train a model. However, in this dataset, the entire scene — as a collection of data samples — are the atomic units of data used to train a machine-learned model." }, { "code": null, "e": 5471, "s": 4882, "text": "The reasons for this should be fairly intuitive; to make predictions about the paths a set of objects can take, the samples must be coherent and causally linked across time to build an accurate description of motion. If an amalgam of data samples from different scenes is used to generate a path, the resulting path would most likely be completely inconsistent; the objects would move in impossible ways from the ground truth. Given the need for coherency across time for accuracy in path planning, scenes are the building blocks of data that we will examine holistically using VizViewer." }, { "code": null, "e": 6027, "s": 5471, "text": "VizViewer is a web application and platform for collaboration and visualization of complex, multi-modal datasets. It consists of a suite of communication, data processing, and visualization components bundled into an accessible and easy to use dashboard UI. VV provides tools for interpreting data and accelerating productivity in data analysis workflows. It achieves these goals through a cohesive, configurable, interactive, and versatile toolset for analyzing datasets of different modalities while interoperating with Python and the Jupyter Notebooks." }, { "code": null, "e": 6380, "s": 6027, "text": "In short, VizViewer is a helpful extension of coding tools for data exploration and insights into dense datasets with different types of content. In the next sections, we’ll explore the characteristics of the L5 Prediction dataset using VizViewer to understand the data better, build improved training sets, and utilize it to debug and evaluate models." }, { "code": null, "e": 6940, "s": 6380, "text": "The L5 Prediction Dataset Kit comes with a simple tool for visualizing the semantic map and scene data together. The tool can take a specific set of coordinates and dimensions to generate an image of the roads, lane lines, and other labeled elements. It can also render the traffic lanes' dynamic state by marking specific lanes a certain color if the lane’s traffic is affected by the traffic light, i.e., when a traffic light is red, the lanes it controls are also marked red. These images can be merged to make a short movie clip of the scene, shown below." }, { "code": null, "e": 7218, "s": 6940, "text": "As an alternative, VizViewer has an interactive 3D rendering toolkit that can render the semantic map with free form exploration along with a scene-specific view. The map can be zoomed similarly to other online mapping tools and has support for satellite and vector map layers." }, { "code": null, "e": 7689, "s": 7218, "text": "With VV, the map can be navigated and examined for details that might be interesting for training our models. For example, if we are looking for samples related to left turns onto a multilane street, we can examine the map for street intersections that fit this case and then filter our samples by the coordinates of this region of interest. To assist with the exploration, the map elements can also be selected by clicking them to expose more details about the element." }, { "code": null, "e": 8405, "s": 7689, "text": "VV integrates with Python, allowing data to be aggregated and processed using Python code, then sending data to VV for rendering via a Python API. For example, VV has data querying features that allow objects to be highlighted in the 3D view based on features of interest. A feature query can be defined in Python; then, with an API call, the VV dashboard will update, find, and select the features that satisfy these conditions. The image below shows the semantic map search results by highlighting roads with a decreasing minimum number of lanes criteria. This could help identify areas where samples might be gathered for specific driving scenarios (e.g., highways, residential streets, driveways, parking lots)." }, { "code": null, "e": 8561, "s": 8405, "text": "# example query command for marking roads with 3 to 5 lanesvv.semantic_query({ \"where\": \"msg.kind == 'road' && msg.num_lanes >= 3 && msg.num_lanes <= 5\" })" }, { "code": null, "e": 8855, "s": 8561, "text": "To summarize, VizViewer’s 3D interactive mapping tool features allow a data modeler to examine the contextual information within the semantic map easily. Furthermore, visual searches for specific attributes within the semantic map can assist with training set selection and modeling workflows." }, { "code": null, "e": 9243, "s": 8855, "text": "As mentioned, the scene database contains spatial and orientation coordinates for objects in a scene organized into a time-series of frames. The coordinates describe absolute values relative to the origin of the semantic map. We’ll explore how we can convert this raw data into additional information that is more beneficial for data interpretation and creating a machine learning model." }, { "code": null, "e": 9788, "s": 9243, "text": "Below is a VV chart showing various spatial features of a vehicle driving down a left curve within a particular scene. The top chart uses the raw data from the dataset, plotting X and Y positions on the primary vertical axis, and yaw (orientation) on another. The bottom chart offers more noticeable detail in the changes of the X and Y values by plotting the delta from the first frame in the scene’s data series. The yaw values change equally in both charts, showing that the vehicle was turning through a curve during the initial 10 seconds." }, { "code": null, "e": 10634, "s": 9788, "text": "In the context of machine learning, feature augmentation and data engineering are the processes of molding the data into a form that improves model convergence and accuracy. For example, models could converge faster if their feature values are rescaled into a smaller range. This example above illustrates that raw data could be transformed to accentuate more underlying details in the data within a smaller range of values. In the case above, changing the plot from absolute values to deltas of the values made the change in the time series more obvious with a plot of the same size. Additionally, adjusting the data so it is contextual to a scene provides for easier interpretation. For our case above, using relative values from the initial frame of a scene will yield standardized plots for easier comparison when examining different scenes." }, { "code": null, "e": 11268, "s": 10634, "text": "A few helpful features can be derived from spatial data about the motion of the objects. These can be used to build a motion model for a given object type. For example, because cars have wheels, they should move mostly forward and backward, but not freely from side to side (non-holonomic motion). Therefore, a motion model that independently tracks orientation, longitudinal, and lateral motion would be desirable. With a motion model, an object type’s appropriate dynamics can be trained, simulated, and tested for validity. Below are some of the augmentation values that can be calculated to assist with describing a motion model." }, { "code": null, "e": 11370, "s": 11268, "text": "longitudinal (forward/backward) velocity, acceleration, and jerk (the 1st derivative of acceleration)" }, { "code": null, "e": 11426, "s": 11370, "text": "lateral (side-to-side) velocity, acceleration, and jerk" }, { "code": null, "e": 11487, "s": 11426, "text": "yaw rate (change in orientation), yaw acceleration, yaw jerk" }, { "code": null, "e": 11816, "s": 11487, "text": "Another set of derived features can model the relationships between two objects. These features will help train the model to understand how to generate a planned path given the dynamics between objects (e.g., slow down if you are approaching an object) and the environment (e.g., slow down when approaching a turn or stop sign)." }, { "code": null, "e": 11878, "s": 11816, "text": "distances and relative speed between objects (ego and agents)" }, { "code": null, "e": 11972, "s": 11878, "text": "distances between objects and semantic maps features (traffic lights, stop lines, crosswalks)" }, { "code": null, "e": 12025, "s": 11972, "text": "the orientation of the current or desired lane lines" }, { "code": null, "e": 12069, "s": 12025, "text": "position within the current or desired lane" }, { "code": null, "e": 12606, "s": 12069, "text": "Above is a plot from VV that shows some of these augmented features, such as velocity and acceleration. What is noteworthy is the use of filtering and smoothing in calculating these derived values. The dotted lines represent the unfiltered values, while the solid lines represent the smoothed values derived from spline-based interpolation methods. The smoothing is applied via Python code to assist with the convergence of a trained model using these features. The code below shows an example of how the augmented values were smoothed." }, { "code": null, "e": 12883, "s": 12606, "text": "Having described the data features in detail, exploring and visualizing these features is a helpful part of building training and validation sets for an ML model. We’ll dive into some explorations and insights about the data, describing how VizViewer assists with these tasks." }, { "code": null, "e": 13488, "s": 12883, "text": "For exploration, we’ll set up a dashboard that will allow for easy viewing of the data with different modalities. VizViewer offers a configurable dashboard to build a data-viz layout best suited for a data exploration task. While this paradigm is different from inline visualization in Jupyter Notebooks, this alternative UI offers additional comprehensiveness, customization, and interaction beyond the confines of the Notebook’s code cells. This is desirable when a task requires comparing and synthesizing multiple streams of feature data into one cohesive representation, which we’ll examine further." }, { "code": null, "e": 13955, "s": 13488, "text": "Furthermore, the dashboard can be configured to arrange panels of visual components in an optimal manner of a user’s choosing. For example, to view spatial dataset patterns, the 3D mapping components and charting components are chosen to provide a holistic view. The charts can be configured to present data in various forms; time-series charts and histograms are used for this particular task. An example of a composite view of the map and histogram is shown below." }, { "code": null, "e": 14676, "s": 13955, "text": "Examining the visualization above, the map shows the paths (magenta) taken by the ego vehicle across all the sample dataset scenes. Below, the larger histogram view shows the distribution of the feature data across all scenes. We can see the data is concentrated down one particular predetermined path. The data follows a normal distribution for most features, but not in all cases; speed follows a bimodal distribution pattern, with most of the data samples either being near zero or a near 13 m/s (30 mph), a common speed limit for most city streets. The graph below shows normalized histograms for multiple features across 100 bins and an un-normalized histogram plotting the probability distribution of speed values." }, { "code": null, "e": 15475, "s": 14676, "text": "Having a holistic view of the data is useful, yet it is equally useful to drill into specific scenes to explore whether there is coherence in our derived calculations across the dataset. With VV’s configurable selection features, a specific scene can be selected on the map by clicking the path, revealing more details about the scene’s time-series data. In the example below, the graphs of the ego vehicle’s motion of the right are updated when a section of the scene’s path is selected on the map to the left. Using this feature, a data engineer can quickly validate the consistency of these motion values across varying sections of the semantic map. For example, velocity/acceleration should slow down on sharp turns, so the map would assist with isolating those potential scenes for validation." }, { "code": null, "e": 15921, "s": 15475, "text": "We can see details about the vehicle's longitudinal and lateral velocity for a selected scene within the image above. For scenes with data samples along straight paths, the lateral velocity and yaw rate will remain close to zero. However, if a path along a turn or a curve is selected, the expected visualized result is an increase in lateral velocity and yaw rate. The image confirms both of these outcomes across different sections of the map." }, { "code": null, "e": 16616, "s": 15921, "text": "To examine how speed is influenced by location, aggregated data statistics can be analyzed using a heatmap feature. The heatmap collects data into a grid, then assigns a color set to the data distribution. The heatmap shows where the data samples are located by coloring the region, while the color itself represents the feature’s magnitude. For example, below is a heatmap of ego vehicle speed. We can see a pattern with high-velocity samples (brighter shades) collected down specific roads on the map. In comparison, lower-velocity (darker shades) samples are collected on smaller side streets. This can indicate regions of the map with fast-moving traffic vs. slower, more regulated traffic." }, { "code": null, "e": 17296, "s": 16616, "text": "An important topic to discuss is the consistency of the agent observations. Within each scene, a set of agents can be observed; however, many agent observations could be short-lived or sporadic, only being labeled and tracked across a short time span and not the entire scene length. The following heatmap illustrates this point, showing a decreasing number of samples as the minimum number of sequential frames is raised from 0 to 9 seconds in 3-second intervals. Given 25 seconds as the scene length, scenes with longer sequences of agent tracking will be relatively sparse; therefore, any robust prediction model will have to make inferences across non-sequential data frames." }, { "code": null, "e": 17734, "s": 17296, "text": "Regardless of the sparseness, scenes with higher agent frame continuity will be more valuable agent data examples for training. The longer the number of observed frames, the more accurate the predictions will be for paths at longer time horizons. To avoid bias based on location, it would be important to gather these less common examples from as many sections of the map as possible, so using the heatmap would be helpful for this task." }, { "code": null, "e": 18404, "s": 17734, "text": "Another interesting insight we can observe visually is the inverse correlation of speed with the number of observations. The image below shows two heatmaps overlaid, ego vehicle speed (blue) and agent observation density (red). Areas where the speed is low will likely result in an increase in the agent observation count. While this might not be obvious at first, the reason for this should be clear when we observe where on the map these correlations best occur; these occur at intersections, where speed is likely to decrease due to traffic lights or stop signs, and thus yields a higher likelihood for additional agent observations from traffic across both streets." }, { "code": null, "e": 19241, "s": 18404, "text": "To summarize, we discovered some useful insights about the data, which is an essential step in the model building process. To review the data holistically, we can employ tools like heatmaps and histograms at different scales to identify spatial patterns that may be advantageous to capture in our models. Being able to easily access data at a high-level and low-level through interactive selection was also helpful. The insights learned through the exploration process will lead to a better determination of what correlations and biases may exist in the dataset. It will also provide better information about the availability, distribution, and quality of particular data samples. Equipped with this knowledge, we can better feature engineer training sets and avoid overfitting or underfitting a certain subset of model-driven behavior." }, { "code": null, "e": 19461, "s": 19241, "text": "Transitioning from data exploration to model development, we’ll switch focus from a global view of the data to a local scene. We will explore aspects of visualizing scene data and path data for debugging and evaluation." }, { "code": null, "e": 20182, "s": 19461, "text": "As shown above, the local scene view within VizViewer offers a 3D simulation of the vehicle and its semantic environment, along with labels for agents, lane states, traffic light states, annotated bounding boxes for agents (yellow and blue boxes), and the annotated planned path of travel (blue). Plots of the various features are synchronized with the model simulation in one unified layout. VV also offers a UI for controlling the simulation's state, such as a play and pause button, rate controls, and discrete timestamp adjustments. The scene camera is fully interactive, allowing for visualizing different perspectives of the scene. These features are beneficial while debugging the model’s behavior within a scene." }, { "code": null, "e": 20602, "s": 20182, "text": "As part of a path prediction model, one subproblem is determining the current lane of a given vehicle. If we can accurately detect the lane a vehicle is in, we can build a model to predict where a vehicle will travel confidently, given the pose and derived motion features. Additionally, the semantic map will be needed to determine the possible lane paths in the environment through which vehicles would likely travel." }, { "code": null, "e": 21110, "s": 20602, "text": "During the course of this exploration, I was able to train a neural network with various pose features and the semantic map data to determine an estimate of the current lane and possible next lane. Using VizViewer, the lane lines and lane candidates can be visualized and annotated with additional data from the SVM network (e.g., raw regression values, confidence scores). By loading a scene, running the visual simulation, and using the interactive 3D view, the resulting paths can be examined and tested." }, { "code": null, "e": 21855, "s": 21110, "text": "The blue lane segments highlight the possible prediction paths, with a darker color representing a higher degree of confidence in the path. Additionally, the paths can be clicked to expose the underlying data, such as the confidence score. In the example scene above, the vehicle approaches a 3-way stop sign. The prediction that the vehicle would continue to move forward was fairly high as it came to a stop. As the vehicle began to move forward, the prediction began to change to a left turn and the confidence values increased as it moved through the turn. With an improved model that includes more data, such as considering the pedestrian motion and the delay between stopping and turning, a left turn prediction could be made much sooner." }, { "code": null, "e": 22467, "s": 21855, "text": "As the model is further developed, visualization can help determine how well the planned paths are performing. Deviations from a lane can be reviewed, potential collisions with other objects can be detected and highlighted for display. This evaluation can be performed for both ego and agents, detecting when paths intersect. Smoothness is also important for accurate behavior modeling. Using the chart functionality to display attributes such as speed and acceleration will also help evaluate how smooth a predicted path is. For achieving these goals, VV offers a beneficial UI for model tuning and assessment." }, { "code": null, "e": 22858, "s": 22467, "text": "The Lyft Prediction Dataset proved to be a massive dataset with the potential for some interesting patterns for research and prediction algorithms. The inclusion of free form agent observational data for motion prediction is beneficial and valuable. Additionally, the SDK offers useful tools for extracting the data; yet the dataset's structure is easy to navigate with a subset of the SDK." }, { "code": null, "e": 23696, "s": 22858, "text": "There are a few critiques about the dataset package. One downside is this dataset only includes a pre-planned path for the ego vehicle on a limited set of street types. Hopefully, in the future, Lyft will expand the dataset to include samples collected across a heterogeneous set of streets. Another point is the quality of agent labels are poor at times; labels are incorrectly assigned or unusual motion in the agents is apparent, but that should be expected for a small percentage of data samples. Additionally, while useful as a starting point, the visualization tools provided in the L5 Kit are far less helpful for data exploration. The visualization tool is provided, ostensively, as a way to generate training data for a possible convolutional neural network (CNN) based inference model, not necessarily for data exploration [2]." }, { "code": null, "e": 24317, "s": 23696, "text": "Through the use of the L5 Kit, VizViewer and Jupyter Notebooks, we explored and visualized the dataset in both novel and useful ways. Specifically, VV offered the ability to create a custom dashboard that can receive data from Python code for contextual visualization. The interactive charts, maps, 3D visualizations, and simulations were synthesized and synchronized to facilitate data discovery, exploration, and model debugging processes. Additionally, VV's interactive visualization features offered ways to perform these tasks with more freedom and efficacy than traditional Notebook based UI tools like Matplotlib." }, { "code": null, "e": 24453, "s": 24317, "text": "So how would approach analyzing a large dataset as the one reviewed here? What other interesting data points would you like to explore?" }, { "code": null, "e": 24709, "s": 24453, "text": "If you found this article interesting, please leave a comment and follow me for similar content. For information about VizViewer, please check out VizViewer.com, where you can sign-up to request access to the chat community and updates about the platform." }, { "code": null, "e": 24788, "s": 24709, "text": "[1] Lyft Level 5, Rethinking Maps for Self Driving, (2018), Lyft Level 5 Blog." }, { "code": null, "e": 24950, "s": 24788, "text": "[2] Houston, Zuidhof, Bergamini, et al., One Thousand and One Hours: Self-driving Motion Prediction Dataset (2020). Baseline motion prediction solution (page 6)." } ]
How to disable a MenuItem in Java?
To disable a MenuItem, use the setEnabled() method and set it to FALSE. Let’s say we have the following MenuBar − JMenuBar menuBar = new JMenuBar(); Now, create a Menu − JMenu fileMenu = new JMenu("File"); fileMenu.setMnemonic(KeyEvent.VK_F); menuBar.add(fileMenu); We will now create two MenuItems inside the above Menu − JMenuItem menuItem1 = new JMenuItem("New", KeyEvent.VK_N); fileMenu.add(menuItem1); JMenuItem menuItem2 = new JMenuItem("Open File", KeyEvent.VK_O); fileMenu.add(menuItem2); Now, let us disable the 2nd MenuItem − menuItem2.setEnabled(false); The following is an example to disable a MenuItem in Java − package my; import java.awt.Color; import java.awt.event.KeyEvent; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.UIManager; public class SwingDemo { public static void main(final String args[]) { JFrame frame = new JFrame("MenuBar Demo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JMenuBar menuBar = new JMenuBar(); UIManager.put("MenuBar.background", Color.ORANGE); JMenu fileMenu = new JMenu("File"); fileMenu.setMnemonic(KeyEvent.VK_F); menuBar.add(fileMenu); JMenuItem menuItem1 = new JMenuItem("New", KeyEvent.VK_N); fileMenu.add(menuItem1); JMenuItem menuItem2 = new JMenuItem("Open File", KeyEvent.VK_O); fileMenu.add(menuItem2); menuItem2.setEnabled(false); JMenu editMenu = new JMenu("Edit"); editMenu.setMnemonic(KeyEvent.VK_E); menuBar.add(editMenu); JMenuItem menuItem3 = new JMenuItem("Cut", KeyEvent.VK_C); editMenu.add(menuItem3); JMenu searchMenu = new JMenu("Search"); searchMenu.setMnemonic(KeyEvent.VK_S); menuBar.add(searchMenu); JMenu projectMenu = new JMenu("Project"); projectMenu.setMnemonic(KeyEvent.VK_P); menuBar.add(projectMenu); JMenu runMenu = new JMenu("Run"); runMenu.setMnemonic(KeyEvent.VK_R); menuBar.add(runMenu); menuBar.revalidate(); frame.setJMenuBar(menuBar); frame.setSize(550, 350); frame.setVisible(true); } } The output is as follows. Here, we have disabled the “Open File” MenuItem −
[ { "code": null, "e": 1176, "s": 1062, "text": "To disable a MenuItem, use the setEnabled() method and set it to FALSE. Let’s say we have the following MenuBar −" }, { "code": null, "e": 1211, "s": 1176, "text": "JMenuBar menuBar = new JMenuBar();" }, { "code": null, "e": 1232, "s": 1211, "text": "Now, create a Menu −" }, { "code": null, "e": 1328, "s": 1232, "text": "JMenu fileMenu = new JMenu(\"File\");\nfileMenu.setMnemonic(KeyEvent.VK_F);\nmenuBar.add(fileMenu);" }, { "code": null, "e": 1385, "s": 1328, "text": "We will now create two MenuItems inside the above Menu −" }, { "code": null, "e": 1559, "s": 1385, "text": "JMenuItem menuItem1 = new JMenuItem(\"New\", KeyEvent.VK_N);\nfileMenu.add(menuItem1);\nJMenuItem menuItem2 = new JMenuItem(\"Open File\", KeyEvent.VK_O);\nfileMenu.add(menuItem2);" }, { "code": null, "e": 1598, "s": 1559, "text": "Now, let us disable the 2nd MenuItem −" }, { "code": null, "e": 1627, "s": 1598, "text": "menuItem2.setEnabled(false);" }, { "code": null, "e": 1687, "s": 1627, "text": "The following is an example to disable a MenuItem in Java −" }, { "code": null, "e": 3223, "s": 1687, "text": "package my;\nimport java.awt.Color;\nimport java.awt.event.KeyEvent;\nimport javax.swing.JFrame;\nimport javax.swing.JMenu;\nimport javax.swing.JMenuBar;\nimport javax.swing.JMenuItem;\nimport javax.swing.UIManager;\npublic class SwingDemo {\n public static void main(final String args[]) {\n JFrame frame = new JFrame(\"MenuBar Demo\");\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n JMenuBar menuBar = new JMenuBar();\n UIManager.put(\"MenuBar.background\", Color.ORANGE);\n JMenu fileMenu = new JMenu(\"File\");\n fileMenu.setMnemonic(KeyEvent.VK_F);\n menuBar.add(fileMenu);\n JMenuItem menuItem1 = new JMenuItem(\"New\", KeyEvent.VK_N);\n fileMenu.add(menuItem1);\n JMenuItem menuItem2 = new JMenuItem(\"Open File\", KeyEvent.VK_O);\n fileMenu.add(menuItem2);\n menuItem2.setEnabled(false);\n JMenu editMenu = new JMenu(\"Edit\");\n editMenu.setMnemonic(KeyEvent.VK_E);\n menuBar.add(editMenu);\n JMenuItem menuItem3 = new JMenuItem(\"Cut\", KeyEvent.VK_C);\n editMenu.add(menuItem3);\n JMenu searchMenu = new JMenu(\"Search\");\n searchMenu.setMnemonic(KeyEvent.VK_S);\n menuBar.add(searchMenu);\n JMenu projectMenu = new JMenu(\"Project\");\n projectMenu.setMnemonic(KeyEvent.VK_P);\n menuBar.add(projectMenu);\n JMenu runMenu = new JMenu(\"Run\");\n runMenu.setMnemonic(KeyEvent.VK_R);\n menuBar.add(runMenu);\n menuBar.revalidate();\n frame.setJMenuBar(menuBar);\n frame.setSize(550, 350);\n frame.setVisible(true);\n }\n}" }, { "code": null, "e": 3299, "s": 3223, "text": "The output is as follows. Here, we have disabled the “Open File” MenuItem −" } ]
Count of all possible N length balanced Binary Strings - GeeksforGeeks
10 Dec, 2021 Given a number N, the task is to find the total number of balanced binary strings possible of length N. A binary string is said to be balanced if: The number of 0s and 1s are equal in each binary string The count of 0s in any prefix of binary strings is always greater than or equal to the count of 1s For Example: 01 is a balanced binary string of length 2, but 10 is not. Example: Input: N = 4Output: 2Explanation: Possible balanced binary strings are: 0101, 0011 Input: N = 5Output: 0 Approach: The given problem can be solved as below: If N is odd, then no balanced binary string is possible as the condition of an equal count of 0s and 1s will fail.If N is even, then the N length binary string will have N/2 balanced pair of 0s and 1s.So, now try to create a formula to get the number of balanced strings when N is even. If N is odd, then no balanced binary string is possible as the condition of an equal count of 0s and 1s will fail. If N is even, then the N length binary string will have N/2 balanced pair of 0s and 1s. So, now try to create a formula to get the number of balanced strings when N is even. So if N = 2, then possible balanced binary string will be “01” only, as “00” and “11” do not have same count of 0s and 1s and “10” does not have count of 0s >= count of 1s in prefix [0, 1).Similarly, if N=4, then possible balanced binary string will be “0101” and “0011”For N = 6, then possible balanced binary string will be “010101”, “010011”, “001101”, “000111”, and “001011”Now, If we consider this series:For N=0, count(0) = 1For N=2, count(2) = count(0)*count(0) = 1For N=4, count(4) = count(0)*count(2) + count(2)*count(0) = 1*1 + 1*1 = 2For N=6, count(6) = count(0)*count(4) + count(2)*count(2) + count(4)*count(0) = 1*2 + 1*1 + 2*1 = 5For N=8, count(8) = count(0)*count(6) + count(2)*count(4) + count(4)*count(2) + count(6)*count(0) = 1*5 + 1*2 + 2*1 + 5*1 = 14...For N=N, count(N) = count(0)*count(N-2) + count(2)*count(N-4) + count(4)*count(N-6) + .... + count(N-6)*count(4) + count(N-4)*count(2) + count(N-2)*count(0)which is nothing but Catalan numbers. Hence for any even N return Catalan number for (N/2) as the answer. Hence for any even N return Catalan number for (N/2) as the answer. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach #include <bits/stdc++.h>using namespace std; #define MAXN 500#define mod 1000000007 // Vector to store catalan numbervector<long long int> cat(MAXN + 1, 0); // Function to get the Catalan Numbervoid catalan(){ cat[0] = 1; cat[1] = 1; for (int i = 2; i < MAXN + 1; i++) { long long int t = 0; for (int j = 0; j < i; j++) { t += ((cat[j] % mod) * (cat[i - 1 - j] % mod) % mod); } cat[i] = (t % mod); }} int countBalancedStrings(int N){ // If N is odd if (N & 1) { return 0; } // Returning Catalan number // of N/2 as the answer return cat[N / 2];} // Driver Codeint main(){ // Precomputing catalan(); int N = 4; cout << countBalancedStrings(N);} // Java program for the above approachclass GFG { public static int MAXN = 500; public static int mod = 1000000007; // Vector to store catalan number public static int[] cat = new int[MAXN + 1]; // Function to get the Catalan Number public static void catalan() { cat[0] = 1; cat[1] = 1; for (int i = 2; i < MAXN + 1; i++) { int t = 0; for (int j = 0; j < i; j++) { t += ((cat[j] % mod) * (cat[i - 1 - j] % mod) % mod); } cat[i] = (t % mod); } } public static int countBalancedStrings(int N) { // If N is odd if ((N & 1) > 0) { return 0; } // Returning Catalan number // of N/2 as the answer return cat[N / 2]; } // Driver Code public static void main(String args[]) { // Precomputing catalan(); int N = 4; System.out.println(countBalancedStrings(N)); }} // This code is contributed by saurabh_jaiswal. # Python3 program for the above approachMAXN = 500mod = 1000000007 # Vector to store catalan numbercat = [0 for _ in range(MAXN + 1)] # Function to get the Catalan Numberdef catalan(): global cat cat[0] = 1 cat[1] = 1 for i in range(2, MAXN + 1): t = 0 for j in range(0, i): t += ((cat[j] % mod) * (cat[i - 1 - j] % mod) % mod) cat[i] = (t % mod) def countBalancedStrings(N): # If N is odd if (N & 1): return 0 # Returning Catalan number # of N/2 as the answer return cat[N // 2] # Driver Codeif __name__ == "__main__": # Precomputing catalan() N = 4 print(countBalancedStrings(N)) # This code is contributed by rakeshsahni // C# program for the above approachusing System;class GFG{ public static int MAXN = 500; public static int mod = 1000000007; // Vector to store catalan number public static int[] cat = new int[MAXN + 1]; // Function to get the Catalan Number public static void catalan() { cat[0] = 1; cat[1] = 1; for (int i = 2; i < MAXN + 1; i++) { int t = 0; for (int j = 0; j < i; j++) { t += ((cat[j] % mod) * (cat[i - 1 - j] % mod) % mod); } cat[i] = (t % mod); } } public static int countBalancedStrings(int N) { // If N is odd if ((N & 1) > 0) { return 0; } // Returning Catalan number // of N/2 as the answer return cat[N / 2]; } // Driver Code public static void Main() { // Precomputing catalan(); int N = 4; Console.Write(countBalancedStrings(N)); }} // This code is contributed by saurabh_jaiswal. <script> // JavaScript Program to implement // the above approach let MAXN = 500 let mod = 1000000007 // Vector to store catalan number let cat = new Array(MAXN + 1).fill(0); // Function to get the Catalan Number function catalan() { cat[0] = 1; cat[1] = 1; for (let i = 2; i < MAXN + 1; i++) { let t = 0; for (let j = 0; j < i; j++) { t += ((cat[j] % mod) * (cat[i - 1 - j] % mod) % mod); } cat[i] = (t % mod); } } function countBalancedStrings(N) { // If N is odd if (N & 1) { return 0; } // Returning Catalan number // of N/2 as the answer return cat[Math.floor(N / 2)]; } // Driver Code // Precomputing catalan(); let N = 4; document.write(countBalancedStrings(N)); // This code is contributed by Potta Lokesh</script> 2 Time Complexity: O(N2)Auxiliary Space: O(N) lokeshpotta20 rakeshsahni _saurabh_jaiswal binary-string Bit Magic Combinatorial Mathematical Strings Strings Mathematical Bit Magic Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Set, Clear and Toggle a given bit of a number in C Check whether K-th bit is set or not Write an Efficient Method to Check if a Number is Multiple of 3 Reverse actual bits of the given number Program to find parity Write a program to print all permutations of a given string Permutation and Combination in Python itertools.combinations() module in Python to print all possible combinations Factorial of a large number Program to calculate value of nCr
[ { "code": null, "e": 24597, "s": 24569, "text": "\n10 Dec, 2021" }, { "code": null, "e": 24744, "s": 24597, "text": "Given a number N, the task is to find the total number of balanced binary strings possible of length N. A binary string is said to be balanced if:" }, { "code": null, "e": 24800, "s": 24744, "text": "The number of 0s and 1s are equal in each binary string" }, { "code": null, "e": 24899, "s": 24800, "text": "The count of 0s in any prefix of binary strings is always greater than or equal to the count of 1s" }, { "code": null, "e": 24971, "s": 24899, "text": "For Example: 01 is a balanced binary string of length 2, but 10 is not." }, { "code": null, "e": 24980, "s": 24971, "text": "Example:" }, { "code": null, "e": 25063, "s": 24980, "text": "Input: N = 4Output: 2Explanation: Possible balanced binary strings are: 0101, 0011" }, { "code": null, "e": 25085, "s": 25063, "text": "Input: N = 5Output: 0" }, { "code": null, "e": 25137, "s": 25085, "text": "Approach: The given problem can be solved as below:" }, { "code": null, "e": 25424, "s": 25137, "text": "If N is odd, then no balanced binary string is possible as the condition of an equal count of 0s and 1s will fail.If N is even, then the N length binary string will have N/2 balanced pair of 0s and 1s.So, now try to create a formula to get the number of balanced strings when N is even." }, { "code": null, "e": 25539, "s": 25424, "text": "If N is odd, then no balanced binary string is possible as the condition of an equal count of 0s and 1s will fail." }, { "code": null, "e": 25627, "s": 25539, "text": "If N is even, then the N length binary string will have N/2 balanced pair of 0s and 1s." }, { "code": null, "e": 25713, "s": 25627, "text": "So, now try to create a formula to get the number of balanced strings when N is even." }, { "code": null, "e": 26680, "s": 25713, "text": "So if N = 2, then possible balanced binary string will be “01” only, as “00” and “11” do not have same count of 0s and 1s and “10” does not have count of 0s >= count of 1s in prefix [0, 1).Similarly, if N=4, then possible balanced binary string will be “0101” and “0011”For N = 6, then possible balanced binary string will be “010101”, “010011”, “001101”, “000111”, and “001011”Now, If we consider this series:For N=0, count(0) = 1For N=2, count(2) = count(0)*count(0) = 1For N=4, count(4) = count(0)*count(2) + count(2)*count(0) = 1*1 + 1*1 = 2For N=6, count(6) = count(0)*count(4) + count(2)*count(2) + count(4)*count(0) = 1*2 + 1*1 + 2*1 = 5For N=8, count(8) = count(0)*count(6) + count(2)*count(4) + count(4)*count(2) + count(6)*count(0) = 1*5 + 1*2 + 2*1 + 5*1 = 14...For N=N, count(N) = count(0)*count(N-2) + count(2)*count(N-4) + count(4)*count(N-6) + .... + count(N-6)*count(4) + count(N-4)*count(2) + count(N-2)*count(0)which is nothing but Catalan numbers." }, { "code": null, "e": 26748, "s": 26680, "text": "Hence for any even N return Catalan number for (N/2) as the answer." }, { "code": null, "e": 26816, "s": 26748, "text": "Hence for any even N return Catalan number for (N/2) as the answer." }, { "code": null, "e": 26867, "s": 26816, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26871, "s": 26867, "text": "C++" }, { "code": null, "e": 26876, "s": 26871, "text": "Java" }, { "code": null, "e": 26884, "s": 26876, "text": "Python3" }, { "code": null, "e": 26887, "s": 26884, "text": "C#" }, { "code": null, "e": 26898, "s": 26887, "text": "Javascript" }, { "code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; #define MAXN 500#define mod 1000000007 // Vector to store catalan numbervector<long long int> cat(MAXN + 1, 0); // Function to get the Catalan Numbervoid catalan(){ cat[0] = 1; cat[1] = 1; for (int i = 2; i < MAXN + 1; i++) { long long int t = 0; for (int j = 0; j < i; j++) { t += ((cat[j] % mod) * (cat[i - 1 - j] % mod) % mod); } cat[i] = (t % mod); }} int countBalancedStrings(int N){ // If N is odd if (N & 1) { return 0; } // Returning Catalan number // of N/2 as the answer return cat[N / 2];} // Driver Codeint main(){ // Precomputing catalan(); int N = 4; cout << countBalancedStrings(N);}", "e": 27705, "s": 26898, "text": null }, { "code": "// Java program for the above approachclass GFG { public static int MAXN = 500; public static int mod = 1000000007; // Vector to store catalan number public static int[] cat = new int[MAXN + 1]; // Function to get the Catalan Number public static void catalan() { cat[0] = 1; cat[1] = 1; for (int i = 2; i < MAXN + 1; i++) { int t = 0; for (int j = 0; j < i; j++) { t += ((cat[j] % mod) * (cat[i - 1 - j] % mod) % mod); } cat[i] = (t % mod); } } public static int countBalancedStrings(int N) { // If N is odd if ((N & 1) > 0) { return 0; } // Returning Catalan number // of N/2 as the answer return cat[N / 2]; } // Driver Code public static void main(String args[]) { // Precomputing catalan(); int N = 4; System.out.println(countBalancedStrings(N)); }} // This code is contributed by saurabh_jaiswal.", "e": 28786, "s": 27705, "text": null }, { "code": "# Python3 program for the above approachMAXN = 500mod = 1000000007 # Vector to store catalan numbercat = [0 for _ in range(MAXN + 1)] # Function to get the Catalan Numberdef catalan(): global cat cat[0] = 1 cat[1] = 1 for i in range(2, MAXN + 1): t = 0 for j in range(0, i): t += ((cat[j] % mod) * (cat[i - 1 - j] % mod) % mod) cat[i] = (t % mod) def countBalancedStrings(N): # If N is odd if (N & 1): return 0 # Returning Catalan number # of N/2 as the answer return cat[N // 2] # Driver Codeif __name__ == \"__main__\": # Precomputing catalan() N = 4 print(countBalancedStrings(N)) # This code is contributed by rakeshsahni", "e": 29517, "s": 28786, "text": null }, { "code": "// C# program for the above approachusing System;class GFG{ public static int MAXN = 500; public static int mod = 1000000007; // Vector to store catalan number public static int[] cat = new int[MAXN + 1]; // Function to get the Catalan Number public static void catalan() { cat[0] = 1; cat[1] = 1; for (int i = 2; i < MAXN + 1; i++) { int t = 0; for (int j = 0; j < i; j++) { t += ((cat[j] % mod) * (cat[i - 1 - j] % mod) % mod); } cat[i] = (t % mod); } } public static int countBalancedStrings(int N) { // If N is odd if ((N & 1) > 0) { return 0; } // Returning Catalan number // of N/2 as the answer return cat[N / 2]; } // Driver Code public static void Main() { // Precomputing catalan(); int N = 4; Console.Write(countBalancedStrings(N)); }} // This code is contributed by saurabh_jaiswal.", "e": 30605, "s": 29517, "text": null }, { "code": "<script> // JavaScript Program to implement // the above approach let MAXN = 500 let mod = 1000000007 // Vector to store catalan number let cat = new Array(MAXN + 1).fill(0); // Function to get the Catalan Number function catalan() { cat[0] = 1; cat[1] = 1; for (let i = 2; i < MAXN + 1; i++) { let t = 0; for (let j = 0; j < i; j++) { t += ((cat[j] % mod) * (cat[i - 1 - j] % mod) % mod); } cat[i] = (t % mod); } } function countBalancedStrings(N) { // If N is odd if (N & 1) { return 0; } // Returning Catalan number // of N/2 as the answer return cat[Math.floor(N / 2)]; } // Driver Code // Precomputing catalan(); let N = 4; document.write(countBalancedStrings(N)); // This code is contributed by Potta Lokesh</script>", "e": 31570, "s": 30605, "text": null }, { "code": null, "e": 31572, "s": 31570, "text": "2" }, { "code": null, "e": 31616, "s": 31572, "text": "Time Complexity: O(N2)Auxiliary Space: O(N)" }, { "code": null, "e": 31632, "s": 31618, "text": "lokeshpotta20" }, { "code": null, "e": 31644, "s": 31632, "text": "rakeshsahni" }, { "code": null, "e": 31661, "s": 31644, "text": "_saurabh_jaiswal" }, { "code": null, "e": 31675, "s": 31661, "text": "binary-string" }, { "code": null, "e": 31685, "s": 31675, "text": "Bit Magic" }, { "code": null, "e": 31699, "s": 31685, "text": "Combinatorial" }, { "code": null, "e": 31712, "s": 31699, "text": "Mathematical" }, { "code": null, "e": 31720, "s": 31712, "text": "Strings" }, { "code": null, "e": 31728, "s": 31720, "text": "Strings" }, { "code": null, "e": 31741, "s": 31728, "text": "Mathematical" }, { "code": null, "e": 31751, "s": 31741, "text": "Bit Magic" }, { "code": null, "e": 31765, "s": 31751, "text": "Combinatorial" }, { "code": null, "e": 31863, "s": 31765, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31872, "s": 31863, "text": "Comments" }, { "code": null, "e": 31885, "s": 31872, "text": "Old Comments" }, { "code": null, "e": 31936, "s": 31885, "text": "Set, Clear and Toggle a given bit of a number in C" }, { "code": null, "e": 31973, "s": 31936, "text": "Check whether K-th bit is set or not" }, { "code": null, "e": 32037, "s": 31973, "text": "Write an Efficient Method to Check if a Number is Multiple of 3" }, { "code": null, "e": 32077, "s": 32037, "text": "Reverse actual bits of the given number" }, { "code": null, "e": 32100, "s": 32077, "text": "Program to find parity" }, { "code": null, "e": 32160, "s": 32100, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 32198, "s": 32160, "text": "Permutation and Combination in Python" }, { "code": null, "e": 32275, "s": 32198, "text": "itertools.combinations() module in Python to print all possible combinations" }, { "code": null, "e": 32303, "s": 32275, "text": "Factorial of a large number" } ]
Create a two line legend in a Bokeh Plot - GeeksforGeeks
27 May, 2021 In this article, we will be learning about how to create a two line legend in the bokeh plot. Legends are one of the most essential parts of a bokeh plot. They help us to differentiate between different glyphs used in a plot. Other than that if we need to plot different lines of different colors in the same plot, we can differentiate them using legend. Also, we can change various properties of the things mentioned in the legend. But before we dive deep into the topic, we should either have google colab or should be using a local device code editor. If we are working in google colab, then we can straight away go to the below implementation. But if we are using a local device, then we should ensure that we have bokeh preinstalled in our device, else we can install it too. Open a command prompt and write pip install bokeh Now, everything is set. The installation is essential in our local device else the functionalities won’t work. Let’s move to the above implementation. Example 1: In the first example, we are looking at some lines which are plotted using a wide range of points in an empty canvas. Using legend in bokeh we are differentiating the lines. The main thing to notice here is, we are having a two-line legend. So without further wait, let’s go to the code and see how it works. Code: Python3 # importing show from# bokeh.io to show the plotfrom bokeh.io import show # importing legend from bokeh.modelsfrom bokeh.models import Legend # importing figure from bokeh.plottingfrom bokeh.plotting import figure # importing numpy package from pythonimport numpy as np # Creating an empty figure of plot height=600# and plot width=600fig = figure(plot_height=600, plot_width=600) # Creating point1 which is a yellow color line with# line width as 3 for a set of pointspoint1 = fig.line(x=[0, 1.43, 2.76, 3.24, 4.45, 5.65, 6.98, 7, 8, 9.76, 10.67, 11.54, 12.567, 13.21, 14.65, 15, 16.45, 17, 18.32, 19.57, 20], y=np.linspace(0, 2, 21), line_width=3, color="yellow") # Creating point2 which is a purple color line with# line width as 2 for a set of pointspoint2 = fig.line(x=np.linspace(0, 20, 20), y=np.linspace(0, 3, 20), line_width=2, color="purple") # Creating point3 which is a pink color line with# line width as 4 for a set of pointspoint3 = fig.line(x=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], y=[3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2.5, 2.34, 2.48, 2.67, 2.12, 2.01, 1.67, 1.98, 1.07, 1], line_width=4, color="pink") # Creating point4 which is a green color line with# line width as 2 for a set of pointspoint4 = fig.line(x=[0, 20], y=5, line_width=2, color="green") # Using legend we are placing two point descriptions# beside each other horizontallylegend1 = Legend(items=[("point1", [point1]), ("point2", [point2])], location=(7, 2), orientation="horizontal") # Using legend we are placing th other two point# descriptions beside each other horizontallylegend2 = Legend(items=[("point3", [point3]), ("point4", [point4])], location=(7, 2), orientation="horizontal") # placing legend1 at the topfig.add_layout(legend1, 'above') # placing legend2 at the topfig.add_layout(legend2, 'above') # showing the figureshow(fig) Output: Explanation: In the above example, we are importing all the necessary packages at first such as show, figure, Legend, and numpy from different modules of the bokeh library that python provides us. After importing the packages, we are creating an empty figure of plot width and height as 600. After that, we are creating four different lines with a different set of points along with different line colors and line width. In order to identify them, a legend is used. Now to create a two-line legend, we are using two variables legend1 and legend2 where we are storing two points in each of the variables where we are providing the orientation as horizontal. As a result, two will be shown in each row. Using ‘add_layout‘ we are determining the position of the legend as above i.e it will be shown at the top of the graphical representation. Finally, we are showing the plot using a show from bokeh.io. Example 2: In the next example, we will be exploring the concept with some glyphs provided by bokeh. Bokeh provides us with various types of glyphs, so we will be implementing the same concept used in the earlier example. Code: Python3 # importing show from# bokeh.io to show the plotfrom bokeh.io import show # importing legend from bokeh.modelsfrom bokeh.models import Legend # importing figure from bokeh.plottingfrom bokeh.plotting import figure # importing numpy package from pythonimport numpy as np x1 = [7, 8, 4, 3, 2, 9, 10, 11, 6, 6, 3]y1 = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] # Creating an empty figure of plot height=600# and plot width=600fig = figure(plot_height=600, plot_width=600) # Creating point1 in the form of circular glyphs# with a set of pointspoint1 = fig.circle(x=np.arange(14), y=[14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]) # Creating point2 in the form of triangular glyphs# with a set of pointspoint2 = fig.triangle(x=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14], y=[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196], size=30, color="green", alpha=0.5) # Creating point3 in the form of diamond shaped glyphs# with a set of pointspoint3 = fig.diamond(x=[1, 2, 4], y=[20, 19, 1], color="red", alpha=0.4) # Creating point4 in the form of square shaped glyphs# with a set of pointspoint4 = fig.square(x=[70, 80, 40, 30, 20, 10], y=[10, 20, 40, 50, 60, 70], color="red", size=20, alpha=0.6) # Creating point5 in the form of inverted triangular glyphs# with a set of pointspoint5 = fig.inverted_triangle(x=[75, 85, 45, 35, 25, 15], y=[15, 25, 45, 55, 65, 75], color="purple", size=10, alpha=0.6) # Creating point6 in the form of square shaped glyphs# with a set of pointspoint6 = fig.square(x1, y1, color="yellow", size=20, alpha=0.6) # Using legend we are placing two point descriptions# beside each other# horizontallylegend1 = Legend(items=[("point1", [point1]), ("point2", [point2])], location=(10, 10), orientation="horizontal") # Using legend we are placing th other two point# descriptions beside each other horizontallylegend2 = Legend(items=[("point3", [point3]), ("point4", [point4])], location=(10, 10), orientation="horizontal") # Using legend we are placing th other two point# descriptions beside each other horizontallylegend3 = Legend(items=[("point5", [point5]), ("point6", [point6])], location=(10, 10), orientation="horizontal") # placing legend1 at the bottomfig.add_layout(legend1, 'below') # placing legend2 at the bottomfig.add_layout(legend2, 'below') # placing legend3 at the bottomfig.add_layout(legend3, 'below') # showing the figureshow(fig) Output: Explanation: After importing the required packages, we are taking two variables x1 and y1 with a set of points that are to be plotted later. After that, we are setting the plot width and plot height as 600. Now, bokeh provides us with a variety of glyphs that can be used to differentiate different plots in a graph. So, we took some of the glyphs to point 6 such graphs in our plot with a wide range of points. After pointing them, we used the legend to identify each of the glyphs and we kept two points beside each other along with their orientation as ‘horizontal‘. Now using ‘add_layout‘ option, we can determine the position of the legend box. In this case, we are placing it at the bottom. Finally, we are showing the figure with the help of ‘show‘ from ‘bokeh.io‘. sooda367 Picked Python-Bokeh Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Enumerate() in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() sum() function in Python Create a Pandas DataFrame from Lists How to drop one or multiple columns in Pandas Dataframe *args and **kwargs in Python Graph Plotting in Python | Set 1
[ { "code": null, "e": 24217, "s": 24189, "text": "\n27 May, 2021" }, { "code": null, "e": 24650, "s": 24217, "text": "In this article, we will be learning about how to create a two line legend in the bokeh plot. Legends are one of the most essential parts of a bokeh plot. They help us to differentiate between different glyphs used in a plot. Other than that if we need to plot different lines of different colors in the same plot, we can differentiate them using legend. Also, we can change various properties of the things mentioned in the legend." }, { "code": null, "e": 25030, "s": 24650, "text": "But before we dive deep into the topic, we should either have google colab or should be using a local device code editor. If we are working in google colab, then we can straight away go to the below implementation. But if we are using a local device, then we should ensure that we have bokeh preinstalled in our device, else we can install it too. Open a command prompt and write" }, { "code": null, "e": 25048, "s": 25030, "text": "pip install bokeh" }, { "code": null, "e": 25199, "s": 25048, "text": "Now, everything is set. The installation is essential in our local device else the functionalities won’t work. Let’s move to the above implementation." }, { "code": null, "e": 25210, "s": 25199, "text": "Example 1:" }, { "code": null, "e": 25519, "s": 25210, "text": "In the first example, we are looking at some lines which are plotted using a wide range of points in an empty canvas. Using legend in bokeh we are differentiating the lines. The main thing to notice here is, we are having a two-line legend. So without further wait, let’s go to the code and see how it works." }, { "code": null, "e": 25525, "s": 25519, "text": "Code:" }, { "code": null, "e": 25533, "s": 25525, "text": "Python3" }, { "code": "# importing show from# bokeh.io to show the plotfrom bokeh.io import show # importing legend from bokeh.modelsfrom bokeh.models import Legend # importing figure from bokeh.plottingfrom bokeh.plotting import figure # importing numpy package from pythonimport numpy as np # Creating an empty figure of plot height=600# and plot width=600fig = figure(plot_height=600, plot_width=600) # Creating point1 which is a yellow color line with# line width as 3 for a set of pointspoint1 = fig.line(x=[0, 1.43, 2.76, 3.24, 4.45, 5.65, 6.98, 7, 8, 9.76, 10.67, 11.54, 12.567, 13.21, 14.65, 15, 16.45, 17, 18.32, 19.57, 20], y=np.linspace(0, 2, 21), line_width=3, color=\"yellow\") # Creating point2 which is a purple color line with# line width as 2 for a set of pointspoint2 = fig.line(x=np.linspace(0, 20, 20), y=np.linspace(0, 3, 20), line_width=2, color=\"purple\") # Creating point3 which is a pink color line with# line width as 4 for a set of pointspoint3 = fig.line(x=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], y=[3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2.5, 2.34, 2.48, 2.67, 2.12, 2.01, 1.67, 1.98, 1.07, 1], line_width=4, color=\"pink\") # Creating point4 which is a green color line with# line width as 2 for a set of pointspoint4 = fig.line(x=[0, 20], y=5, line_width=2, color=\"green\") # Using legend we are placing two point descriptions# beside each other horizontallylegend1 = Legend(items=[(\"point1\", [point1]), (\"point2\", [point2])], location=(7, 2), orientation=\"horizontal\") # Using legend we are placing th other two point# descriptions beside each other horizontallylegend2 = Legend(items=[(\"point3\", [point3]), (\"point4\", [point4])], location=(7, 2), orientation=\"horizontal\") # placing legend1 at the topfig.add_layout(legend1, 'above') # placing legend2 at the topfig.add_layout(legend2, 'above') # showing the figureshow(fig)", "e": 27669, "s": 25533, "text": null }, { "code": null, "e": 27677, "s": 27669, "text": "Output:" }, { "code": null, "e": 27690, "s": 27677, "text": "Explanation:" }, { "code": null, "e": 27874, "s": 27690, "text": "In the above example, we are importing all the necessary packages at first such as show, figure, Legend, and numpy from different modules of the bokeh library that python provides us." }, { "code": null, "e": 27969, "s": 27874, "text": "After importing the packages, we are creating an empty figure of plot width and height as 600." }, { "code": null, "e": 28143, "s": 27969, "text": "After that, we are creating four different lines with a different set of points along with different line colors and line width. In order to identify them, a legend is used." }, { "code": null, "e": 28378, "s": 28143, "text": "Now to create a two-line legend, we are using two variables legend1 and legend2 where we are storing two points in each of the variables where we are providing the orientation as horizontal. As a result, two will be shown in each row." }, { "code": null, "e": 28517, "s": 28378, "text": "Using ‘add_layout‘ we are determining the position of the legend as above i.e it will be shown at the top of the graphical representation." }, { "code": null, "e": 28578, "s": 28517, "text": "Finally, we are showing the plot using a show from bokeh.io." }, { "code": null, "e": 28589, "s": 28578, "text": "Example 2:" }, { "code": null, "e": 28800, "s": 28589, "text": "In the next example, we will be exploring the concept with some glyphs provided by bokeh. Bokeh provides us with various types of glyphs, so we will be implementing the same concept used in the earlier example." }, { "code": null, "e": 28806, "s": 28800, "text": "Code:" }, { "code": null, "e": 28814, "s": 28806, "text": "Python3" }, { "code": "# importing show from# bokeh.io to show the plotfrom bokeh.io import show # importing legend from bokeh.modelsfrom bokeh.models import Legend # importing figure from bokeh.plottingfrom bokeh.plotting import figure # importing numpy package from pythonimport numpy as np x1 = [7, 8, 4, 3, 2, 9, 10, 11, 6, 6, 3]y1 = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] # Creating an empty figure of plot height=600# and plot width=600fig = figure(plot_height=600, plot_width=600) # Creating point1 in the form of circular glyphs# with a set of pointspoint1 = fig.circle(x=np.arange(14), y=[14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]) # Creating point2 in the form of triangular glyphs# with a set of pointspoint2 = fig.triangle(x=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14], y=[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196], size=30, color=\"green\", alpha=0.5) # Creating point3 in the form of diamond shaped glyphs# with a set of pointspoint3 = fig.diamond(x=[1, 2, 4], y=[20, 19, 1], color=\"red\", alpha=0.4) # Creating point4 in the form of square shaped glyphs# with a set of pointspoint4 = fig.square(x=[70, 80, 40, 30, 20, 10], y=[10, 20, 40, 50, 60, 70], color=\"red\", size=20, alpha=0.6) # Creating point5 in the form of inverted triangular glyphs# with a set of pointspoint5 = fig.inverted_triangle(x=[75, 85, 45, 35, 25, 15], y=[15, 25, 45, 55, 65, 75], color=\"purple\", size=10, alpha=0.6) # Creating point6 in the form of square shaped glyphs# with a set of pointspoint6 = fig.square(x1, y1, color=\"yellow\", size=20, alpha=0.6) # Using legend we are placing two point descriptions# beside each other# horizontallylegend1 = Legend(items=[(\"point1\", [point1]), (\"point2\", [point2])], location=(10, 10), orientation=\"horizontal\") # Using legend we are placing th other two point# descriptions beside each other horizontallylegend2 = Legend(items=[(\"point3\", [point3]), (\"point4\", [point4])], location=(10, 10), orientation=\"horizontal\") # Using legend we are placing th other two point# descriptions beside each other horizontallylegend3 = Legend(items=[(\"point5\", [point5]), (\"point6\", [point6])], location=(10, 10), orientation=\"horizontal\") # placing legend1 at the bottomfig.add_layout(legend1, 'below') # placing legend2 at the bottomfig.add_layout(legend2, 'below') # placing legend3 at the bottomfig.add_layout(legend3, 'below') # showing the figureshow(fig)", "e": 31640, "s": 28814, "text": null }, { "code": null, "e": 31648, "s": 31640, "text": "Output:" }, { "code": null, "e": 31661, "s": 31648, "text": "Explanation:" }, { "code": null, "e": 31789, "s": 31661, "text": "After importing the required packages, we are taking two variables x1 and y1 with a set of points that are to be plotted later." }, { "code": null, "e": 32060, "s": 31789, "text": "After that, we are setting the plot width and plot height as 600. Now, bokeh provides us with a variety of glyphs that can be used to differentiate different plots in a graph. So, we took some of the glyphs to point 6 such graphs in our plot with a wide range of points." }, { "code": null, "e": 32218, "s": 32060, "text": "After pointing them, we used the legend to identify each of the glyphs and we kept two points beside each other along with their orientation as ‘horizontal‘." }, { "code": null, "e": 32345, "s": 32218, "text": "Now using ‘add_layout‘ option, we can determine the position of the legend box. In this case, we are placing it at the bottom." }, { "code": null, "e": 32421, "s": 32345, "text": "Finally, we are showing the figure with the help of ‘show‘ from ‘bokeh.io‘." }, { "code": null, "e": 32430, "s": 32421, "text": "sooda367" }, { "code": null, "e": 32437, "s": 32430, "text": "Picked" }, { "code": null, "e": 32450, "s": 32437, "text": "Python-Bokeh" }, { "code": null, "e": 32457, "s": 32450, "text": "Python" }, { "code": null, "e": 32555, "s": 32457, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32564, "s": 32555, "text": "Comments" }, { "code": null, "e": 32577, "s": 32564, "text": "Old Comments" }, { "code": null, "e": 32595, "s": 32577, "text": "Python Dictionary" }, { "code": null, "e": 32617, "s": 32595, "text": "Enumerate() in Python" }, { "code": null, "e": 32649, "s": 32617, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 32691, "s": 32649, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 32717, "s": 32691, "text": "Python String | replace()" }, { "code": null, "e": 32742, "s": 32717, "text": "sum() function in Python" }, { "code": null, "e": 32779, "s": 32742, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 32835, "s": 32779, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 32864, "s": 32835, "text": "*args and **kwargs in Python" } ]
Product of Complex Numbers using three Multiplication Operation
29 Nov, 2021 Given four integers a, b, c, and d which represents two complex numbers of the form (a + bi) and (c + di), the task is to find the product of the given complex numbers using only three multiplication operations.Examples: Input: a = 2, b = 3, c = 4 and d = 5 Output: -7 + 22i Explanation: Product is given by: (2 + 3i)*(4 + 5i) = 2*4 + 4*3i + 2*5i + 3*5*(-1) = 8 – 15 + (12 + 10)i = -7 + 22iInput: a = 3, b = 7, c = 6 and d = 2 Output: 4 + 48i Naive Approach: The naive approach is to directly multiply given two complex numbers as: => (a + bi)*(c + di) => a(c + di) + b*i(c + di) => a*c + ad*i + b*c*i + b*d*i*i => (a*c – b*d) + (a*d + b*c)*i The above operations would required four multiplication to find the product of two complex number.Efficient Approach: The above approach required four multiplication to find the product. It can be reduced to three multiplication as:Multiplication of two Complex Numbers is as follows: (a + bi)*(c + di) = a*c – b*d + (a*d + b*c)i Simplify real part: real part = a*c – b*d Let prod1 = a*c and prod2 = b*d. Thus, real part = prod1 – prod2 Simplify the imaginary part as follows: imaginary part = a*d + b*cAdding and subtracting a*c and b*d in the above imaginar part we have,imaginary part = a*c – a*c + a*d + b*c + b*d – b*d, On rearranging the terms we get, => a*b + b*c + a*d + b*d – a*c – b*d => (a + b)*c + (a + b)*d – a*c – b*d => (a + b)*(c + d) – a*c – b*dLet prod3 = (a + b)*(c + d) Then the imaginary part is given by prod3 – (prod1 + prod2). Thus, we need to find the value of prod1 = a * c, prod2 = b * d, and prod3 = ( a + b ) * ( c + d ).So, our final answer will be: Real Part = prod1 – prod2 Imaginary Part = prod3 – (prod1 + prod2) Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to multiply Complex// Numbers with just three// multiplicationsvoid print_product(int a, int b, int c, int d){ // Find value of prod1, prod2 and prod3 int prod1 = a * c; int prod2 = b * d; int prod3 = (a + b) * (c + d); // Real Part int real = prod1 - prod2; // Imaginary Part int imag = prod3 - (prod1 + prod2); // Print the result cout << real << " + " << imag << "i";} // Driver Codeint main(){ int a, b, c, d; // Given four Numbers a = 2; b = 3; c = 4; d = 5; // Function Call print_product(a, b, c, d); return 0;} // Java program for the above approachclass GFG{ // Function to multiply Complex// Numbers with just three// multiplicationsstatic void print_product(int a, int b, int c, int d){ // Find value of prod1, prod2 and prod3 int prod1 = a * c; int prod2 = b * d; int prod3 = (a + b) * (c + d); // Real Part int real = prod1 - prod2; // Imaginary Part int imag = prod3 - (prod1 + prod2); // Print the result System.out.println(real + " + " + imag + "i");} // Driver Codepublic static void main(String[] args){ // Given four numbers int a = 2; int b = 3; int c = 4; int d = 5; // Function call print_product(a, b, c, d);}} // This code is contributed by Pratima Pandey # Python3 program for the above approach # Function to multiply Complex# Numbers with just three# multiplicationsdef print_product(a, b, c, d): # Find value of prod1, prod2 # and prod3 prod1 = a * c prod2 = b * d prod3 = (a + b) * (c + d) # Real part real = prod1 - prod2 # Imaginary part imag = prod3 - (prod1 + prod2) # Print the result print(real, " + ", imag, "i") # Driver code # Given four numbersa = 2b = 3c = 4d = 5 # Function callprint_product(a, b, c, d) # This code is contributed by Vishal Maurya. // C# program for the above approachusing System;class GFG{ // Function to multiply Complex// Numbers with just three// multiplicationsstatic void print_product(int a, int b, int c, int d){ // Find value of prod1, prod2 and prod3 int prod1 = a * c; int prod2 = b * d; int prod3 = (a + b) * (c + d); // Real Part int real = prod1 - prod2; // Imaginary Part int imag = prod3 - (prod1 + prod2); // Print the result Console.Write(real + " + " + imag + "i");} // Driver Codepublic static void Main(){ int a, b, c, d; // Given four Numbers a = 2; b = 3; c = 4; d = 5; // Function Call print_product(a, b, c, d);}} // This code is contributed by Code_Mech <script> // Javascript program for the above approach // Function to multiply Complex// Numbers with just three// multiplicationsfunction print_product( a, b, c, d){ // Find value of prod1, prod2 and prod3 let prod1 = a * c; let prod2 = b * d; let prod3 = (a + b) * (c + d); // Real Part let real = prod1 - prod2; // Imaginary Part let imag = prod3 - (prod1 + prod2); // Print the result document.write(real + " + " + imag + "i");} // Driver Code let a, b, c, d; // Given four Numbersa = 2;b = 3;c = 4;d = 5; // Function Callprint_product(a, b, c, d); </script> -7 + 22i Time Complexity: O(1) Auxiliary Space: O(1) vishu2908 Code_Mech dewantipandeydp jana_sayantan kk9826225 Numbers Mathematical School Programming Mathematical Numbers Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Algorithm to solve Rubik's Cube Merge two sorted arrays with O(1) extra space Sum of the series (1*2) + (2*3) + (3*4) + ...... upto n terms Program to print prime numbers from 1 to N. Segment Tree | Set 1 (Sum of given range) Python Dictionary Reverse a string in Java Arrays in C/C++ Introduction To PYTHON Interfaces in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Nov, 2021" }, { "code": null, "e": 250, "s": 28, "text": "Given four integers a, b, c, and d which represents two complex numbers of the form (a + bi) and (c + di), the task is to find the product of the given complex numbers using only three multiplication operations.Examples: " }, { "code": null, "e": 474, "s": 250, "text": "Input: a = 2, b = 3, c = 4 and d = 5 Output: -7 + 22i Explanation: Product is given by: (2 + 3i)*(4 + 5i) = 2*4 + 4*3i + 2*5i + 3*5*(-1) = 8 – 15 + (12 + 10)i = -7 + 22iInput: a = 3, b = 7, c = 6 and d = 2 Output: 4 + 48i " }, { "code": null, "e": 566, "s": 476, "text": "Naive Approach: The naive approach is to directly multiply given two complex numbers as: " }, { "code": null, "e": 679, "s": 566, "text": "=> (a + bi)*(c + di) => a(c + di) + b*i(c + di) => a*c + ad*i + b*c*i + b*d*i*i => (a*c – b*d) + (a*d + b*c)*i " }, { "code": null, "e": 965, "s": 679, "text": "The above operations would required four multiplication to find the product of two complex number.Efficient Approach: The above approach required four multiplication to find the product. It can be reduced to three multiplication as:Multiplication of two Complex Numbers is as follows: " }, { "code": null, "e": 1012, "s": 965, "text": "(a + bi)*(c + di) = a*c – b*d + (a*d + b*c)i " }, { "code": null, "e": 1032, "s": 1012, "text": "Simplify real part:" }, { "code": null, "e": 1121, "s": 1032, "text": "real part = a*c – b*d Let prod1 = a*c and prod2 = b*d. Thus, real part = prod1 – prod2 " }, { "code": null, "e": 1162, "s": 1121, "text": "Simplify the imaginary part as follows: " }, { "code": null, "e": 1538, "s": 1162, "text": "imaginary part = a*d + b*cAdding and subtracting a*c and b*d in the above imaginar part we have,imaginary part = a*c – a*c + a*d + b*c + b*d – b*d, On rearranging the terms we get, => a*b + b*c + a*d + b*d – a*c – b*d => (a + b)*c + (a + b)*d – a*c – b*d => (a + b)*(c + d) – a*c – b*dLet prod3 = (a + b)*(c + d) Then the imaginary part is given by prod3 – (prod1 + prod2). " }, { "code": null, "e": 1669, "s": 1538, "text": "Thus, we need to find the value of prod1 = a * c, prod2 = b * d, and prod3 = ( a + b ) * ( c + d ).So, our final answer will be: " }, { "code": null, "e": 1738, "s": 1669, "text": "Real Part = prod1 – prod2 Imaginary Part = prod3 – (prod1 + prod2) " }, { "code": null, "e": 1789, "s": 1738, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1793, "s": 1789, "text": "C++" }, { "code": null, "e": 1798, "s": 1793, "text": "Java" }, { "code": null, "e": 1806, "s": 1798, "text": "Python3" }, { "code": null, "e": 1809, "s": 1806, "text": "C#" }, { "code": null, "e": 1820, "s": 1809, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to multiply Complex// Numbers with just three// multiplicationsvoid print_product(int a, int b, int c, int d){ // Find value of prod1, prod2 and prod3 int prod1 = a * c; int prod2 = b * d; int prod3 = (a + b) * (c + d); // Real Part int real = prod1 - prod2; // Imaginary Part int imag = prod3 - (prod1 + prod2); // Print the result cout << real << \" + \" << imag << \"i\";} // Driver Codeint main(){ int a, b, c, d; // Given four Numbers a = 2; b = 3; c = 4; d = 5; // Function Call print_product(a, b, c, d); return 0;}", "e": 2513, "s": 1820, "text": null }, { "code": "// Java program for the above approachclass GFG{ // Function to multiply Complex// Numbers with just three// multiplicationsstatic void print_product(int a, int b, int c, int d){ // Find value of prod1, prod2 and prod3 int prod1 = a * c; int prod2 = b * d; int prod3 = (a + b) * (c + d); // Real Part int real = prod1 - prod2; // Imaginary Part int imag = prod3 - (prod1 + prod2); // Print the result System.out.println(real + \" + \" + imag + \"i\");} // Driver Codepublic static void main(String[] args){ // Given four numbers int a = 2; int b = 3; int c = 4; int d = 5; // Function call print_product(a, b, c, d);}} // This code is contributed by Pratima Pandey", "e": 3290, "s": 2513, "text": null }, { "code": "# Python3 program for the above approach # Function to multiply Complex# Numbers with just three# multiplicationsdef print_product(a, b, c, d): # Find value of prod1, prod2 # and prod3 prod1 = a * c prod2 = b * d prod3 = (a + b) * (c + d) # Real part real = prod1 - prod2 # Imaginary part imag = prod3 - (prod1 + prod2) # Print the result print(real, \" + \", imag, \"i\") # Driver code # Given four numbersa = 2b = 3c = 4d = 5 # Function callprint_product(a, b, c, d) # This code is contributed by Vishal Maurya.", "e": 3841, "s": 3290, "text": null }, { "code": "// C# program for the above approachusing System;class GFG{ // Function to multiply Complex// Numbers with just three// multiplicationsstatic void print_product(int a, int b, int c, int d){ // Find value of prod1, prod2 and prod3 int prod1 = a * c; int prod2 = b * d; int prod3 = (a + b) * (c + d); // Real Part int real = prod1 - prod2; // Imaginary Part int imag = prod3 - (prod1 + prod2); // Print the result Console.Write(real + \" + \" + imag + \"i\");} // Driver Codepublic static void Main(){ int a, b, c, d; // Given four Numbers a = 2; b = 3; c = 4; d = 5; // Function Call print_product(a, b, c, d);}} // This code is contributed by Code_Mech", "e": 4574, "s": 3841, "text": null }, { "code": "<script> // Javascript program for the above approach // Function to multiply Complex// Numbers with just three// multiplicationsfunction print_product( a, b, c, d){ // Find value of prod1, prod2 and prod3 let prod1 = a * c; let prod2 = b * d; let prod3 = (a + b) * (c + d); // Real Part let real = prod1 - prod2; // Imaginary Part let imag = prod3 - (prod1 + prod2); // Print the result document.write(real + \" + \" + imag + \"i\");} // Driver Code let a, b, c, d; // Given four Numbersa = 2;b = 3;c = 4;d = 5; // Function Callprint_product(a, b, c, d); </script>", "e": 5170, "s": 4574, "text": null }, { "code": null, "e": 5179, "s": 5170, "text": "-7 + 22i" }, { "code": null, "e": 5225, "s": 5181, "text": "Time Complexity: O(1) Auxiliary Space: O(1)" }, { "code": null, "e": 5235, "s": 5225, "text": "vishu2908" }, { "code": null, "e": 5245, "s": 5235, "text": "Code_Mech" }, { "code": null, "e": 5261, "s": 5245, "text": "dewantipandeydp" }, { "code": null, "e": 5275, "s": 5261, "text": "jana_sayantan" }, { "code": null, "e": 5285, "s": 5275, "text": "kk9826225" }, { "code": null, "e": 5293, "s": 5285, "text": "Numbers" }, { "code": null, "e": 5306, "s": 5293, "text": "Mathematical" }, { "code": null, "e": 5325, "s": 5306, "text": "School Programming" }, { "code": null, "e": 5338, "s": 5325, "text": "Mathematical" }, { "code": null, "e": 5346, "s": 5338, "text": "Numbers" }, { "code": null, "e": 5444, "s": 5346, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5476, "s": 5444, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 5522, "s": 5476, "text": "Merge two sorted arrays with O(1) extra space" }, { "code": null, "e": 5584, "s": 5522, "text": "Sum of the series (1*2) + (2*3) + (3*4) + ...... upto n terms" }, { "code": null, "e": 5628, "s": 5584, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 5670, "s": 5628, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 5688, "s": 5670, "text": "Python Dictionary" }, { "code": null, "e": 5713, "s": 5688, "text": "Reverse a string in Java" }, { "code": null, "e": 5729, "s": 5713, "text": "Arrays in C/C++" }, { "code": null, "e": 5752, "s": 5729, "text": "Introduction To PYTHON" } ]
Python Program to print element with maximum vowels from a List
08 Dec, 2020 Given a list containing string elements, the task is to write a Python program to print string with maximum vowels. Input : test_list = [“gfg”, “best”, “for”, “geeks”] Output : geeks Explanation : geeks has 2 e’s which is a maximum number of vowels compared to other strings. Input : test_list = [“gfg”, “best”] Output : best Explanation : best has 1 e which is a maximum number of vowels compared to other strings. Approach : Using loop In this, we iterate for all the strings and keep a counter to check number of vowel in each string. Then, return the string with maximum vowels at end of the loop. Python3 # initializing Matrixtest_list = ["gfg", "best", "for", "geeks"] # printing original listprint("The original list is : " + str(test_list)) res = ""max_len = 0for ele in test_list: # getting maximum length and element # iteratively vow_len = len([el for el in ele if el in ['a', 'e', 'o', 'u', 'i']]) if vow_len > max_len: max_len = vow_len res = ele # printing resultprint("Maximum vowels word : " + str(res)) Output: The original list is : [‘gfg’, ‘best’, ‘for’, ‘geeks’] Maximum vowels word : geeks Python list-programs Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Dec, 2020" }, { "code": null, "e": 144, "s": 28, "text": "Given a list containing string elements, the task is to write a Python program to print string with maximum vowels." }, { "code": null, "e": 304, "s": 144, "text": "Input : test_list = [“gfg”, “best”, “for”, “geeks”] Output : geeks Explanation : geeks has 2 e’s which is a maximum number of vowels compared to other strings." }, { "code": null, "e": 446, "s": 304, "text": "Input : test_list = [“gfg”, “best”] Output : best Explanation : best has 1 e which is a maximum number of vowels compared to other strings. " }, { "code": null, "e": 468, "s": 446, "text": "Approach : Using loop" }, { "code": null, "e": 632, "s": 468, "text": "In this, we iterate for all the strings and keep a counter to check number of vowel in each string. Then, return the string with maximum vowels at end of the loop." }, { "code": null, "e": 640, "s": 632, "text": "Python3" }, { "code": "# initializing Matrixtest_list = [\"gfg\", \"best\", \"for\", \"geeks\"] # printing original listprint(\"The original list is : \" + str(test_list)) res = \"\"max_len = 0for ele in test_list: # getting maximum length and element # iteratively vow_len = len([el for el in ele if el in ['a', 'e', 'o', 'u', 'i']]) if vow_len > max_len: max_len = vow_len res = ele # printing resultprint(\"Maximum vowels word : \" + str(res))", "e": 1081, "s": 640, "text": null }, { "code": null, "e": 1090, "s": 1081, "text": " Output:" }, { "code": null, "e": 1145, "s": 1090, "text": "The original list is : [‘gfg’, ‘best’, ‘for’, ‘geeks’]" }, { "code": null, "e": 1174, "s": 1145, "text": "Maximum vowels word : geeks " }, { "code": null, "e": 1195, "s": 1174, "text": "Python list-programs" }, { "code": null, "e": 1218, "s": 1195, "text": "Python string-programs" }, { "code": null, "e": 1225, "s": 1218, "text": "Python" }, { "code": null, "e": 1241, "s": 1225, "text": "Python Programs" } ]
Setting the Position of the Image in PDF Document using Java
17 Jun, 2021 To set the Position of the Image in a PDF document using Java multiple external dependencies need to download first. Setting the Position of the Image in a PDF, use the iText library. These are the steps that should be followed to Set the Position of the Image in a PDF using java. 1. Creating a PdfWriter object: The PdfWriter class represents the DocWriter for a PDF. The constructor of this class accepts a string, i.e. the path of the file where the PDF is to be created. 2. Creating a PdfDocument object: The PdfDocument class is the class that represents the PDF Document in iText, to instantiate this class in write mode, you need to pass an object of the class PdfWriter (i.e. pdfwriter from above code) to its constructor. 3. Creating the Document object: The Document class is the root element when creating a self-sufficient PDF. One of the constructors of this class accepts an object of the class PdfDocument (i.e. pdfdocument). 4. Create an Image object: We need the image object to manage the images. In order to create an image object, we need to create an ImageData object. We can create it bypassing the string parameter that represents the path of the image to create() method of the ImageDataFactory class. Now we can create an image object by passing the ImageData object, as a parameter to the constructor of the Image class.5. Setting the position of the image: We will use setFixedPosition() method of the Image to set the position of the image in a PDF document. We pass the desired coordinates of position to setFixedPosition() method. 6. Add image to the Pdf Document: Add the image object using the add() method of the Document class, and close the document using the close() method of the Document class.The following are dependencies required for executing the program: io-7.1.13.jar kernel-7.1.13.jar layout-7.1.13.jar Below is the implementation of the above approach: Java // Setting the Position of the Image// in PDF Document using Javaimport com.itextpdf.io.image.ImageData;import com.itextpdf.io.image.ImageDataFactory; import com.itextpdf.kernel.pdf.PdfDocument;import com.itextpdf.kernel.pdf.PdfWriter; import com.itextpdf.layout.Document;import com.itextpdf.layout.element.Image; public class SetImagePosition { public static void main(String args[]) throws Exception { try { // path where the pdf is to be created. String path = "F:/JavaPdf/setImagePosition.pdf"; PdfWriter pdfwriter = new PdfWriter(path); // Creating a PdfDocument object. // passing PdfWriter object constructor PdfDocument pdfdocument = new PdfDocument(pdfwriter); // Creating a Document and // passing pdfDocument object Document document = new Document(pdfdocument); // Create an ImageData object String imageFile = "F:/JavaPdf/image.png"; ImageData data = ImageDataFactory.create(imageFile); // Creating an Image object Image image = new Image(data); // Set the position of the image. image.setFixedPosition(200, 300); // Adding image to the document document.add(image); // Closing the document document.close(); System.out.println( "Image position set successfully in pdf"); } catch (Exception e) { System.out.println( "unable to set image position due to " + e); } }} Output: Image position set successfully in pdf PDF: adnanirshad158 Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Jun, 2021" }, { "code": null, "e": 310, "s": 28, "text": "To set the Position of the Image in a PDF document using Java multiple external dependencies need to download first. Setting the Position of the Image in a PDF, use the iText library. These are the steps that should be followed to Set the Position of the Image in a PDF using java." }, { "code": null, "e": 505, "s": 310, "text": "1. Creating a PdfWriter object: The PdfWriter class represents the DocWriter for a PDF. The constructor of this class accepts a string, i.e. the path of the file where the PDF is to be created. " }, { "code": null, "e": 762, "s": 505, "text": "2. Creating a PdfDocument object: The PdfDocument class is the class that represents the PDF Document in iText, to instantiate this class in write mode, you need to pass an object of the class PdfWriter (i.e. pdfwriter from above code) to its constructor. " }, { "code": null, "e": 973, "s": 762, "text": "3. Creating the Document object: The Document class is the root element when creating a self-sufficient PDF. One of the constructors of this class accepts an object of the class PdfDocument (i.e. pdfdocument). " }, { "code": null, "e": 1594, "s": 973, "text": "4. Create an Image object: We need the image object to manage the images. In order to create an image object, we need to create an ImageData object. We can create it bypassing the string parameter that represents the path of the image to create() method of the ImageDataFactory class. Now we can create an image object by passing the ImageData object, as a parameter to the constructor of the Image class.5. Setting the position of the image: We will use setFixedPosition() method of the Image to set the position of the image in a PDF document. We pass the desired coordinates of position to setFixedPosition() method. " }, { "code": null, "e": 1832, "s": 1594, "text": "6. Add image to the Pdf Document: Add the image object using the add() method of the Document class, and close the document using the close() method of the Document class.The following are dependencies required for executing the program:" }, { "code": null, "e": 1882, "s": 1832, "text": "io-7.1.13.jar\nkernel-7.1.13.jar\nlayout-7.1.13.jar" }, { "code": null, "e": 1933, "s": 1882, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1938, "s": 1933, "text": "Java" }, { "code": "// Setting the Position of the Image// in PDF Document using Javaimport com.itextpdf.io.image.ImageData;import com.itextpdf.io.image.ImageDataFactory; import com.itextpdf.kernel.pdf.PdfDocument;import com.itextpdf.kernel.pdf.PdfWriter; import com.itextpdf.layout.Document;import com.itextpdf.layout.element.Image; public class SetImagePosition { public static void main(String args[]) throws Exception { try { // path where the pdf is to be created. String path = \"F:/JavaPdf/setImagePosition.pdf\"; PdfWriter pdfwriter = new PdfWriter(path); // Creating a PdfDocument object. // passing PdfWriter object constructor PdfDocument pdfdocument = new PdfDocument(pdfwriter); // Creating a Document and // passing pdfDocument object Document document = new Document(pdfdocument); // Create an ImageData object String imageFile = \"F:/JavaPdf/image.png\"; ImageData data = ImageDataFactory.create(imageFile); // Creating an Image object Image image = new Image(data); // Set the position of the image. image.setFixedPosition(200, 300); // Adding image to the document document.add(image); // Closing the document document.close(); System.out.println( \"Image position set successfully in pdf\"); } catch (Exception e) { System.out.println( \"unable to set image position due to \" + e); } }}", "e": 3563, "s": 1938, "text": null }, { "code": null, "e": 3574, "s": 3566, "text": "Output:" }, { "code": null, "e": 3616, "s": 3576, "text": "Image position set successfully in pdf" }, { "code": null, "e": 3621, "s": 3616, "text": "PDF:" }, { "code": null, "e": 3640, "s": 3625, "text": "adnanirshad158" }, { "code": null, "e": 3645, "s": 3640, "text": "Java" }, { "code": null, "e": 3659, "s": 3645, "text": "Java Programs" }, { "code": null, "e": 3664, "s": 3659, "text": "Java" } ]
Scala | REPL
09 Apr, 2019 Scala REPL is an interactive command line interpreter shell, where REPL stands for Read-Evaluate-Print-Loop. It works like it stands for only. It first Read expression provided as input on Scala command line and then it Evaluate given expression and Print expression’s outcome on screen and then it is again ready to Read and this thing goes in loop. In the scope of the current expression as required, previous results are automatically imported. The REPL reads expressions at the prompt In interactive mode, then wraps them into an executable template, and after that compiles and executes the result. Either an object Or a class can be wrapped by user code the switch used is -Yrepl-class-based. Each and every line of input is compiled separately. The Dependencies on previous lines are included by automatically generated imports. The implicit import of scala.Predef can be controlled by inputting an explicit import. We can start Scala REPL by typing scala command in console/terminal. $scala Let’s understand how we can add two variable using Scala REPL.In first line we initialized two variable in Scala REPL. Then Scala REPL printed these. In this we can see that internally it create two variable of type Int with value. Then we executed expression of sum with defined two variable. with this Scala REPL printed sum of expression on screen again. Here it did not have any variable so it showed it with its temporary variable only with prefix res. We can use these variable as same like we created it. We can get more information of these temporary variable by calling getClass function over these variable like below. We can do lots of experiments like this with scala REPL on run time which would have been time consuming if we were using some IDE. With scala2.0 we can also list down all function suggestion that we can apply on variable by pressing TAB key. IMain of REPL is bound to $intp. The tab key is used for completion. lastException binds REPL’s last exception. :load is used to load a REPL input file. :javap is used to inspect class artifacts. -Yrepl-outdir is used to inspect class artifacts with external tools. :power imports compiler components after entering compiler mode. :help is used to get a list of commands to help the user. Picked Scala Scala-Basics Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Apr, 2019" }, { "code": null, "e": 632, "s": 28, "text": "Scala REPL is an interactive command line interpreter shell, where REPL stands for Read-Evaluate-Print-Loop. It works like it stands for only. It first Read expression provided as input on Scala command line and then it Evaluate given expression and Print expression’s outcome on screen and then it is again ready to Read and this thing goes in loop. In the scope of the current expression as required, previous results are automatically imported. The REPL reads expressions at the prompt In interactive mode, then wraps them into an executable template, and after that compiles and executes the result." }, { "code": null, "e": 727, "s": 632, "text": "Either an object Or a class can be wrapped by user code the switch used is -Yrepl-class-based." }, { "code": null, "e": 780, "s": 727, "text": "Each and every line of input is compiled separately." }, { "code": null, "e": 864, "s": 780, "text": "The Dependencies on previous lines are included by automatically generated imports." }, { "code": null, "e": 951, "s": 864, "text": "The implicit import of scala.Predef can be controlled by inputting an explicit import." }, { "code": null, "e": 1020, "s": 951, "text": "We can start Scala REPL by typing scala command in console/terminal." }, { "code": null, "e": 1027, "s": 1020, "text": "$scala" }, { "code": null, "e": 1539, "s": 1027, "text": "Let’s understand how we can add two variable using Scala REPL.In first line we initialized two variable in Scala REPL. Then Scala REPL printed these. In this we can see that internally it create two variable of type Int with value. Then we executed expression of sum with defined two variable. with this Scala REPL printed sum of expression on screen again. Here it did not have any variable so it showed it with its temporary variable only with prefix res. We can use these variable as same like we created it." }, { "code": null, "e": 1656, "s": 1539, "text": "We can get more information of these temporary variable by calling getClass function over these variable like below." }, { "code": null, "e": 1899, "s": 1656, "text": "We can do lots of experiments like this with scala REPL on run time which would have been time consuming if we were using some IDE. With scala2.0 we can also list down all function suggestion that we can apply on variable by pressing TAB key." }, { "code": null, "e": 1932, "s": 1899, "text": "IMain of REPL is bound to $intp." }, { "code": null, "e": 1968, "s": 1932, "text": "The tab key is used for completion." }, { "code": null, "e": 2011, "s": 1968, "text": "lastException binds REPL’s last exception." }, { "code": null, "e": 2052, "s": 2011, "text": ":load is used to load a REPL input file." }, { "code": null, "e": 2095, "s": 2052, "text": ":javap is used to inspect class artifacts." }, { "code": null, "e": 2165, "s": 2095, "text": "-Yrepl-outdir is used to inspect class artifacts with external tools." }, { "code": null, "e": 2230, "s": 2165, "text": ":power imports compiler components after entering compiler mode." }, { "code": null, "e": 2288, "s": 2230, "text": ":help is used to get a list of commands to help the user." }, { "code": null, "e": 2295, "s": 2288, "text": "Picked" }, { "code": null, "e": 2301, "s": 2295, "text": "Scala" }, { "code": null, "e": 2314, "s": 2301, "text": "Scala-Basics" }, { "code": null, "e": 2320, "s": 2314, "text": "Scala" } ]
Scheduling Python Scripts on Linux
31 Aug, 2021 Sometimes we need to do a task every day, and we can do these repetitive tasks every day by ourselves, or we can use the art of programming to automate these repetitive tasks by scheduling the task. And today in this article we are going to learn how to schedule a python script on Linux to do the repetitive tasks. We are going to a utility called cron to schedule the python script. Cron is driven by crontab which is also referred to as timetable because the word cron is derived from the Greek word Chronos which means time and tab is simply table. Syntax: * * * * * command In Crontab there are six fields. The first five are reserved for the date and time of scheduled execution, and the last field is reserved for a command to be executed. Python3 #!/usr/bin/env python3 # importing librariesimport osimport random # setting up folder namefolder_name = "geeksforgeeks" # entering into the loop# to create 2 folder every time this script runsfor i in range(2): # generating random number between 0 and 9 number = int(random.randrange(0, 10)) print("Creating folder {}".format(number)) # creating directories os.mkdir(folder_name+" {}".format(number)) Output: Now following are the steps we need to be followed to schedule python scripts in Linux: Step 1: Firstly, we have to create a python script that we will be going to schedule. Above is the python script that we are going to use in this article. Step 2: Open up the crontab to create a configuration file for scheduling the python script. Step 3: Run the following command in the terminal to open up the crontab configuration file. crontab -e This should open up an editor to edit the configuration file and the output should look like this: Step 4: Scroll to the end of the file and write down the timing and the command to be executed. * * * * * /usr/bin/env python3 /home/amninder/Desktop/Geeks/cron/schedule.py >> /home/amninder/Desktop/Geeks/cron/output.txt Here, “/usr/bin/env python3 /home/amninder/Desktop/Geeks/cron/schedule.py ” is the path to the script that we are going to schedule and “/home/amninder/Desktop/Geeks/cron/output.txt” is the path to the file where we are going to save our output. Asterisks (*) on all first 5 fields indicate that the script is going to execute after every minute, every hour. To check logs to see if It’s working or not run the following command: sudo tail -f /var/log/syslog Output: To remove the job from the crontab, run this command. crontab -r : This will delete the current cron jobs. Picked python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n31 Aug, 2021" }, { "code": null, "e": 344, "s": 28, "text": "Sometimes we need to do a task every day, and we can do these repetitive tasks every day by ourselves, or we can use the art of programming to automate these repetitive tasks by scheduling the task. And today in this article we are going to learn how to schedule a python script on Linux to do the repetitive tasks." }, { "code": null, "e": 581, "s": 344, "text": "We are going to a utility called cron to schedule the python script. Cron is driven by crontab which is also referred to as timetable because the word cron is derived from the Greek word Chronos which means time and tab is simply table." }, { "code": null, "e": 607, "s": 581, "text": "Syntax: * * * * * command" }, { "code": null, "e": 775, "s": 607, "text": "In Crontab there are six fields. The first five are reserved for the date and time of scheduled execution, and the last field is reserved for a command to be executed." }, { "code": null, "e": 783, "s": 775, "text": "Python3" }, { "code": "#!/usr/bin/env python3 # importing librariesimport osimport random # setting up folder namefolder_name = \"geeksforgeeks\" # entering into the loop# to create 2 folder every time this script runsfor i in range(2): # generating random number between 0 and 9 number = int(random.randrange(0, 10)) print(\"Creating folder {}\".format(number)) # creating directories os.mkdir(folder_name+\" {}\".format(number))", "e": 1209, "s": 783, "text": null }, { "code": null, "e": 1217, "s": 1209, "text": "Output:" }, { "code": null, "e": 1305, "s": 1217, "text": "Now following are the steps we need to be followed to schedule python scripts in Linux:" }, { "code": null, "e": 1461, "s": 1305, "text": "Step 1: Firstly, we have to create a python script that we will be going to schedule. Above is the python script that we are going to use in this article." }, { "code": null, "e": 1554, "s": 1461, "text": "Step 2: Open up the crontab to create a configuration file for scheduling the python script." }, { "code": null, "e": 1647, "s": 1554, "text": "Step 3: Run the following command in the terminal to open up the crontab configuration file." }, { "code": null, "e": 1658, "s": 1647, "text": "crontab -e" }, { "code": null, "e": 1757, "s": 1658, "text": "This should open up an editor to edit the configuration file and the output should look like this:" }, { "code": null, "e": 1853, "s": 1757, "text": "Step 4: Scroll to the end of the file and write down the timing and the command to be executed." }, { "code": null, "e": 1978, "s": 1853, "text": "* * * * * /usr/bin/env python3 /home/amninder/Desktop/Geeks/cron/schedule.py >> /home/amninder/Desktop/Geeks/cron/output.txt" }, { "code": null, "e": 2337, "s": 1978, "text": "Here, “/usr/bin/env python3 /home/amninder/Desktop/Geeks/cron/schedule.py ” is the path to the script that we are going to schedule and “/home/amninder/Desktop/Geeks/cron/output.txt” is the path to the file where we are going to save our output. Asterisks (*) on all first 5 fields indicate that the script is going to execute after every minute, every hour." }, { "code": null, "e": 2408, "s": 2337, "text": "To check logs to see if It’s working or not run the following command:" }, { "code": null, "e": 2437, "s": 2408, "text": "sudo tail -f /var/log/syslog" }, { "code": null, "e": 2445, "s": 2437, "text": "Output:" }, { "code": null, "e": 2499, "s": 2445, "text": "To remove the job from the crontab, run this command." }, { "code": null, "e": 2552, "s": 2499, "text": "crontab -r : This will delete the current cron jobs." }, { "code": null, "e": 2559, "s": 2552, "text": "Picked" }, { "code": null, "e": 2574, "s": 2559, "text": "python-utility" }, { "code": null, "e": 2581, "s": 2574, "text": "Python" } ]
Listview.builder in Flutter
17 Jun, 2022 ListView is a very important widget in a flutter. It is used to create the list of children But when we want to create a list recursively without writing code again and again then ListView.builder is used instead of ListView. ListView.builder creates a scrollable, linear array of widgets. ListView.builder by default does not support child reordering. ListView.builder({Key key, Axis scrollDirection, bool reverse, ScrollController controller, bool primary, ScrollPhysics physics, bool shrinkWrap, EdgeInsetsGeometry padding, double itemExtent, Widget Function(BuildContext, int) itemBuilder, int itemCount, bool addAutomaticKeepAlives, bool addRepaintBoundaries, bool addSemanticIndexes, double cacheExtent, int semanticChildCount, DragStartBehavior dragStartBehavior}) Let us understand this concept with the help of an example : Steps: Create a new flutter application. For now, delete the code from the main.dart. Copy the below code and paste it into your main.dart. Dart import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key);// This widget is the root// of your application. @override Widget build(BuildContext context) { return MaterialApp( title: "ListView.builder", theme: ThemeData(primarySwatch: Colors.green), debugShowCheckedModeBanner: false, // home : new ListViewBuilder(), NO Need To Use Unnecessary New Keyword home: const ListViewBuilder()); }} class ListViewBuilder extends StatelessWidget { const ListViewBuilder({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text("ListView.builder")), body: ListView.builder( itemCount: 5, itemBuilder: (BuildContext context, int index) { return ListTile( leading: const Icon(Icons.list), trailing: const Text( "GFG", style: TextStyle(color: Colors.green, fontSize: 15), ), title: Text("List item $index")); }), ); }} In the above code, we have ListViewBuilder class which is a stateless class. It returns a new Scaffold which consists of appBar and body. In the body, we have ListView.builder with itemcount 5 and itemBuilder which will create a new widget again and again up to 5 times because we have itemCount=5. If we don’t use itemCount in ListView.builder then we will get infinite list items so it is recommended to use itemCount to avoid such mistakes. The itemBuilder returns ListTile which has leading, trailing and title. This ListTile will build again and again up to 5 times. Output : This task can also be done with the help of ListView then why we used ListView.builder? The answer to this question is that we can do the same task with the help of ListView but when we have numerous items(for ex: 10000) then it is inefficient to create these items with ListView because it loads all the list items at once but ListView.builder make this task quicker by creating layouts for items visible on the screen with the help of itemBuilder & lazily build other layouts/containers as the user scrolls. Now, from the above code of ListView.builder, if we want to create a total of 8 items then simply change itemCount to 8, and we will get 8 items on our screen. Output: SahilSingh sweetyty ankit_kumar_ Flutter Dart Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flutter - Custom Bottom Navigation Bar Flutter - Checkbox Widget ListView Class in Flutter Flutter - Stack Widget Flutter - Search Bar Flutter - FutureBuilder Widget Flutter - Dialogs Operators in Dart Flutter - Flexible Widget Flutter - BoxShadow Widget
[ { "code": null, "e": 54, "s": 26, "text": "\n17 Jun, 2022" }, { "code": null, "e": 345, "s": 54, "text": "ListView is a very important widget in a flutter. It is used to create the list of children But when we want to create a list recursively without writing code again and again then ListView.builder is used instead of ListView. ListView.builder creates a scrollable, linear array of widgets." }, { "code": null, "e": 408, "s": 345, "text": "ListView.builder by default does not support child reordering." }, { "code": null, "e": 843, "s": 408, "text": "ListView.builder({Key key, \nAxis scrollDirection, \nbool reverse, \nScrollController controller, \nbool primary, \nScrollPhysics physics, \nbool shrinkWrap, \nEdgeInsetsGeometry padding, \ndouble itemExtent, \nWidget Function(BuildContext, int) itemBuilder, \nint itemCount, \nbool addAutomaticKeepAlives, \nbool addRepaintBoundaries, \nbool addSemanticIndexes, \ndouble cacheExtent, \nint semanticChildCount, \nDragStartBehavior dragStartBehavior})" }, { "code": null, "e": 904, "s": 843, "text": "Let us understand this concept with the help of an example :" }, { "code": null, "e": 911, "s": 904, "text": "Steps:" }, { "code": null, "e": 945, "s": 911, "text": "Create a new flutter application." }, { "code": null, "e": 990, "s": 945, "text": "For now, delete the code from the main.dart." }, { "code": null, "e": 1044, "s": 990, "text": "Copy the below code and paste it into your main.dart." }, { "code": null, "e": 1049, "s": 1044, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key);// This widget is the root// of your application. @override Widget build(BuildContext context) { return MaterialApp( title: \"ListView.builder\", theme: ThemeData(primarySwatch: Colors.green), debugShowCheckedModeBanner: false, // home : new ListViewBuilder(), NO Need To Use Unnecessary New Keyword home: const ListViewBuilder()); }} class ListViewBuilder extends StatelessWidget { const ListViewBuilder({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text(\"ListView.builder\")), body: ListView.builder( itemCount: 5, itemBuilder: (BuildContext context, int index) { return ListTile( leading: const Icon(Icons.list), trailing: const Text( \"GFG\", style: TextStyle(color: Colors.green, fontSize: 15), ), title: Text(\"List item $index\")); }), ); }}", "e": 2222, "s": 1049, "text": null }, { "code": null, "e": 2360, "s": 2222, "text": "In the above code, we have ListViewBuilder class which is a stateless class. It returns a new Scaffold which consists of appBar and body." }, { "code": null, "e": 2794, "s": 2360, "text": "In the body, we have ListView.builder with itemcount 5 and itemBuilder which will create a new widget again and again up to 5 times because we have itemCount=5. If we don’t use itemCount in ListView.builder then we will get infinite list items so it is recommended to use itemCount to avoid such mistakes. The itemBuilder returns ListTile which has leading, trailing and title. This ListTile will build again and again up to 5 times." }, { "code": null, "e": 2803, "s": 2794, "text": "Output :" }, { "code": null, "e": 2891, "s": 2803, "text": "This task can also be done with the help of ListView then why we used ListView.builder?" }, { "code": null, "e": 3314, "s": 2891, "text": "The answer to this question is that we can do the same task with the help of ListView but when we have numerous items(for ex: 10000) then it is inefficient to create these items with ListView because it loads all the list items at once but ListView.builder make this task quicker by creating layouts for items visible on the screen with the help of itemBuilder & lazily build other layouts/containers as the user scrolls." }, { "code": null, "e": 3474, "s": 3314, "text": "Now, from the above code of ListView.builder, if we want to create a total of 8 items then simply change itemCount to 8, and we will get 8 items on our screen." }, { "code": null, "e": 3483, "s": 3474, "text": "Output: " }, { "code": null, "e": 3494, "s": 3483, "text": "SahilSingh" }, { "code": null, "e": 3503, "s": 3494, "text": "sweetyty" }, { "code": null, "e": 3516, "s": 3503, "text": "ankit_kumar_" }, { "code": null, "e": 3524, "s": 3516, "text": "Flutter" }, { "code": null, "e": 3529, "s": 3524, "text": "Dart" }, { "code": null, "e": 3627, "s": 3529, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3666, "s": 3627, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 3692, "s": 3666, "text": "Flutter - Checkbox Widget" }, { "code": null, "e": 3718, "s": 3692, "text": "ListView Class in Flutter" }, { "code": null, "e": 3741, "s": 3718, "text": "Flutter - Stack Widget" }, { "code": null, "e": 3762, "s": 3741, "text": "Flutter - Search Bar" }, { "code": null, "e": 3793, "s": 3762, "text": "Flutter - FutureBuilder Widget" }, { "code": null, "e": 3811, "s": 3793, "text": "Flutter - Dialogs" }, { "code": null, "e": 3829, "s": 3811, "text": "Operators in Dart" }, { "code": null, "e": 3855, "s": 3829, "text": "Flutter - Flexible Widget" } ]
How to display HTML tags as plain text using PHP
28 Nov, 2018 HTML tags begin with the less-than character and end with greater-than character, the text inside the tag formatted and presented according to the tag used. Every tag has special meaning to the browser but there are cases when to show plain HTML code in webpage.There are various methods in PHP to show the HTML tags as plain text, some of them are discussed below:Method 1: Using htmlspecialchars() function: The htmlspecialchars() function is an inbuilt function in PHP which is used to convert all predefined characters to HTML entities. Syntax: string htmlspecialchars( $string, $flags, $encoding, $double_encode ) $string: This parameter is used to hold the input string. $flags: This parameter is used to hold the flags. It is combination of one or two flags, which tells how to handle quotes. $encoding: It is an optional argument which specifies the encoding which is used when characters are converted. If encoding is not given then it is converted according to PHP default version. $double_encode: If double_encode is turned off then PHP will not encode existing HTML entities. The default is to convert everything. Return Values: This function returns the converted string. If there is invalid input string then empty string will returned. Example: <?php echo("<b>without using htmlspecialchars() function</b><br>"); $myVar = htmlspecialchars("<b>using htmlspecialchars() function</b>", ENT_QUOTES);echo($myVar);?> Output: Method 2: Using htmlentities() function: The htmlentities() function is an inbuilt function in PHP which is used to transform all characters which are applicable to HTML entities. This function converts all characters that are applicable to HTML entity. Syntax: string htmlentities( $string, $flags, $encoding, $double_encode ) Parameters: This function accepts four parameters as mentioned above and described below: $string: This parameter is used to hold the input string. $flags: This parameter is used to hold the flags. It is combination of one or two flags, which tells how to handle quotes. encoding: It is an optional argument which specifies the encoding which is used when characters are converted. If encoding is not given then it is converted according to PHP default version. $double_encode: If double_encode is turned off then PHP will not encode existing HTML entities. The default is to convert everything. Return Values: This function returns the string which has been encoded. Example: <?php$str = "<b>GeeksforGeeks</b>";echo("without using htmlentities() function = ".$str."<br>"); $myVar = htmlentities($str, ENT_QUOTES);echo("with using htmlentities() function = ".$myVar); ?> Output: Method 3: This method is used to replace the character by set of characters to get the desired output. In this method, < is replaced by &lt; and > is replaced by &gt;. Example: <?php$str = "<b>GeeksforGeeks</b>";echo("without using & lt; and & gt; = ".$str."<br>"); $myVar = "<b>GeeksforGeeks</b>";echo("with using & lt; and & gt; = ".$myVar); ?> Output: Picked PHP PHP Programs 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": "\n28 Nov, 2018" }, { "code": null, "e": 569, "s": 28, "text": "HTML tags begin with the less-than character and end with greater-than character, the text inside the tag formatted and presented according to the tag used. Every tag has special meaning to the browser but there are cases when to show plain HTML code in webpage.There are various methods in PHP to show the HTML tags as plain text, some of them are discussed below:Method 1: Using htmlspecialchars() function: The htmlspecialchars() function is an inbuilt function in PHP which is used to convert all predefined characters to HTML entities." }, { "code": null, "e": 577, "s": 569, "text": "Syntax:" }, { "code": null, "e": 647, "s": 577, "text": "string htmlspecialchars( $string, $flags, $encoding, $double_encode )" }, { "code": null, "e": 705, "s": 647, "text": "$string: This parameter is used to hold the input string." }, { "code": null, "e": 828, "s": 705, "text": "$flags: This parameter is used to hold the flags. It is combination of one or two flags, which tells how to handle quotes." }, { "code": null, "e": 1020, "s": 828, "text": "$encoding: It is an optional argument which specifies the encoding which is used when characters are converted. If encoding is not given then it is converted according to PHP default version." }, { "code": null, "e": 1154, "s": 1020, "text": "$double_encode: If double_encode is turned off then PHP will not encode existing HTML entities. The default is to convert everything." }, { "code": null, "e": 1279, "s": 1154, "text": "Return Values: This function returns the converted string. If there is invalid input string then empty string will returned." }, { "code": null, "e": 1288, "s": 1279, "text": "Example:" }, { "code": "<?php echo(\"<b>without using htmlspecialchars() function</b><br>\"); $myVar = htmlspecialchars(\"<b>using htmlspecialchars() function</b>\", ENT_QUOTES);echo($myVar);?>", "e": 1485, "s": 1288, "text": null }, { "code": null, "e": 1493, "s": 1485, "text": "Output:" }, { "code": null, "e": 1747, "s": 1493, "text": "Method 2: Using htmlentities() function: The htmlentities() function is an inbuilt function in PHP which is used to transform all characters which are applicable to HTML entities. This function converts all characters that are applicable to HTML entity." }, { "code": null, "e": 1755, "s": 1747, "text": "Syntax:" }, { "code": null, "e": 1821, "s": 1755, "text": "string htmlentities( $string, $flags, $encoding, $double_encode )" }, { "code": null, "e": 1911, "s": 1821, "text": "Parameters: This function accepts four parameters as mentioned above and described below:" }, { "code": null, "e": 1969, "s": 1911, "text": "$string: This parameter is used to hold the input string." }, { "code": null, "e": 2092, "s": 1969, "text": "$flags: This parameter is used to hold the flags. It is combination of one or two flags, which tells how to handle quotes." }, { "code": null, "e": 2283, "s": 2092, "text": "encoding: It is an optional argument which specifies the encoding which is used when characters are converted. If encoding is not given then it is converted according to PHP default version." }, { "code": null, "e": 2417, "s": 2283, "text": "$double_encode: If double_encode is turned off then PHP will not encode existing HTML entities. The default is to convert everything." }, { "code": null, "e": 2489, "s": 2417, "text": "Return Values: This function returns the string which has been encoded." }, { "code": null, "e": 2498, "s": 2489, "text": "Example:" }, { "code": "<?php$str = \"<b>GeeksforGeeks</b>\";echo(\"without using htmlentities() function = \".$str.\"<br>\"); $myVar = htmlentities($str, ENT_QUOTES);echo(\"with using htmlentities() function = \".$myVar); ?>", "e": 2694, "s": 2498, "text": null }, { "code": null, "e": 2702, "s": 2694, "text": "Output:" }, { "code": null, "e": 2870, "s": 2702, "text": "Method 3: This method is used to replace the character by set of characters to get the desired output. In this method, < is replaced by &lt; and > is replaced by &gt;." }, { "code": null, "e": 2879, "s": 2870, "text": "Example:" }, { "code": "<?php$str = \"<b>GeeksforGeeks</b>\";echo(\"without using & lt; and & gt; = \".$str.\"<br>\"); $myVar = \"<b>GeeksforGeeks</b>\";echo(\"with using & lt; and & gt; = \".$myVar); ?>", "e": 3051, "s": 2879, "text": null }, { "code": null, "e": 3059, "s": 3051, "text": "Output:" }, { "code": null, "e": 3066, "s": 3059, "text": "Picked" }, { "code": null, "e": 3070, "s": 3066, "text": "PHP" }, { "code": null, "e": 3083, "s": 3070, "text": "PHP Programs" }, { "code": null, "e": 3100, "s": 3083, "text": "Web Technologies" }, { "code": null, "e": 3104, "s": 3100, "text": "PHP" } ]
Data Structures | Stack | Question 4
09 Feb, 2013 Consider the following pseudocode that uses a stack declare a stack of characterswhile ( there are more characters in the word to read ){ read a character push the character on the stack}while ( the stack is not empty ){ pop a character off the stack write the character to the screen} What is output for input “geeksquiz”? (A) geeksquizgeeksquiz(B) ziuqskeeg(C) geeksquiz(D) ziuqskeegziuqskeegAnswer: (B)Explanation: Since the stack data structure follows LIFO order. When we pop() items from stack, they are popped in reverse order of their insertion (or push()) Data Structures Data Structures-Stack Data Structures Data Structures Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n09 Feb, 2013" }, { "code": null, "e": 105, "s": 53, "text": "Consider the following pseudocode that uses a stack" }, { "code": "declare a stack of characterswhile ( there are more characters in the word to read ){ read a character push the character on the stack}while ( the stack is not empty ){ pop a character off the stack write the character to the screen}", "e": 347, "s": 105, "text": null }, { "code": null, "e": 385, "s": 347, "text": "What is output for input “geeksquiz”?" }, { "code": null, "e": 626, "s": 385, "text": "(A) geeksquizgeeksquiz(B) ziuqskeeg(C) geeksquiz(D) ziuqskeegziuqskeegAnswer: (B)Explanation: Since the stack data structure follows LIFO order. When we pop() items from stack, they are popped in reverse order of their insertion (or push())" }, { "code": null, "e": 642, "s": 626, "text": "Data Structures" }, { "code": null, "e": 664, "s": 642, "text": "Data Structures-Stack" }, { "code": null, "e": 680, "s": 664, "text": "Data Structures" }, { "code": null, "e": 696, "s": 680, "text": "Data Structures" } ]
Python | os.getuid() and os.setuid() method
25 Jun, 2019 OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. All functions in os module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type, but are not accepted by the operating system. os.getuid() method in Python is used to get the current process’s real user id while os.setuid() method is used to set the current process’s real user id. User ID: In Unix-like operating systems, a user is identified by a unique value called user ID. User ID is used to determine which system resource a user is authorized to access. Note: os.setuid() and os.getuid() methods are available only on UNIX platforms and functionality of os.setuid() method is typically available only to the superuser as only superuser can change user id.Superuser means a root user or an administrative user who has all the permissions to run or execute any program in the operating system. os.getuid() method Syntax: os.getuid() Parameter: No parameter is required Return Type: This method returns an integer value which represents the current process’s real user id. # Python program to explain os.getuid() method # importing os module import os # Get the real user ID# of the current process# using os.getuid() methoduid = os.getuid() # Print the real user ID# of the current processprint("Real user ID of the current process:", uid) Real user ID of the current process: 1000 os.setuid() method Syntax: os.setuid(uid) Parameter:uid: An integer value representing new user ID for the current process. Return Type: This method does not return any value. # Python program to explain os.setuid() method # importing os module import os # Get the real user ID# of the current process# using os.getuid() methoduid = os.getuid() # Print the real user ID# of the current processprint("Real user ID of the current process:", uid) # Set real user ID# of the current process# using os.setuid() methoduid = 1500os.setuid(uid)print("Real user ID changed") # Print the real user ID# of the current processprint("Real user ID of the current process:", os.getuid()) Real user ID of the current process: 0 Real user ID changed Real user ID of the current process: 1500 python-os-module Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Jun, 2019" }, { "code": null, "e": 247, "s": 28, "text": "OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality." }, { "code": null, "e": 442, "s": 247, "text": "All functions in os module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type, but are not accepted by the operating system." }, { "code": null, "e": 597, "s": 442, "text": "os.getuid() method in Python is used to get the current process’s real user id while os.setuid() method is used to set the current process’s real user id." }, { "code": null, "e": 776, "s": 597, "text": "User ID: In Unix-like operating systems, a user is identified by a unique value called user ID. User ID is used to determine which system resource a user is authorized to access." }, { "code": null, "e": 1114, "s": 776, "text": "Note: os.setuid() and os.getuid() methods are available only on UNIX platforms and functionality of os.setuid() method is typically available only to the superuser as only superuser can change user id.Superuser means a root user or an administrative user who has all the permissions to run or execute any program in the operating system." }, { "code": null, "e": 1133, "s": 1114, "text": "os.getuid() method" }, { "code": null, "e": 1153, "s": 1133, "text": "Syntax: os.getuid()" }, { "code": null, "e": 1189, "s": 1153, "text": "Parameter: No parameter is required" }, { "code": null, "e": 1292, "s": 1189, "text": "Return Type: This method returns an integer value which represents the current process’s real user id." }, { "code": "# Python program to explain os.getuid() method # importing os module import os # Get the real user ID# of the current process# using os.getuid() methoduid = os.getuid() # Print the real user ID# of the current processprint(\"Real user ID of the current process:\", uid)", "e": 1564, "s": 1292, "text": null }, { "code": null, "e": 1607, "s": 1564, "text": "Real user ID of the current process: 1000\n" }, { "code": null, "e": 1626, "s": 1607, "text": "os.setuid() method" }, { "code": null, "e": 1649, "s": 1626, "text": "Syntax: os.setuid(uid)" }, { "code": null, "e": 1731, "s": 1649, "text": "Parameter:uid: An integer value representing new user ID for the current process." }, { "code": null, "e": 1783, "s": 1731, "text": "Return Type: This method does not return any value." }, { "code": "# Python program to explain os.setuid() method # importing os module import os # Get the real user ID# of the current process# using os.getuid() methoduid = os.getuid() # Print the real user ID# of the current processprint(\"Real user ID of the current process:\", uid) # Set real user ID# of the current process# using os.setuid() methoduid = 1500os.setuid(uid)print(\"Real user ID changed\") # Print the real user ID# of the current processprint(\"Real user ID of the current process:\", os.getuid())", "e": 2288, "s": 1783, "text": null }, { "code": null, "e": 2391, "s": 2288, "text": "Real user ID of the current process: 0\nReal user ID changed\nReal user ID of the current process: 1500\n" }, { "code": null, "e": 2408, "s": 2391, "text": "python-os-module" }, { "code": null, "e": 2415, "s": 2408, "text": "Python" } ]
Convert CSV to HTML Table in Python
01 Jun, 2021 CSV file is a Comma Separated Value file that uses a comma to separate values. It is basically used for exchanging data between different applications. In this, individual rows are separated by a newline. Fields of data in each row are delimited with a comma.Example : Name, Salary, Age, No.of years employed Akriti, 90000, 20, 1 Shreya, 100000, 21, 2 Priyanka, 25000, 45, 7 Neha, 46000, 25, 4 Note: For more information, refer to Working with csv files in Python Method 1 Using pandas: One of the easiest way to convert CSV file to HTML table is using pandas. Type the below code in the command prompt to install pandas. pip install pandas Example: Suppose the CSV file looks like this – Python3 # Python program to convert# CSV to HTML Table import pandas as pd # to read csv file named "samplee"a = pd.read_csv("read_file.csv") # to save as html file# named as "Table"a.to_html("Table.htm") # assign it to a# variable (string)html_file = a.to_html() Output: Method 2 Using PrettyTable: PrettyTable is a simple Python library designed to make it quick and easy to represent tabular data in visually appealing ASCII tables. Type the below command to install this module. pip install PrettyTable Example: The above CSV file is used. Python3 from prettytable import PrettyTable # open csv filea = open("read_file.csv", 'r') # read the csv filea = a.readlines() # Separating the Headersl1 = a[0]l1 = l1.split(',') # headers for tablet = PrettyTable([l1[0], l1[1]]) # Adding the datafor i in range(1, len(a)) : t.add_row(a[i].split(',')) code = t.get_html_string()html_file = open('Tablee.html', 'w')html_file = html_file.write(code) Output : saurabh1990aror Python-pandas python-utility Technical Scripter 2019 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n01 Jun, 2021" }, { "code": null, "e": 325, "s": 54, "text": "CSV file is a Comma Separated Value file that uses a comma to separate values. It is basically used for exchanging data between different applications. In this, individual rows are separated by a newline. Fields of data in each row are delimited with a comma.Example : " }, { "code": null, "e": 450, "s": 325, "text": "Name, Salary, Age, No.of years employed\nAkriti, 90000, 20, 1\nShreya, 100000, 21, 2\nPriyanka, 25000, 45, 7\nNeha, 46000, 25, 4" }, { "code": null, "e": 521, "s": 450, "text": "Note: For more information, refer to Working with csv files in Python " }, { "code": null, "e": 680, "s": 521, "text": "Method 1 Using pandas: One of the easiest way to convert CSV file to HTML table is using pandas. Type the below code in the command prompt to install pandas. " }, { "code": null, "e": 700, "s": 680, "text": "pip install pandas " }, { "code": null, "e": 750, "s": 700, "text": "Example: Suppose the CSV file looks like this – " }, { "code": null, "e": 760, "s": 752, "text": "Python3" }, { "code": "# Python program to convert# CSV to HTML Table import pandas as pd # to read csv file named \"samplee\"a = pd.read_csv(\"read_file.csv\") # to save as html file# named as \"Table\"a.to_html(\"Table.htm\") # assign it to a# variable (string)html_file = a.to_html()", "e": 1017, "s": 760, "text": null }, { "code": null, "e": 1026, "s": 1017, "text": "Output: " }, { "code": null, "e": 1238, "s": 1026, "text": "Method 2 Using PrettyTable: PrettyTable is a simple Python library designed to make it quick and easy to represent tabular data in visually appealing ASCII tables. Type the below command to install this module. " }, { "code": null, "e": 1262, "s": 1238, "text": "pip install PrettyTable" }, { "code": null, "e": 1300, "s": 1262, "text": "Example: The above CSV file is used. " }, { "code": null, "e": 1308, "s": 1300, "text": "Python3" }, { "code": "from prettytable import PrettyTable # open csv filea = open(\"read_file.csv\", 'r') # read the csv filea = a.readlines() # Separating the Headersl1 = a[0]l1 = l1.split(',') # headers for tablet = PrettyTable([l1[0], l1[1]]) # Adding the datafor i in range(1, len(a)) : t.add_row(a[i].split(',')) code = t.get_html_string()html_file = open('Tablee.html', 'w')html_file = html_file.write(code)", "e": 1702, "s": 1308, "text": null }, { "code": null, "e": 1713, "s": 1702, "text": "Output : " }, { "code": null, "e": 1731, "s": 1715, "text": "saurabh1990aror" }, { "code": null, "e": 1745, "s": 1731, "text": "Python-pandas" }, { "code": null, "e": 1760, "s": 1745, "text": "python-utility" }, { "code": null, "e": 1784, "s": 1760, "text": "Technical Scripter 2019" }, { "code": null, "e": 1791, "s": 1784, "text": "Python" }, { "code": null, "e": 1810, "s": 1791, "text": "Technical Scripter" } ]
How to convert PDF file to Excel file using Python?
28 Jan, 2021 In this article, we will see how to convert a PDF to Excel or CSV File Using Python. It can be done with various methods, here are we are going to use some methods. Method 1: Using pdftables_api Here will use the pdftables_api Module for converting the PDF file into any other format. It’s a simple web-based API, so can be called from any programming language. Installation: pip install git+https://github.com/pdftables/python-pdftables-api.git After Installation, you need an API KEY. Go to PDFTables.com and signup, then visit the API Page to see your API KEY. For Converting PDF File Into excel File we will use xml() method. Syntax: xml(pdf_path, xml_path) Below is the Implementation: PDF File Used: PDF FILE Python3 # Import Moduleimport pdftables_api # API KEY VERIFICATIONconversion = pdftables_api.Client('API KEY') # PDf to Excel # (Hello.pdf, Hello)conversion.xlsx("pdf_file_path", "output_file_path") Output: EXCEL FILE Method 2: Using tabula-py Here will use the tabula-py Module for converting the PDF file into any other format. Installation: pip install tabula-py Before we start, first we need to install java and add a java installation folder to the PATH variable. Install java click here Add java installation folder (C:\Program Files (x86)\Java\jre1.8.0_251\bin) to the environment path variable Approach: Read PDF file using read_pdf() method. Then we will convert the PDF files into an Excel file using the to_excel() method. Syntax: read_pdf(PDF File Path, pages = Number of pages, **agrs) Below is the Implementation: PDF File Used: PDF FILE Python3 # Import Module import tabula # Read PDF File# this contain a listdf = tabula.read_pdf("PDF File Path", pages = 1)[0] # Convert into Excel Filedf.to_excel('Excel File Path') Output: EXCEL FILE Picked Python-excel python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Jan, 2021" }, { "code": null, "e": 217, "s": 52, "text": "In this article, we will see how to convert a PDF to Excel or CSV File Using Python. It can be done with various methods, here are we are going to use some methods." }, { "code": null, "e": 248, "s": 217, "text": "Method 1: Using pdftables_api " }, { "code": null, "e": 415, "s": 248, "text": "Here will use the pdftables_api Module for converting the PDF file into any other format. It’s a simple web-based API, so can be called from any programming language." }, { "code": null, "e": 429, "s": 415, "text": "Installation:" }, { "code": null, "e": 499, "s": 429, "text": "pip install git+https://github.com/pdftables/python-pdftables-api.git" }, { "code": null, "e": 617, "s": 499, "text": "After Installation, you need an API KEY. Go to PDFTables.com and signup, then visit the API Page to see your API KEY." }, { "code": null, "e": 683, "s": 617, "text": "For Converting PDF File Into excel File we will use xml() method." }, { "code": null, "e": 691, "s": 683, "text": "Syntax:" }, { "code": null, "e": 715, "s": 691, "text": "xml(pdf_path, xml_path)" }, { "code": null, "e": 744, "s": 715, "text": "Below is the Implementation:" }, { "code": null, "e": 759, "s": 744, "text": "PDF File Used:" }, { "code": null, "e": 768, "s": 759, "text": "PDF FILE" }, { "code": null, "e": 776, "s": 768, "text": "Python3" }, { "code": "# Import Moduleimport pdftables_api # API KEY VERIFICATIONconversion = pdftables_api.Client('API KEY') # PDf to Excel # (Hello.pdf, Hello)conversion.xlsx(\"pdf_file_path\", \"output_file_path\")", "e": 969, "s": 776, "text": null }, { "code": null, "e": 977, "s": 969, "text": "Output:" }, { "code": null, "e": 988, "s": 977, "text": "EXCEL FILE" }, { "code": null, "e": 1014, "s": 988, "text": "Method 2: Using tabula-py" }, { "code": null, "e": 1100, "s": 1014, "text": "Here will use the tabula-py Module for converting the PDF file into any other format." }, { "code": null, "e": 1114, "s": 1100, "text": "Installation:" }, { "code": null, "e": 1136, "s": 1114, "text": "pip install tabula-py" }, { "code": null, "e": 1240, "s": 1136, "text": "Before we start, first we need to install java and add a java installation folder to the PATH variable." }, { "code": null, "e": 1264, "s": 1240, "text": "Install java click here" }, { "code": null, "e": 1373, "s": 1264, "text": "Add java installation folder (C:\\Program Files (x86)\\Java\\jre1.8.0_251\\bin) to the environment path variable" }, { "code": null, "e": 1383, "s": 1373, "text": "Approach:" }, { "code": null, "e": 1422, "s": 1383, "text": "Read PDF file using read_pdf() method." }, { "code": null, "e": 1505, "s": 1422, "text": "Then we will convert the PDF files into an Excel file using the to_excel() method." }, { "code": null, "e": 1513, "s": 1505, "text": "Syntax:" }, { "code": null, "e": 1570, "s": 1513, "text": "read_pdf(PDF File Path, pages = Number of pages, **agrs)" }, { "code": null, "e": 1599, "s": 1570, "text": "Below is the Implementation:" }, { "code": null, "e": 1614, "s": 1599, "text": "PDF File Used:" }, { "code": null, "e": 1623, "s": 1614, "text": "PDF FILE" }, { "code": null, "e": 1631, "s": 1623, "text": "Python3" }, { "code": "# Import Module import tabula # Read PDF File# this contain a listdf = tabula.read_pdf(\"PDF File Path\", pages = 1)[0] # Convert into Excel Filedf.to_excel('Excel File Path')", "e": 1807, "s": 1631, "text": null }, { "code": null, "e": 1815, "s": 1807, "text": "Output:" }, { "code": null, "e": 1826, "s": 1815, "text": "EXCEL FILE" }, { "code": null, "e": 1833, "s": 1826, "text": "Picked" }, { "code": null, "e": 1846, "s": 1833, "text": "Python-excel" }, { "code": null, "e": 1861, "s": 1846, "text": "python-utility" }, { "code": null, "e": 1868, "s": 1861, "text": "Python" } ]
\varsigma - Tex Command
\varsigma - Used to create varsigma symbol. { \varsigma} \varsigma command draws varsigma symbol. \varsigma ς \varsigma ς \varsigma 14 Lectures 52 mins Ashraf Said 11 Lectures 1 hours Ashraf Said 9 Lectures 1 hours Emenwa Global, Ejike IfeanyiChukwu 29 Lectures 2.5 hours Mohammad Nauman 14 Lectures 1 hours Daniel Stern 15 Lectures 47 mins Nishant Kumar Print Add Notes Bookmark this page
[ { "code": null, "e": 8030, "s": 7986, "text": "\\varsigma - Used to create varsigma symbol." }, { "code": null, "e": 8043, "s": 8030, "text": "{ \\varsigma}" }, { "code": null, "e": 8084, "s": 8043, "text": "\\varsigma command draws varsigma symbol." }, { "code": null, "e": 8101, "s": 8084, "text": "\n\\varsigma\n\nς\n\n\n" }, { "code": null, "e": 8116, "s": 8101, "text": "\\varsigma\n\nς\n\n" }, { "code": null, "e": 8126, "s": 8116, "text": "\\varsigma" }, { "code": null, "e": 8158, "s": 8126, "text": "\n 14 Lectures \n 52 mins\n" }, { "code": null, "e": 8171, "s": 8158, "text": " Ashraf Said" }, { "code": null, "e": 8204, "s": 8171, "text": "\n 11 Lectures \n 1 hours \n" }, { "code": null, "e": 8217, "s": 8204, "text": " Ashraf Said" }, { "code": null, "e": 8249, "s": 8217, "text": "\n 9 Lectures \n 1 hours \n" }, { "code": null, "e": 8285, "s": 8249, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 8320, "s": 8285, "text": "\n 29 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8337, "s": 8320, "text": " Mohammad Nauman" }, { "code": null, "e": 8370, "s": 8337, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 8384, "s": 8370, "text": " Daniel Stern" }, { "code": null, "e": 8416, "s": 8384, "text": "\n 15 Lectures \n 47 mins\n" }, { "code": null, "e": 8431, "s": 8416, "text": " Nishant Kumar" }, { "code": null, "e": 8438, "s": 8431, "text": " Print" }, { "code": null, "e": 8449, "s": 8438, "text": " Add Notes" } ]
How to Create a Single Legend for All Subplots in Matplotlib?
23 Dec, 2020 The subplot() function in matplotlib helps to create a grid of subplots within a single figure. In a figure, subplots are created and ordered row-wise from the top left. A legend in the Matplotlib library basically describes the graph elements. The legend() can be customized and adjusted anywhere inside or outside the graph by placing it at various positions. Sometimes it is necessary to create a single legend for all subplots. Below are the examples that show a single legend for all subplots. Syntax of Subplot(): subplot(nrows,ncols,nsubplot) For example, subplot(2,1,1) is the figure which represents the first subplot with 2 rows and one column, the first subplot lies in the first row. The subplot(2,1,2) represents the second subplot which lies in the second row in the first column. The legend command Syntax: legend(*args, **kwargs) If the length of arguments i.e, args is 0 in the legend command then it automatically generates the legend from label properties by calling get_legend_handles_labels() method. For example, ax.legend() is equivalent to: handles, labels = ax.get_legend_handles_labels() ax.legend(handles, labels) The get_legend_handles_labels() method returns a tuple of two lists, i.e., list of artists and list of labels. Example 1: Python3 # Importing required librariesimport matplotlib.pyplot as pltimport numpy as np # 2 subplots in 1 row and 2 columnsfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5)) x1 = ['Telugu', 'Hindi', 'English', 'Maths', 'Science', 'Social']y1 = [45, 34, 30, 45, 50, 38]y2 = [36, 28, 30, 45, 38, 48] # Labels to use in the legend for each linelabels = ["in 2019", "in 2020"] # Title for subplotsfig.suptitle('Number of Students passed in each subject\from a class in 2019 & 2020', fontsize=20) # Creating the sub-plots.l1 = ax1.plot(x1, y1, color="green")l2 = ax2.plot(x1, y2, color="blue") ax1.set_yticks(np.arange(0, 51, 5))ax2.set_yticks(np.arange(0, 51, 5)) ax1.set_ylabel('Number of students', fontsize=25) fig.legend([l1, l2], labels=labels, loc="upper right") # Adjusting the sub-plotsplt.subplots_adjust(right=0.9) plt.show() Output: Example 2: Python3 # Plotting sub-plots of number of # students passed in each subject # in academic year 2017-20.import matplotlib.pyplot as pltimport numpy as np plt.style.use('seaborn') # Plot Styles fig = plt.figure() # 4 subplots in 2 rows and 2 columns in a figureaxes = fig.subplots(nrows=2, ncols=2) axes[0, 0].bar(['Telugu', 'Hindi', 'English', 'Maths', 'Science', 'Social'], [50, 27, 42, 34, 45, 48], color='g', label="Students passed in 2017") axes[0, 0].set_yticks(np.arange(0, 51, 5)) axes[0, 1].bar(['Telugu', 'Hindi', 'English', 'Maths', 'Science', 'Social'], [50, 27, 42, 34, 45, 48], color='y', label="Students passed in 2018") axes[0, 1].set_yticks(np.arange(0, 51, 5)) axes[1, 0].bar(['Telugu', 'Hindi', 'English', 'Maths', 'Science', 'Social'], [40, 27, 22, 44, 35, 38], color='r', label="Students passed in 2019") axes[1, 0].set_yticks(np.arange(0, 51, 5))axes[1, 0].set_xlabel('Subjects', fontsize=25) # rotating third sub-plot x-axis labelsfor tick in axes[1, 0].get_xticklabels(): tick.set_rotation(45) axes[1, 0].set_ylabel(" Number of Students passed in 2017-2020", fontsize=20) axes[1, 1].bar(['Telugu', 'Hindi', 'English', 'Maths', 'Science', 'Social'], [40, 27, 32, 44, 45, 48], color='b', label="Students passed in 2020") axes[1, 1].set_xlabel('Subjects', fontsize=20)axes[1, 1].set_yticks(np.arange(0, 51, 5)) lines = []labels = [] for ax in fig.axes: Line, Label = ax.get_legend_handles_labels() # print(Label) lines.extend(Line) labels.extend(Label) # rotating x-axis labels of last sub-plotplt.xticks(rotation=45) fig.legend(lines, labels, loc='upper right') plt.show() Output : Python-matplotlib Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Dec, 2020" }, { "code": null, "e": 551, "s": 52, "text": "The subplot() function in matplotlib helps to create a grid of subplots within a single figure. In a figure, subplots are created and ordered row-wise from the top left. A legend in the Matplotlib library basically describes the graph elements. The legend() can be customized and adjusted anywhere inside or outside the graph by placing it at various positions. Sometimes it is necessary to create a single legend for all subplots. Below are the examples that show a single legend for all subplots." }, { "code": null, "e": 572, "s": 551, "text": "Syntax of Subplot():" }, { "code": null, "e": 602, "s": 572, "text": "subplot(nrows,ncols,nsubplot)" }, { "code": null, "e": 748, "s": 602, "text": "For example, subplot(2,1,1) is the figure which represents the first subplot with 2 rows and one column, the first subplot lies in the first row." }, { "code": null, "e": 848, "s": 748, "text": "The subplot(2,1,2) represents the second subplot which lies in the second row in the first column. " }, { "code": null, "e": 875, "s": 848, "text": "The legend command Syntax:" }, { "code": null, "e": 899, "s": 875, "text": "legend(*args, **kwargs)" }, { "code": null, "e": 1075, "s": 899, "text": "If the length of arguments i.e, args is 0 in the legend command then it automatically generates the legend from label properties by calling get_legend_handles_labels() method." }, { "code": null, "e": 1119, "s": 1075, "text": " For example, ax.legend() is equivalent to:" }, { "code": null, "e": 1195, "s": 1119, "text": "handles, labels = ax.get_legend_handles_labels()\nax.legend(handles, labels)" }, { "code": null, "e": 1307, "s": 1195, "text": "The get_legend_handles_labels() method returns a tuple of two lists, i.e., list of artists and list of labels. " }, { "code": null, "e": 1318, "s": 1307, "text": "Example 1:" }, { "code": null, "e": 1326, "s": 1318, "text": "Python3" }, { "code": "# Importing required librariesimport matplotlib.pyplot as pltimport numpy as np # 2 subplots in 1 row and 2 columnsfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5)) x1 = ['Telugu', 'Hindi', 'English', 'Maths', 'Science', 'Social']y1 = [45, 34, 30, 45, 50, 38]y2 = [36, 28, 30, 45, 38, 48] # Labels to use in the legend for each linelabels = [\"in 2019\", \"in 2020\"] # Title for subplotsfig.suptitle('Number of Students passed in each subject\\from a class in 2019 & 2020', fontsize=20) # Creating the sub-plots.l1 = ax1.plot(x1, y1, color=\"green\")l2 = ax2.plot(x1, y2, color=\"blue\") ax1.set_yticks(np.arange(0, 51, 5))ax2.set_yticks(np.arange(0, 51, 5)) ax1.set_ylabel('Number of students', fontsize=25) fig.legend([l1, l2], labels=labels, loc=\"upper right\") # Adjusting the sub-plotsplt.subplots_adjust(right=0.9) plt.show()", "e": 2180, "s": 1326, "text": null }, { "code": null, "e": 2188, "s": 2180, "text": "Output:" }, { "code": null, "e": 2199, "s": 2188, "text": "Example 2:" }, { "code": null, "e": 2207, "s": 2199, "text": "Python3" }, { "code": "# Plotting sub-plots of number of # students passed in each subject # in academic year 2017-20.import matplotlib.pyplot as pltimport numpy as np plt.style.use('seaborn') # Plot Styles fig = plt.figure() # 4 subplots in 2 rows and 2 columns in a figureaxes = fig.subplots(nrows=2, ncols=2) axes[0, 0].bar(['Telugu', 'Hindi', 'English', 'Maths', 'Science', 'Social'], [50, 27, 42, 34, 45, 48], color='g', label=\"Students passed in 2017\") axes[0, 0].set_yticks(np.arange(0, 51, 5)) axes[0, 1].bar(['Telugu', 'Hindi', 'English', 'Maths', 'Science', 'Social'], [50, 27, 42, 34, 45, 48], color='y', label=\"Students passed in 2018\") axes[0, 1].set_yticks(np.arange(0, 51, 5)) axes[1, 0].bar(['Telugu', 'Hindi', 'English', 'Maths', 'Science', 'Social'], [40, 27, 22, 44, 35, 38], color='r', label=\"Students passed in 2019\") axes[1, 0].set_yticks(np.arange(0, 51, 5))axes[1, 0].set_xlabel('Subjects', fontsize=25) # rotating third sub-plot x-axis labelsfor tick in axes[1, 0].get_xticklabels(): tick.set_rotation(45) axes[1, 0].set_ylabel(\" Number of Students passed in 2017-2020\", fontsize=20) axes[1, 1].bar(['Telugu', 'Hindi', 'English', 'Maths', 'Science', 'Social'], [40, 27, 32, 44, 45, 48], color='b', label=\"Students passed in 2020\") axes[1, 1].set_xlabel('Subjects', fontsize=20)axes[1, 1].set_yticks(np.arange(0, 51, 5)) lines = []labels = [] for ax in fig.axes: Line, Label = ax.get_legend_handles_labels() # print(Label) lines.extend(Line) labels.extend(Label) # rotating x-axis labels of last sub-plotplt.xticks(rotation=45) fig.legend(lines, labels, loc='upper right') plt.show()", "e": 4008, "s": 2207, "text": null }, { "code": null, "e": 4017, "s": 4008, "text": "Output :" }, { "code": null, "e": 4035, "s": 4017, "text": "Python-matplotlib" }, { "code": null, "e": 4059, "s": 4035, "text": "Technical Scripter 2020" }, { "code": null, "e": 4066, "s": 4059, "text": "Python" }, { "code": null, "e": 4085, "s": 4066, "text": "Technical Scripter" } ]
Python | Speech recognition on large audio files
23 Jul, 2019 Speech recognition is the process of converting audio into text. This is commonly used in voice assistants like Alexa, Siri, etc. Python provides an API called SpeechRecognition to allow us to convert audio into text for further processing. In this article, we will look at converting large or long audio files into text using the SpeechRecognition API in python. When the input is a long audio file, the accuracy of speech recognition decreases. Moreover, Google speech recognition API cannot recognize long audio files with good accuracy. Therefore, we need to process the audio file into smaller chunks and then feed these chunks to the API. Doing this improves accuracy and allows us to recognize large audio files. One way to process the audio file is to split it into chunks of constant size. For example, we can take an audio file which is 10 minutes long and split it into 60 chunks each of length 10 seconds. We can then feed these chunks to the API and convert speech to text by concatenating the results of all these chunks. This method is inaccurate. Splitting the audio file into chunks of constant size might interrupt sentences in between and we might lose some important words in the process. This is because the audio file might end before a word is completely spoken and google will not be able to recognize incomplete words. The other way is to split the audio file based on silence. Humans pause for a short amount of time between sentences. If we can split the audio file into chunks based on these silences, then we can process the file sentence by sentence and concatenate them to get the result. This approach is more accurate than the previous one because we do not cut sentences in between and the audio chunk will contain the entire sentence without any interruptions. This way, we don’t need to split it into chunks of constant length. The disadvantage of this method is that it is difficult to determine the length of silence to split because different users speak differently and some users might pause for 1 second in between sentences whereas some may pause for just 0.5 seconds. Pydub: sudo pip3 install pydub Speech recognition: sudo pip3 install SpeechRecognition Example: Input: peacock.wav Output: exporting chunk0.wav Processing chunk 0 exporting chunk1.wav Processing chunk 1 exporting chunk2.wav Processing chunk 2 exporting chunk3.wav Processing chunk 3 exporting chunk4.wav Processing chunk 4 exporting chunk5.wav Processing chunk 5 exporting chunk6.wav Processing chunk 6 Code: # importing librariesimport speech_recognition as sr import os from pydub import AudioSegmentfrom pydub.silence import split_on_silence # a function that splits the audio file into chunks# and applies speech recognitiondef silence_based_conversion(path = "alice-medium.wav"): # open the audio file stored in # the local system as a wav file. song = AudioSegment.from_wav(path) # open a file where we will concatenate # and store the recognized text fh = open("recognized.txt", "w+") # split track where silence is 0.5 seconds # or more and get chunks chunks = split_on_silence(song, # must be silent for at least 0.5 seconds # or 500 ms. adjust this value based on user # requirement. if the speaker stays silent for # longer, increase this value. else, decrease it. min_silence_len = 500, # consider it silent if quieter than -16 dBFS # adjust this per requirement silence_thresh = -16 ) # create a directory to store the audio chunks. try: os.mkdir('audio_chunks') except(FileExistsError): pass # move into the directory to # store the audio files. os.chdir('audio_chunks') i = 0 # process each chunk for chunk in chunks: # Create 0.5 seconds silence chunk chunk_silent = AudioSegment.silent(duration = 10) # add 0.5 sec silence to beginning and # end of audio chunk. This is done so that # it doesn't seem abruptly sliced. audio_chunk = chunk_silent + chunk + chunk_silent # export audio chunk and save it in # the current directory. print("saving chunk{0}.wav".format(i)) # specify the bitrate to be 192 k audio_chunk.export("./chunk{0}.wav".format(i), bitrate ='192k', format ="wav") # the name of the newly created chunk filename = 'chunk'+str(i)+'.wav' print("Processing chunk "+str(i)) # get the name of the newly created chunk # in the AUDIO_FILE variable for later use. file = filename # create a speech recognition object r = sr.Recognizer() # recognize the chunk with sr.AudioFile(file) as source: # remove this if it is not working # correctly. r.adjust_for_ambient_noise(source) audio_listened = r.listen(source) try: # try converting it to text rec = r.recognize_google(audio_listened) # write the output to the file. fh.write(rec+". ") # catch any errors. except sr.UnknownValueError: print("Could not understand audio") except sr.RequestError as e: print("Could not request results. check your internet connection") i += 1 os.chdir('..') if __name__ == '__main__': print('Enter the audio file path') path = input() silence_based_conversion(path) Output : recognized.txt: The peacock is the national bird of India. They have colourful feathers, two legs and a small beak. They are famous for their dance. When a peacock dances it spreads its feathers like a fan. It has a long shiny dark blue neck. Peacocks are mostly found in the fields they are very beautiful birds. The females are known as 'Peahen1. Their feathers are used for making jackets, purses etc. We can see them in a zoo. shubham_singh Advanced Computer Subject Machine Learning Project Python Python Programs Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. System Design Tutorial ML | Linear Regression Reinforcement learning Docker - COPY Instruction Supervised and Unsupervised learning ML | Linear Regression Reinforcement learning Agents in Artificial Intelligence Supervised and Unsupervised learning Search Algorithms in AI
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Jul, 2019" }, { "code": null, "e": 392, "s": 28, "text": "Speech recognition is the process of converting audio into text. This is commonly used in voice assistants like Alexa, Siri, etc. Python provides an API called SpeechRecognition to allow us to convert audio into text for further processing. In this article, we will look at converting large or long audio files into text using the SpeechRecognition API in python." }, { "code": null, "e": 748, "s": 392, "text": "When the input is a long audio file, the accuracy of speech recognition decreases. Moreover, Google speech recognition API cannot recognize long audio files with good accuracy. Therefore, we need to process the audio file into smaller chunks and then feed these chunks to the API. Doing this improves accuracy and allows us to recognize large audio files." }, { "code": null, "e": 1372, "s": 748, "text": "One way to process the audio file is to split it into chunks of constant size. For example, we can take an audio file which is 10 minutes long and split it into 60 chunks each of length 10 seconds. We can then feed these chunks to the API and convert speech to text by concatenating the results of all these chunks. This method is inaccurate. Splitting the audio file into chunks of constant size might interrupt sentences in between and we might lose some important words in the process. This is because the audio file might end before a word is completely spoken and google will not be able to recognize incomplete words." }, { "code": null, "e": 1892, "s": 1372, "text": "The other way is to split the audio file based on silence. Humans pause for a short amount of time between sentences. If we can split the audio file into chunks based on these silences, then we can process the file sentence by sentence and concatenate them to get the result. This approach is more accurate than the previous one because we do not cut sentences in between and the audio chunk will contain the entire sentence without any interruptions. This way, we don’t need to split it into chunks of constant length." }, { "code": null, "e": 2140, "s": 1892, "text": "The disadvantage of this method is that it is difficult to determine the length of silence to split because different users speak differently and some users might pause for 1 second in between sentences whereas some may pause for just 0.5 seconds." }, { "code": null, "e": 2228, "s": 2140, "text": "Pydub: sudo pip3 install pydub\nSpeech recognition: sudo pip3 install SpeechRecognition\n" }, { "code": null, "e": 2237, "s": 2228, "text": "Example:" }, { "code": null, "e": 2556, "s": 2237, "text": " \nInput: peacock.wav \n\n \nOutput: \n\nexporting chunk0.wav\nProcessing chunk 0\nexporting chunk1.wav\nProcessing chunk 1\nexporting chunk2.wav\nProcessing chunk 2\nexporting chunk3.wav\nProcessing chunk 3\nexporting chunk4.wav\nProcessing chunk 4\nexporting chunk5.wav\nProcessing chunk 5\nexporting chunk6.wav\nProcessing chunk 6\n\n\n" }, { "code": null, "e": 2562, "s": 2556, "text": "Code:" }, { "code": "# importing librariesimport speech_recognition as sr import os from pydub import AudioSegmentfrom pydub.silence import split_on_silence # a function that splits the audio file into chunks# and applies speech recognitiondef silence_based_conversion(path = \"alice-medium.wav\"): # open the audio file stored in # the local system as a wav file. song = AudioSegment.from_wav(path) # open a file where we will concatenate # and store the recognized text fh = open(\"recognized.txt\", \"w+\") # split track where silence is 0.5 seconds # or more and get chunks chunks = split_on_silence(song, # must be silent for at least 0.5 seconds # or 500 ms. adjust this value based on user # requirement. if the speaker stays silent for # longer, increase this value. else, decrease it. min_silence_len = 500, # consider it silent if quieter than -16 dBFS # adjust this per requirement silence_thresh = -16 ) # create a directory to store the audio chunks. try: os.mkdir('audio_chunks') except(FileExistsError): pass # move into the directory to # store the audio files. os.chdir('audio_chunks') i = 0 # process each chunk for chunk in chunks: # Create 0.5 seconds silence chunk chunk_silent = AudioSegment.silent(duration = 10) # add 0.5 sec silence to beginning and # end of audio chunk. This is done so that # it doesn't seem abruptly sliced. audio_chunk = chunk_silent + chunk + chunk_silent # export audio chunk and save it in # the current directory. print(\"saving chunk{0}.wav\".format(i)) # specify the bitrate to be 192 k audio_chunk.export(\"./chunk{0}.wav\".format(i), bitrate ='192k', format =\"wav\") # the name of the newly created chunk filename = 'chunk'+str(i)+'.wav' print(\"Processing chunk \"+str(i)) # get the name of the newly created chunk # in the AUDIO_FILE variable for later use. file = filename # create a speech recognition object r = sr.Recognizer() # recognize the chunk with sr.AudioFile(file) as source: # remove this if it is not working # correctly. r.adjust_for_ambient_noise(source) audio_listened = r.listen(source) try: # try converting it to text rec = r.recognize_google(audio_listened) # write the output to the file. fh.write(rec+\". \") # catch any errors. except sr.UnknownValueError: print(\"Could not understand audio\") except sr.RequestError as e: print(\"Could not request results. check your internet connection\") i += 1 os.chdir('..') if __name__ == '__main__': print('Enter the audio file path') path = input() silence_based_conversion(path)", "e": 5542, "s": 2562, "text": null }, { "code": null, "e": 5551, "s": 5542, "text": "Output :" }, { "code": null, "e": 5991, "s": 5551, "text": "\nrecognized.txt:\n\nThe peacock is the national bird of India. They have colourful feathers, two legs and \na small beak. They are famous for their dance. When a peacock dances it spreads its \nfeathers like a fan. It has a long shiny dark blue neck. Peacocks are mostly found in \nthe fields they are very beautiful birds. The females are known as 'Peahen1. Their \nfeathers are used for making jackets, purses etc. We can see them in a zoo. \n\n" }, { "code": null, "e": 6005, "s": 5991, "text": "shubham_singh" }, { "code": null, "e": 6031, "s": 6005, "text": "Advanced Computer Subject" }, { "code": null, "e": 6048, "s": 6031, "text": "Machine Learning" }, { "code": null, "e": 6056, "s": 6048, "text": "Project" }, { "code": null, "e": 6063, "s": 6056, "text": "Python" }, { "code": null, "e": 6079, "s": 6063, "text": "Python Programs" }, { "code": null, "e": 6096, "s": 6079, "text": "Machine Learning" }, { "code": null, "e": 6194, "s": 6096, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6217, "s": 6194, "text": "System Design Tutorial" }, { "code": null, "e": 6240, "s": 6217, "text": "ML | Linear Regression" }, { "code": null, "e": 6263, "s": 6240, "text": "Reinforcement learning" }, { "code": null, "e": 6289, "s": 6263, "text": "Docker - COPY Instruction" }, { "code": null, "e": 6326, "s": 6289, "text": "Supervised and Unsupervised learning" }, { "code": null, "e": 6349, "s": 6326, "text": "ML | Linear Regression" }, { "code": null, "e": 6372, "s": 6349, "text": "Reinforcement learning" }, { "code": null, "e": 6406, "s": 6372, "text": "Agents in Artificial Intelligence" }, { "code": null, "e": 6443, "s": 6406, "text": "Supervised and Unsupervised learning" } ]
Ruby | Time usec function
06 Jan, 2020 Time#usec() is a Time class method which returns the number of microseconds for time. Syntax: Time.usec() Parameter: Time values Return: the number of microseconds for time. Example #1 : # Ruby code for Time.usec() method # loading libraryrequire 'time' # declaring time a = Time.new(2019) # declaring timeb = Time.new(2019, 10) # declaring timec = Time.new(2019, 12, 31) # Time puts "Time a : #{a}\n\n"puts "Time b : #{b}\n\n"puts "Time c : #{c}\n\n\n\n" # usec form puts "Time a usec form : #{a.usec}\n\n"puts "Time b usec form : #{b.usec}\n\n"puts "Time c usec form : #{c.usec}\n\n" Output : Time a : 2019-01-01 00:00:00 +0000 Time b : 2019-10-01 00:00:00 +0000 Time c : 2019-12-31 00:00:00 +0000 Time a usec form : 0 Time b usec form : 0 Time c usec form : 0 Example #2 : # Ruby code for Time.usec() method # loading libraryrequire 'time' # declaring time a = Time.now # declaring timeb = Time.new(1000, 10, 10) # declaring timec = Time.new(2020, 12) # Time puts "Time a : #{a}\n\n"puts "Time b : #{b}\n\n"puts "Time c : #{c}\n\n\n\n" # usec form puts "Time a usec form : #{a.usec}\n\n"puts "Time b usec form : #{b.usec}\n\n"puts "Time c usec form : #{c.usec}\n\n" Output : Time a : 2019-08-27 09:16:21 +0000 Time b : 1000-10-10 00:00:00 +0000 Time c : 2020-12-01 00:00:00 +0000 Time a usec form : 673126 Time b usec form : 0 Time c usec form : 0 Ruby Time-class Ruby-Methods Ruby Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Make a Custom Array of Hashes in Ruby? Ruby | Array count() operation Ruby | Array slice() function Include v/s Extend in Ruby Global Variable in Ruby Ruby | Enumerator each_with_index function Ruby | Case Statement Ruby | Array select() function Ruby | unless Statement and unless Modifier Ruby | Data Types
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Jan, 2020" }, { "code": null, "e": 114, "s": 28, "text": "Time#usec() is a Time class method which returns the number of microseconds for time." }, { "code": null, "e": 134, "s": 114, "text": "Syntax: Time.usec()" }, { "code": null, "e": 157, "s": 134, "text": "Parameter: Time values" }, { "code": null, "e": 202, "s": 157, "text": "Return: the number of microseconds for time." }, { "code": null, "e": 215, "s": 202, "text": "Example #1 :" }, { "code": "# Ruby code for Time.usec() method # loading libraryrequire 'time' # declaring time a = Time.new(2019) # declaring timeb = Time.new(2019, 10) # declaring timec = Time.new(2019, 12, 31) # Time puts \"Time a : #{a}\\n\\n\"puts \"Time b : #{b}\\n\\n\"puts \"Time c : #{c}\\n\\n\\n\\n\" # usec form puts \"Time a usec form : #{a.usec}\\n\\n\"puts \"Time b usec form : #{b.usec}\\n\\n\"puts \"Time c usec form : #{c.usec}\\n\\n\"", "e": 622, "s": 215, "text": null }, { "code": null, "e": 631, "s": 622, "text": "Output :" }, { "code": null, "e": 809, "s": 631, "text": "Time a : 2019-01-01 00:00:00 +0000\n\nTime b : 2019-10-01 00:00:00 +0000\n\nTime c : 2019-12-31 00:00:00 +0000\n\n\n\nTime a usec form : 0\n\nTime b usec form : 0\n\nTime c usec form : 0\n\n\n" }, { "code": null, "e": 822, "s": 809, "text": "Example #2 :" }, { "code": "# Ruby code for Time.usec() method # loading libraryrequire 'time' # declaring time a = Time.now # declaring timeb = Time.new(1000, 10, 10) # declaring timec = Time.new(2020, 12) # Time puts \"Time a : #{a}\\n\\n\"puts \"Time b : #{b}\\n\\n\"puts \"Time c : #{c}\\n\\n\\n\\n\" # usec form puts \"Time a usec form : #{a.usec}\\n\\n\"puts \"Time b usec form : #{b.usec}\\n\\n\"puts \"Time c usec form : #{c.usec}\\n\\n\"", "e": 1223, "s": 822, "text": null }, { "code": null, "e": 1232, "s": 1223, "text": "Output :" }, { "code": null, "e": 1414, "s": 1232, "text": "Time a : 2019-08-27 09:16:21 +0000\n\nTime b : 1000-10-10 00:00:00 +0000\n\nTime c : 2020-12-01 00:00:00 +0000\n\n\n\nTime a usec form : 673126\n\nTime b usec form : 0\n\nTime c usec form : 0\n\n" }, { "code": null, "e": 1430, "s": 1414, "text": "Ruby Time-class" }, { "code": null, "e": 1443, "s": 1430, "text": "Ruby-Methods" }, { "code": null, "e": 1448, "s": 1443, "text": "Ruby" }, { "code": null, "e": 1546, "s": 1448, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1592, "s": 1546, "text": "How to Make a Custom Array of Hashes in Ruby?" }, { "code": null, "e": 1623, "s": 1592, "text": "Ruby | Array count() operation" }, { "code": null, "e": 1653, "s": 1623, "text": "Ruby | Array slice() function" }, { "code": null, "e": 1680, "s": 1653, "text": "Include v/s Extend in Ruby" }, { "code": null, "e": 1704, "s": 1680, "text": "Global Variable in Ruby" }, { "code": null, "e": 1747, "s": 1704, "text": "Ruby | Enumerator each_with_index function" }, { "code": null, "e": 1769, "s": 1747, "text": "Ruby | Case Statement" }, { "code": null, "e": 1800, "s": 1769, "text": "Ruby | Array select() function" }, { "code": null, "e": 1844, "s": 1800, "text": "Ruby | unless Statement and unless Modifier" } ]
How to get form data using POST method in PHP ?
02 Jun, 2020 PHP provides a way to read raw POST data of an HTML Form using php:// which is used for accessing PHP’s input and output streams. In this article, we will use the mentioned way in three different ways. We will use php://input, which is a read-only PHP stream. We will create a basic HTML form page where we can use all the possible approaches one at a time.HTML Code: <!DOCTYPE html><html><head> <title>POST Body</title> <style> form { margin: 30px 0px; } input { display: block; margin: 10px 15px; padding: 8px 10px; font-size: 16px; } div { font-size: 20px; margin: 0px 15px; } h2 { color: green; margin: 20px 15px; } </style></head><body> <h2>GeeksforGeeks</h2> <form method="post"> <input type="text" name="username" placeholder="Enter Username"> <input type="password" name="password" placeholder="Enter Password"> <input type="submit" name="submit-btn" value="submit"> </form> <br></body></html> Below examples illustrate the approach:Example 1: In this example, we will use file_get_contents() Function. The file_get_contents() function is used to get the data in string format. Syntax:file_get_contents('php://input'); file_get_contents('php://input'); PHP Code:<?php if (isset($_POST["submit-btn"])) { $post_data = file_get_contents('php://input'); echo "<div> POST BODY <br>".$post_data."</div>"; }?> <?php if (isset($_POST["submit-btn"])) { $post_data = file_get_contents('php://input'); echo "<div> POST BODY <br>".$post_data."</div>"; }?> Output: Example 2: In this example, we will use print_r() Function. It is a much simpler way to get the POST data and that is using the print_r() function. This will give the output in the form of an array. Syntax:print_r($_POST); print_r($_POST); PHP Code:<?php if (isset($_POST["submit-btn"])) { echo "<div> POST BODY <br>"; print_r($_POST); echo "</div>"; }?> <?php if (isset($_POST["submit-btn"])) { echo "<div> POST BODY <br>"; print_r($_POST); echo "</div>"; }?> Output: Example 3: We can also use var_dump() function which will give us an array as well but with a bit more information. Syntax:var_dump($_POST); var_dump($_POST); PHP Code:<?php if (isset($_POST["submit-btn"])) { echo "<div> POST BODY <br>"; var_dump($_POST); echo "</div>"; }?> <?php if (isset($_POST["submit-btn"])) { echo "<div> POST BODY <br>"; var_dump($_POST); echo "</div>"; }?> Output: Akanksha_Rai PHP-Misc Picked PHP Technical Scripter Web Technologies Web technologies Questions PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Jun, 2020" }, { "code": null, "e": 288, "s": 28, "text": "PHP provides a way to read raw POST data of an HTML Form using php:// which is used for accessing PHP’s input and output streams. In this article, we will use the mentioned way in three different ways. We will use php://input, which is a read-only PHP stream." }, { "code": null, "e": 396, "s": 288, "text": "We will create a basic HTML form page where we can use all the possible approaches one at a time.HTML Code:" }, { "code": "<!DOCTYPE html><html><head> <title>POST Body</title> <style> form { margin: 30px 0px; } input { display: block; margin: 10px 15px; padding: 8px 10px; font-size: 16px; } div { font-size: 20px; margin: 0px 15px; } h2 { color: green; margin: 20px 15px; } </style></head><body> <h2>GeeksforGeeks</h2> <form method=\"post\"> <input type=\"text\" name=\"username\" placeholder=\"Enter Username\"> <input type=\"password\" name=\"password\" placeholder=\"Enter Password\"> <input type=\"submit\" name=\"submit-btn\" value=\"submit\"> </form> <br></body></html>", "e": 1214, "s": 396, "text": null }, { "code": null, "e": 1398, "s": 1214, "text": "Below examples illustrate the approach:Example 1: In this example, we will use file_get_contents() Function. The file_get_contents() function is used to get the data in string format." }, { "code": null, "e": 1439, "s": 1398, "text": "Syntax:file_get_contents('php://input');" }, { "code": null, "e": 1473, "s": 1439, "text": "file_get_contents('php://input');" }, { "code": null, "e": 1652, "s": 1473, "text": "PHP Code:<?php if (isset($_POST[\"submit-btn\"])) { $post_data = file_get_contents('php://input'); echo \"<div> POST BODY <br>\".$post_data.\"</div>\"; }?>" }, { "code": "<?php if (isset($_POST[\"submit-btn\"])) { $post_data = file_get_contents('php://input'); echo \"<div> POST BODY <br>\".$post_data.\"</div>\"; }?>", "e": 1822, "s": 1652, "text": null }, { "code": null, "e": 1830, "s": 1822, "text": "Output:" }, { "code": null, "e": 2029, "s": 1830, "text": "Example 2: In this example, we will use print_r() Function. It is a much simpler way to get the POST data and that is using the print_r() function. This will give the output in the form of an array." }, { "code": null, "e": 2053, "s": 2029, "text": "Syntax:print_r($_POST);" }, { "code": null, "e": 2070, "s": 2053, "text": "print_r($_POST);" }, { "code": null, "e": 2213, "s": 2070, "text": "PHP Code:<?php if (isset($_POST[\"submit-btn\"])) { echo \"<div> POST BODY <br>\"; print_r($_POST); echo \"</div>\"; }?>" }, { "code": "<?php if (isset($_POST[\"submit-btn\"])) { echo \"<div> POST BODY <br>\"; print_r($_POST); echo \"</div>\"; }?>", "e": 2347, "s": 2213, "text": null }, { "code": null, "e": 2355, "s": 2347, "text": "Output:" }, { "code": null, "e": 2471, "s": 2355, "text": "Example 3: We can also use var_dump() function which will give us an array as well but with a bit more information." }, { "code": null, "e": 2496, "s": 2471, "text": "Syntax:var_dump($_POST);" }, { "code": null, "e": 2514, "s": 2496, "text": "var_dump($_POST);" }, { "code": null, "e": 2658, "s": 2514, "text": "PHP Code:<?php if (isset($_POST[\"submit-btn\"])) { echo \"<div> POST BODY <br>\"; var_dump($_POST); echo \"</div>\"; }?>" }, { "code": "<?php if (isset($_POST[\"submit-btn\"])) { echo \"<div> POST BODY <br>\"; var_dump($_POST); echo \"</div>\"; }?>", "e": 2793, "s": 2658, "text": null }, { "code": null, "e": 2801, "s": 2793, "text": "Output:" }, { "code": null, "e": 2814, "s": 2801, "text": "Akanksha_Rai" }, { "code": null, "e": 2823, "s": 2814, "text": "PHP-Misc" }, { "code": null, "e": 2830, "s": 2823, "text": "Picked" }, { "code": null, "e": 2834, "s": 2830, "text": "PHP" }, { "code": null, "e": 2853, "s": 2834, "text": "Technical Scripter" }, { "code": null, "e": 2870, "s": 2853, "text": "Web Technologies" }, { "code": null, "e": 2897, "s": 2870, "text": "Web technologies Questions" }, { "code": null, "e": 2901, "s": 2897, "text": "PHP" } ]
Print nodes having maximum and minimum degrees
18 Aug, 2021 Given an undirected graph having N nodes, the task is to print the nodes having minimum and maximum degree.Examples: Input: 1-----2 | | 3-----4 Output: Nodes with maximum degree : 1 2 3 4 Nodes with minimum degree : 1 2 3 4 Every node has a degree of 2. Input: 1 / \ 2 3 / 4 Output: Nodes with maximum degree : 1 2 Nodes with minimum degree : 3 4 Approach: For an undirected graph, the degree of a node is the number of edges incident to it, so the degree of each node can be calculated by counting its frequency in the list of edges. Hence the approach is to use a map to calculate the frequency of every vertex from the edge list and use the map to find the nodes having maximum and minimum degrees. Below is the implementation of the above approach: C++ Java Python3 C# // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to print the nodes having// maximum and minimum degreevoid minMax(int edges[][2], int len, int n){ // Map to store the degrees of every node map<int, int> m; for (int i = 0; i < len; i++) { // Storing the degree for each node m[edges[i][0]]++; m[edges[i][1]]++; } // maxi and mini variables to store // the maximum and minimum degree int maxi = 0; int mini = n; for (int i = 1; i <= n; i++) { maxi = max(maxi, m[i]); mini = min(mini, m[i]); } // Printing all the nodes with maximum degree cout << "Nodes with maximum degree : "; for (int i = 1; i <= n; i++) { if (m[i] == maxi) cout << i << " "; } cout << endl; // Printing all the nodes with minimum degree cout << "Nodes with minimum degree : "; for (int i = 1; i <= n; i++) { if (m[i] == mini) cout << i << " "; }} // Driver codeint main(){ // Count of nodes and edges int n = 4, m = 6; // The edge list int edges[][2] = { { 1, 2 }, { 1, 3 }, { 1, 4 }, { 2, 3 }, { 2, 4 }, { 3, 4 } }; minMax(edges, m, 4); return 0;} // Java implementation of the approachimport java.util.*; class GFG{ // Function to print the nodes having// maximum and minimum degreestatic void minMax(int edges[][], int len, int n){ // Map to store the degrees of every node HashMap<Integer, Integer> m = new HashMap<Integer, Integer>(); for (int i = 0; i < len; i++) { // Storing the degree for each node if(m.containsKey(edges[i][0])) { m.put(edges[i][0], m.get(edges[i][0]) + 1); } else { m.put(edges[i][0], 1); } if(m.containsKey(edges[i][1])) { m.put(edges[i][1], m.get(edges[i][1]) + 1); } else { m.put(edges[i][1], 1); } } // maxi and mini variables to store // the maximum and minimum degree int maxi = 0; int mini = n; for (int i = 1; i <= n; i++) { maxi = Math.max(maxi, m.get(i)); mini = Math.min(mini, m.get(i)); } // Printing all the nodes with maximum degree System.out.print("Nodes with maximum degree : "); for (int i = 1; i <= n; i++) { if (m.get(i) == maxi) System.out.print(i + " "); } System.out.println(); // Printing all the nodes with minimum degree System.out.print("Nodes with minimum degree : "); for (int i = 1; i <= n; i++) { if (m.get(i) == mini) System.out.print(i + " "); }} // Driver codepublic static void main(String[] args){ // Count of nodes and edges int n = 4, m = 6; // The edge list int edges[][] = {{ 1, 2 }, { 1, 3 }, { 1, 4 }, { 2, 3 }, { 2, 4 }, { 3, 4 }}; minMax(edges, m, 4);}} // This code is contributed by PrinciRaj1992 # Python3 implementation of the approach # Function to print the nodes having# maximum and minimum degreedef minMax(edges, leng, n) : # Map to store the degrees of every node m = {}; for i in range(leng) : m[edges[i][0]] = 0; m[edges[i][1]] = 0; for i in range(leng) : # Storing the degree for each node m[edges[i][0]] += 1; m[edges[i][1]] += 1; # maxi and mini variables to store # the maximum and minimum degree maxi = 0; mini = n; for i in range(1, n + 1) : maxi = max(maxi, m[i]); mini = min(mini, m[i]); # Printing all the nodes # with maximum degree print("Nodes with maximum degree : ", end = "") for i in range(1, n + 1) : if (m[i] == maxi) : print(i, end = " "); print() # Printing all the nodes # with minimum degree print("Nodes with minimum degree : ", end = "") for i in range(1, n + 1) : if (m[i] == mini) : print(i, end = " "); # Driver codeif __name__ == "__main__" : # Count of nodes and edges n = 4; m = 6; # The edge list edges = [[ 1, 2 ], [ 1, 3 ], [ 1, 4 ], [ 2, 3 ], [ 2, 4 ], [ 3, 4 ]]; minMax(edges, m, 4); # This code is contributed by AnkitRai01 // C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // Function to print the nodes having// maximum and minimum degreestatic void minMax(int [,]edges, int len, int n){ // Map to store the degrees of every node Dictionary<int, int> m = new Dictionary<int, int>(); for (int i = 0; i < len; i++) { // Storing the degree for each node if(m.ContainsKey(edges[i, 0])) { m[edges[i, 0]] = m[edges[i, 0]] + 1; } else { m.Add(edges[i, 0], 1); } if(m.ContainsKey(edges[i, 1])) { m[edges[i, 1]] = m[edges[i, 1]] + 1; } else { m.Add(edges[i, 1], 1); } } // maxi and mini variables to store // the maximum and minimum degree int maxi = 0; int mini = n; for (int i = 1; i <= n; i++) { maxi = Math.Max(maxi, m[i]); mini = Math.Min(mini, m[i]); } // Printing all the nodes with maximum degree Console.Write("Nodes with maximum degree : "); for (int i = 1; i <= n; i++) { if (m[i] == maxi) Console.Write(i + " "); } Console.WriteLine(); // Printing all the nodes with minimum degree Console.Write("Nodes with minimum degree : "); for (int i = 1; i <= n; i++) { if (m[i] == mini) Console.Write(i + " "); }} // Driver codepublic static void Main(String[] args){ // Count of nodes and edges int m = 6; // The edge list int [,]edges = {{ 1, 2 }, { 1, 3 }, { 1, 4 }, { 2, 3 }, { 2, 4 }, { 3, 4 }}; minMax(edges, m, 4);}} // This code is contributed by 29AjayKumar Nodes with maximum degree : 1 2 3 4 Nodes with minimum degree : 1 2 3 4 Time Complexity: O(M*logN + N). Auxiliary Space: O(N). ankthon princiraj1992 29AjayKumar pankajsharmagfg Competitive Programming Data Structures Graph Data Structures Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count of strings whose prefix match with the given string to a given length k Most important type of Algorithms The Ultimate Beginner's Guide For DSA Find two numbers from their sum and XOR C++: Methods of code shortening in competitive programming DSA Sheet by Love Babbar SDE SHEET - A Complete Guide for SDE Preparation Top 50 Array Coding Problems for Interviews Introduction to Data Structures Doubly Linked List | Set 1 (Introduction and Insertion)
[ { "code": null, "e": 54, "s": 26, "text": "\n18 Aug, 2021" }, { "code": null, "e": 173, "s": 54, "text": "Given an undirected graph having N nodes, the task is to print the nodes having minimum and maximum degree.Examples: " }, { "code": null, "e": 424, "s": 173, "text": "Input:\n1-----2\n| |\n3-----4\nOutput:\nNodes with maximum degree : 1 2 3 4 \nNodes with minimum degree : 1 2 3 4 \nEvery node has a degree of 2.\n\nInput:\n 1\n / \\\n 2 3\n /\n4\nOutput:\nNodes with maximum degree : 1 2 \nNodes with minimum degree : 3 4 " }, { "code": null, "e": 834, "s": 426, "text": "Approach: For an undirected graph, the degree of a node is the number of edges incident to it, so the degree of each node can be calculated by counting its frequency in the list of edges. Hence the approach is to use a map to calculate the frequency of every vertex from the edge list and use the map to find the nodes having maximum and minimum degrees. Below is the implementation of the above approach: " }, { "code": null, "e": 838, "s": 834, "text": "C++" }, { "code": null, "e": 843, "s": 838, "text": "Java" }, { "code": null, "e": 851, "s": 843, "text": "Python3" }, { "code": null, "e": 854, "s": 851, "text": "C#" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to print the nodes having// maximum and minimum degreevoid minMax(int edges[][2], int len, int n){ // Map to store the degrees of every node map<int, int> m; for (int i = 0; i < len; i++) { // Storing the degree for each node m[edges[i][0]]++; m[edges[i][1]]++; } // maxi and mini variables to store // the maximum and minimum degree int maxi = 0; int mini = n; for (int i = 1; i <= n; i++) { maxi = max(maxi, m[i]); mini = min(mini, m[i]); } // Printing all the nodes with maximum degree cout << \"Nodes with maximum degree : \"; for (int i = 1; i <= n; i++) { if (m[i] == maxi) cout << i << \" \"; } cout << endl; // Printing all the nodes with minimum degree cout << \"Nodes with minimum degree : \"; for (int i = 1; i <= n; i++) { if (m[i] == mini) cout << i << \" \"; }} // Driver codeint main(){ // Count of nodes and edges int n = 4, m = 6; // The edge list int edges[][2] = { { 1, 2 }, { 1, 3 }, { 1, 4 }, { 2, 3 }, { 2, 4 }, { 3, 4 } }; minMax(edges, m, 4); return 0;}", "e": 2185, "s": 854, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class GFG{ // Function to print the nodes having// maximum and minimum degreestatic void minMax(int edges[][], int len, int n){ // Map to store the degrees of every node HashMap<Integer, Integer> m = new HashMap<Integer, Integer>(); for (int i = 0; i < len; i++) { // Storing the degree for each node if(m.containsKey(edges[i][0])) { m.put(edges[i][0], m.get(edges[i][0]) + 1); } else { m.put(edges[i][0], 1); } if(m.containsKey(edges[i][1])) { m.put(edges[i][1], m.get(edges[i][1]) + 1); } else { m.put(edges[i][1], 1); } } // maxi and mini variables to store // the maximum and minimum degree int maxi = 0; int mini = n; for (int i = 1; i <= n; i++) { maxi = Math.max(maxi, m.get(i)); mini = Math.min(mini, m.get(i)); } // Printing all the nodes with maximum degree System.out.print(\"Nodes with maximum degree : \"); for (int i = 1; i <= n; i++) { if (m.get(i) == maxi) System.out.print(i + \" \"); } System.out.println(); // Printing all the nodes with minimum degree System.out.print(\"Nodes with minimum degree : \"); for (int i = 1; i <= n; i++) { if (m.get(i) == mini) System.out.print(i + \" \"); }} // Driver codepublic static void main(String[] args){ // Count of nodes and edges int n = 4, m = 6; // The edge list int edges[][] = {{ 1, 2 }, { 1, 3 }, { 1, 4 }, { 2, 3 }, { 2, 4 }, { 3, 4 }}; minMax(edges, m, 4);}} // This code is contributed by PrinciRaj1992", "e": 3972, "s": 2185, "text": null }, { "code": "# Python3 implementation of the approach # Function to print the nodes having# maximum and minimum degreedef minMax(edges, leng, n) : # Map to store the degrees of every node m = {}; for i in range(leng) : m[edges[i][0]] = 0; m[edges[i][1]] = 0; for i in range(leng) : # Storing the degree for each node m[edges[i][0]] += 1; m[edges[i][1]] += 1; # maxi and mini variables to store # the maximum and minimum degree maxi = 0; mini = n; for i in range(1, n + 1) : maxi = max(maxi, m[i]); mini = min(mini, m[i]); # Printing all the nodes # with maximum degree print(\"Nodes with maximum degree : \", end = \"\") for i in range(1, n + 1) : if (m[i] == maxi) : print(i, end = \" \"); print() # Printing all the nodes # with minimum degree print(\"Nodes with minimum degree : \", end = \"\") for i in range(1, n + 1) : if (m[i] == mini) : print(i, end = \" \"); # Driver codeif __name__ == \"__main__\" : # Count of nodes and edges n = 4; m = 6; # The edge list edges = [[ 1, 2 ], [ 1, 3 ], [ 1, 4 ], [ 2, 3 ], [ 2, 4 ], [ 3, 4 ]]; minMax(edges, m, 4); # This code is contributed by AnkitRai01", "e": 5327, "s": 3972, "text": null }, { "code": "// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // Function to print the nodes having// maximum and minimum degreestatic void minMax(int [,]edges, int len, int n){ // Map to store the degrees of every node Dictionary<int, int> m = new Dictionary<int, int>(); for (int i = 0; i < len; i++) { // Storing the degree for each node if(m.ContainsKey(edges[i, 0])) { m[edges[i, 0]] = m[edges[i, 0]] + 1; } else { m.Add(edges[i, 0], 1); } if(m.ContainsKey(edges[i, 1])) { m[edges[i, 1]] = m[edges[i, 1]] + 1; } else { m.Add(edges[i, 1], 1); } } // maxi and mini variables to store // the maximum and minimum degree int maxi = 0; int mini = n; for (int i = 1; i <= n; i++) { maxi = Math.Max(maxi, m[i]); mini = Math.Min(mini, m[i]); } // Printing all the nodes with maximum degree Console.Write(\"Nodes with maximum degree : \"); for (int i = 1; i <= n; i++) { if (m[i] == maxi) Console.Write(i + \" \"); } Console.WriteLine(); // Printing all the nodes with minimum degree Console.Write(\"Nodes with minimum degree : \"); for (int i = 1; i <= n; i++) { if (m[i] == mini) Console.Write(i + \" \"); }} // Driver codepublic static void Main(String[] args){ // Count of nodes and edges int m = 6; // The edge list int [,]edges = {{ 1, 2 }, { 1, 3 }, { 1, 4 }, { 2, 3 }, { 2, 4 }, { 3, 4 }}; minMax(edges, m, 4);}} // This code is contributed by 29AjayKumar", "e": 7026, "s": 5327, "text": null }, { "code": null, "e": 7099, "s": 7026, "text": "Nodes with maximum degree : 1 2 3 4 \nNodes with minimum degree : 1 2 3 4" }, { "code": null, "e": 7158, "s": 7101, "text": "Time Complexity: O(M*logN + N). Auxiliary Space: O(N). " }, { "code": null, "e": 7166, "s": 7158, "text": "ankthon" }, { "code": null, "e": 7180, "s": 7166, "text": "princiraj1992" }, { "code": null, "e": 7192, "s": 7180, "text": "29AjayKumar" }, { "code": null, "e": 7208, "s": 7192, "text": "pankajsharmagfg" }, { "code": null, "e": 7232, "s": 7208, "text": "Competitive Programming" }, { "code": null, "e": 7248, "s": 7232, "text": "Data Structures" }, { "code": null, "e": 7254, "s": 7248, "text": "Graph" }, { "code": null, "e": 7270, "s": 7254, "text": "Data Structures" }, { "code": null, "e": 7276, "s": 7270, "text": "Graph" }, { "code": null, "e": 7374, "s": 7276, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7452, "s": 7374, "text": "Count of strings whose prefix match with the given string to a given length k" }, { "code": null, "e": 7486, "s": 7452, "text": "Most important type of Algorithms" }, { "code": null, "e": 7524, "s": 7486, "text": "The Ultimate Beginner's Guide For DSA" }, { "code": null, "e": 7564, "s": 7524, "text": "Find two numbers from their sum and XOR" }, { "code": null, "e": 7623, "s": 7564, "text": "C++: Methods of code shortening in competitive programming" }, { "code": null, "e": 7648, "s": 7623, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 7697, "s": 7648, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 7741, "s": 7697, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 7773, "s": 7741, "text": "Introduction to Data Structures" } ]
Complete the sequence generated by a polynomial
27 Jul, 2021 Given a sequence with some of its term, we need to calculate next K term of this sequence. It is given that sequence is generated by some polynomial, however complex that polynomial can be. Notice polynomial is an expression of the following form: P(x) = a0 + a1 x +a2 x^2 + a3 x^3 ........ + an x^nThe given sequence can always be described by a number of polynomials, among these polynomial we need to find polynomial with lowest degree and generate next terms using this polynomial only. Examples: If given sequence is 1, 2, 3, 4, 5 then its next term will be 6, 7, 8, etc and this correspond to a trivial polynomial. If given sequence is 1, 4, 7, 10 then its next term will be 13, 16, etc. We can solve this problem using a technique called difference of differences method, which is derivable from lagrange polynomial. The technique is simple, we take the difference between the consecutive terms, if difference are equal then we stop and build up next term of the sequence otherwise we again take the difference between these differences until they become constant. The technique is explained in below diagram with an example, given sequence is 8, 11, 16, 23 and we are suppose to find next 3 terms of this sequence. In below, code same technique is implemented, first we loop until we get a constant difference keeping first number of each difference sequence in a separate vector for rebuilding the sequence again. Then we add K instance of same constant difference to our array for generating new K term of sequence and we follow same procedure in reverse order to rebuild the sequence. See the below code for a better understanding. C++ Java Python3 C# Javascript // C++ code to generate next terms of a given polynomial// sequence#include <bits/stdc++.h>using namespace std; // method to print next terms term of sequencevoid nextTermsInSequence(int sequence[], int N, int terms){ int diff[N + terms]; // first copy the sequence itself into diff array for (int i = 0; i < N; i++) diff[i] = sequence[i]; bool more = false; vector<int> first; int len = N; // loop until one difference remains or all // difference become constant while (len > 1) { // keeping the first term of sequence for // later rebuilding first.push_back(diff[0]); len--; // converting the difference to difference // of differences for (int i = 0; i < len; i++) diff[i] = diff[i + 1] - diff[i]; // checking if all difference values are // same or not int i; for (i = 1; i < len; i++) if (diff[i] != diff[i - 1]) break; // If some difference values were not same if (i != len) break; } int iteration = N - len; // padding terms instance of constant difference // at the end of array for (int i = len; i < len + terms; i++) diff[i] = diff[i - 1]; len += terms; // iterating to get actual sequence back for (int i = 0; i < iteration; i++) { len++; // shifting all difference by one place for (int j = len - 1; j > 0; j--) diff[j] = diff[j - 1]; // copying actual first element diff[0] = first[first.size() - i - 1]; // converting difference of differences to // difference array for (int j = 1; j < len; j++) diff[j] = diff[j - 1] + diff[j]; } // printing the result for (int i = 0; i < len; i++) cout << diff[i] << " "; cout << endl;} // Driver code to test above methodint main(){ int sequence[] = {8, 11, 16, 23}; int N = sizeof(sequence) / sizeof(int); int terms = 3; nextTermsInSequence(sequence, N, terms); return 0;} // Java code to generate next terms// of a given polynomial sequenceimport java.util.*; class GFG{ // Method to print next terms term of sequencestatic void nextTermsInSequence(int []sequence, int N, int terms){ int []diff = new int[N + terms]; // First copy the sequence itself // into diff array for(int i = 0; i < N; i++) diff[i] = sequence[i]; //bool more = false; ArrayList<Object> first = new ArrayList<Object>(); int len = N; // Loop until one difference remains // or all difference become constant while (len > 1) { // Keeping the first term of // sequence for later rebuilding first.add(diff[0]); len--; // Converting the difference to // difference of differences for(int i = 0; i < len; i++) diff[i] = diff[i + 1] - diff[i]; // Checking if all difference values // are same or not int j; for(j = 1; j < len; j++) if (diff[j] != diff[j - 1]) break; // If some difference values // were not same if (j != len) break; } int iteration = N - len; // Padding terms instance of constant // difference at the end of array for(int i = len; i < len + terms; i++) diff[i] = diff[i - 1]; len += terms; // Iterating to get actual sequence back for(int i = 0; i < iteration; i++) { len++; // Shifting all difference by one place for(int j = len - 1; j > 0; j--) diff[j] = diff[j - 1]; // Copying actual first element diff[0] = (int)first.get(first.size() - i - 1); // Converting difference of differences // to difference array for(int j = 1; j < len; j++) diff[j] = diff[j - 1] + diff[j]; } // Printing the result for(int i = 0; i < len; i++) { System.out.print(diff[i] + " "); } System.out.println();} // Driver Codepublic static void main(String[] args){ int []sequence = { 8, 11, 16, 23 }; int N = sequence.length; int terms = 3; nextTermsInSequence(sequence, N, terms);}} // This code is contributed by pratham76 # Python3 code to generate next terms# of a given polynomial sequence # Method to print next terms term of sequencedef nextTermsInSequence(sequence, N, terms): diff = [0] * (N + terms) # First copy the sequence itself # into diff array for i in range(N): diff[i] = sequence[i] more = False first = [] length = N # Loop until one difference remains # or all difference become constant while (length > 1): # Keeping the first term of sequence # for later rebuilding first.append(diff[0]) length -= 1 # Converting the difference to difference # of differences for i in range(length): diff[i] = diff[i + 1] - diff[i] # Checking if all difference values are # same or not for i in range(1, length): if (diff[i] != diff[i - 1]): break # If some difference values # were not same if (i != length): break iteration = N - length # Padding terms instance of constant # difference at the end of array for i in range(length, length + terms): diff[i] = diff[i - 1] length += terms # Iterating to get actual sequence back for i in range(iteration): length += 1 # Shifting all difference by one place for j in range(length - 1, -1, -1): diff[j] = diff[j - 1] # Copying actual first element diff[0] = first[len(first) - i - 1] # Converting difference of differences to # difference array for j in range(1, length): diff[j] = diff[j - 1] + diff[j] # Printing the result for i in range(length): print(diff[i], end = " ") print () # Driver codeif __name__ == "__main__": sequence = [ 8, 11, 16, 23 ] N = len(sequence) terms = 3 nextTermsInSequence(sequence, N, terms) # This code is contributed by chitranayal // C# code to generate next terms// of a given polynomial sequenceusing System;using System.Collections;class GFG{ // Method to print next terms term of sequencestatic void nextTermsInSequence(int []sequence, int N, int terms){ int []diff = new int[N + terms]; // First copy the sequence itself // into diff array for(int i = 0; i < N; i++) diff[i] = sequence[i]; //bool more = false; ArrayList first = new ArrayList(); int len = N; // Loop until one difference remains // or all difference become constant while (len > 1) { // Keeping the first term of // sequence for later rebuilding first.Add(diff[0]); len--; // Converting the difference to // difference of differences for(int i = 0; i < len; i++) diff[i] = diff[i + 1] - diff[i]; // Checking if all difference values // are same or not int j; for(j = 1; j < len; j++) if (diff[j] != diff[j - 1]) break; // If some difference values // were not same if (j != len) break; } int iteration = N - len; // Padding terms instance of constant // difference at the end of array for(int i = len; i < len + terms; i++) diff[i] = diff[i - 1]; len += terms; // Iterating to get actual sequence back for(int i = 0; i < iteration; i++) { len++; // Shifting all difference by one place for(int j = len - 1; j > 0; j--) diff[j] = diff[j - 1]; // Copying actual first element diff[0] = (int)first[first.Count - i - 1]; // Converting difference of differences // to difference array for(int j = 1; j < len; j++) diff[j] = diff[j - 1] + diff[j]; } // Printing the result for(int i = 0; i < len; i++) { Console.Write(diff[i] + " "); } Console.Write("\n");} // Driver Codepublic static void Main(string[] args){ int []sequence = { 8, 11, 16, 23 }; int N = sequence.Length; int terms = 3; nextTermsInSequence(sequence, N, terms);}} // This code is contributed by rutvik_56 <script> // Javascript code to generate next terms// of a given polynomial sequence // Method to print next terms term of sequence function nextTermsInSequence(sequence, N,terms) { let diff = new Array(N + terms); // First copy the sequence itself // into diff array for(let i = 0; i < N; i++) diff[i] = sequence[i]; //bool more = false; let first=[]; let len = N; // Loop until one difference remains // or all difference become constant while (len > 1) { // Keeping the first term of // sequence for later rebuilding first.push(diff[0]); len--; // Converting the difference to // difference of differences for(let i = 0; i < len; i++) diff[i] = diff[i + 1] - diff[i]; // Checking if all difference values // are same or not let j; for(j = 1; j < len; j++) if (diff[j] != diff[j - 1]) break; // If some difference values // were not same if (j != len) break; } let iteration = N - len; // Padding terms instance of constant // difference at the end of array for(let i = len; i < len + terms; i++) diff[i] = diff[i - 1]; len += terms; // Iterating to get actual sequence back for(let i = 0; i < iteration; i++) { len++; // Shifting all difference by one place for(let j = len - 1; j > 0; j--) diff[j] = diff[j - 1]; // Copying actual first element diff[0] = first[first.length - i - 1]; // Converting difference of differences // to difference array for(let j = 1; j < len; j++) diff[j] = diff[j - 1] + diff[j]; } // Printing the result for(let i = 0; i < len; i++) { document.write(diff[i] + " "); } document.write("<br>"); } // Driver Code let sequence=[8, 11, 16, 23]; let N = sequence.length; let terms = 3; nextTermsInSequence(sequence, N, terms); // This code is contributed by avanitrachhadiya2155 </script> Output: 8 11 16 23 30 37 44 This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. ukasp rutvik_56 pratham76 avanitrachhadiya2155 sooda367 maths-polynomial Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n27 Jul, 2021" }, { "code": null, "e": 544, "s": 52, "text": "Given a sequence with some of its term, we need to calculate next K term of this sequence. It is given that sequence is generated by some polynomial, however complex that polynomial can be. Notice polynomial is an expression of the following form: P(x) = a0 + a1 x +a2 x^2 + a3 x^3 ........ + an x^nThe given sequence can always be described by a number of polynomials, among these polynomial we need to find polynomial with lowest degree and generate next terms using this polynomial only. " }, { "code": null, "e": 554, "s": 544, "text": "Examples:" }, { "code": null, "e": 747, "s": 554, "text": "If given sequence is 1, 2, 3, 4, 5 then its next term will be 6, 7, 8, etc\nand this correspond to a trivial polynomial.\nIf given sequence is 1, 4, 7, 10 then its next term will be 13, 16, etc." }, { "code": null, "e": 878, "s": 747, "text": "We can solve this problem using a technique called difference of differences method, which is derivable from lagrange polynomial. " }, { "code": null, "e": 1277, "s": 878, "text": "The technique is simple, we take the difference between the consecutive terms, if difference are equal then we stop and build up next term of the sequence otherwise we again take the difference between these differences until they become constant. The technique is explained in below diagram with an example, given sequence is 8, 11, 16, 23 and we are suppose to find next 3 terms of this sequence." }, { "code": null, "e": 1651, "s": 1277, "text": "In below, code same technique is implemented, first we loop until we get a constant difference keeping first number of each difference sequence in a separate vector for rebuilding the sequence again. Then we add K instance of same constant difference to our array for generating new K term of sequence and we follow same procedure in reverse order to rebuild the sequence. " }, { "code": null, "e": 1698, "s": 1651, "text": "See the below code for a better understanding." }, { "code": null, "e": 1702, "s": 1698, "text": "C++" }, { "code": null, "e": 1707, "s": 1702, "text": "Java" }, { "code": null, "e": 1715, "s": 1707, "text": "Python3" }, { "code": null, "e": 1718, "s": 1715, "text": "C#" }, { "code": null, "e": 1729, "s": 1718, "text": "Javascript" }, { "code": "// C++ code to generate next terms of a given polynomial// sequence#include <bits/stdc++.h>using namespace std; // method to print next terms term of sequencevoid nextTermsInSequence(int sequence[], int N, int terms){ int diff[N + terms]; // first copy the sequence itself into diff array for (int i = 0; i < N; i++) diff[i] = sequence[i]; bool more = false; vector<int> first; int len = N; // loop until one difference remains or all // difference become constant while (len > 1) { // keeping the first term of sequence for // later rebuilding first.push_back(diff[0]); len--; // converting the difference to difference // of differences for (int i = 0; i < len; i++) diff[i] = diff[i + 1] - diff[i]; // checking if all difference values are // same or not int i; for (i = 1; i < len; i++) if (diff[i] != diff[i - 1]) break; // If some difference values were not same if (i != len) break; } int iteration = N - len; // padding terms instance of constant difference // at the end of array for (int i = len; i < len + terms; i++) diff[i] = diff[i - 1]; len += terms; // iterating to get actual sequence back for (int i = 0; i < iteration; i++) { len++; // shifting all difference by one place for (int j = len - 1; j > 0; j--) diff[j] = diff[j - 1]; // copying actual first element diff[0] = first[first.size() - i - 1]; // converting difference of differences to // difference array for (int j = 1; j < len; j++) diff[j] = diff[j - 1] + diff[j]; } // printing the result for (int i = 0; i < len; i++) cout << diff[i] << \" \"; cout << endl;} // Driver code to test above methodint main(){ int sequence[] = {8, 11, 16, 23}; int N = sizeof(sequence) / sizeof(int); int terms = 3; nextTermsInSequence(sequence, N, terms); return 0;}", "e": 3800, "s": 1729, "text": null }, { "code": "// Java code to generate next terms// of a given polynomial sequenceimport java.util.*; class GFG{ // Method to print next terms term of sequencestatic void nextTermsInSequence(int []sequence, int N, int terms){ int []diff = new int[N + terms]; // First copy the sequence itself // into diff array for(int i = 0; i < N; i++) diff[i] = sequence[i]; //bool more = false; ArrayList<Object> first = new ArrayList<Object>(); int len = N; // Loop until one difference remains // or all difference become constant while (len > 1) { // Keeping the first term of // sequence for later rebuilding first.add(diff[0]); len--; // Converting the difference to // difference of differences for(int i = 0; i < len; i++) diff[i] = diff[i + 1] - diff[i]; // Checking if all difference values // are same or not int j; for(j = 1; j < len; j++) if (diff[j] != diff[j - 1]) break; // If some difference values // were not same if (j != len) break; } int iteration = N - len; // Padding terms instance of constant // difference at the end of array for(int i = len; i < len + terms; i++) diff[i] = diff[i - 1]; len += terms; // Iterating to get actual sequence back for(int i = 0; i < iteration; i++) { len++; // Shifting all difference by one place for(int j = len - 1; j > 0; j--) diff[j] = diff[j - 1]; // Copying actual first element diff[0] = (int)first.get(first.size() - i - 1); // Converting difference of differences // to difference array for(int j = 1; j < len; j++) diff[j] = diff[j - 1] + diff[j]; } // Printing the result for(int i = 0; i < len; i++) { System.out.print(diff[i] + \" \"); } System.out.println();} // Driver Codepublic static void main(String[] args){ int []sequence = { 8, 11, 16, 23 }; int N = sequence.length; int terms = 3; nextTermsInSequence(sequence, N, terms);}} // This code is contributed by pratham76", "e": 6059, "s": 3800, "text": null }, { "code": "# Python3 code to generate next terms# of a given polynomial sequence # Method to print next terms term of sequencedef nextTermsInSequence(sequence, N, terms): diff = [0] * (N + terms) # First copy the sequence itself # into diff array for i in range(N): diff[i] = sequence[i] more = False first = [] length = N # Loop until one difference remains # or all difference become constant while (length > 1): # Keeping the first term of sequence # for later rebuilding first.append(diff[0]) length -= 1 # Converting the difference to difference # of differences for i in range(length): diff[i] = diff[i + 1] - diff[i] # Checking if all difference values are # same or not for i in range(1, length): if (diff[i] != diff[i - 1]): break # If some difference values # were not same if (i != length): break iteration = N - length # Padding terms instance of constant # difference at the end of array for i in range(length, length + terms): diff[i] = diff[i - 1] length += terms # Iterating to get actual sequence back for i in range(iteration): length += 1 # Shifting all difference by one place for j in range(length - 1, -1, -1): diff[j] = diff[j - 1] # Copying actual first element diff[0] = first[len(first) - i - 1] # Converting difference of differences to # difference array for j in range(1, length): diff[j] = diff[j - 1] + diff[j] # Printing the result for i in range(length): print(diff[i], end = \" \") print () # Driver codeif __name__ == \"__main__\": sequence = [ 8, 11, 16, 23 ] N = len(sequence) terms = 3 nextTermsInSequence(sequence, N, terms) # This code is contributed by chitranayal", "e": 8003, "s": 6059, "text": null }, { "code": "// C# code to generate next terms// of a given polynomial sequenceusing System;using System.Collections;class GFG{ // Method to print next terms term of sequencestatic void nextTermsInSequence(int []sequence, int N, int terms){ int []diff = new int[N + terms]; // First copy the sequence itself // into diff array for(int i = 0; i < N; i++) diff[i] = sequence[i]; //bool more = false; ArrayList first = new ArrayList(); int len = N; // Loop until one difference remains // or all difference become constant while (len > 1) { // Keeping the first term of // sequence for later rebuilding first.Add(diff[0]); len--; // Converting the difference to // difference of differences for(int i = 0; i < len; i++) diff[i] = diff[i + 1] - diff[i]; // Checking if all difference values // are same or not int j; for(j = 1; j < len; j++) if (diff[j] != diff[j - 1]) break; // If some difference values // were not same if (j != len) break; } int iteration = N - len; // Padding terms instance of constant // difference at the end of array for(int i = len; i < len + terms; i++) diff[i] = diff[i - 1]; len += terms; // Iterating to get actual sequence back for(int i = 0; i < iteration; i++) { len++; // Shifting all difference by one place for(int j = len - 1; j > 0; j--) diff[j] = diff[j - 1]; // Copying actual first element diff[0] = (int)first[first.Count - i - 1]; // Converting difference of differences // to difference array for(int j = 1; j < len; j++) diff[j] = diff[j - 1] + diff[j]; } // Printing the result for(int i = 0; i < len; i++) { Console.Write(diff[i] + \" \"); } Console.Write(\"\\n\");} // Driver Codepublic static void Main(string[] args){ int []sequence = { 8, 11, 16, 23 }; int N = sequence.Length; int terms = 3; nextTermsInSequence(sequence, N, terms);}} // This code is contributed by rutvik_56", "e": 10233, "s": 8003, "text": null }, { "code": "<script> // Javascript code to generate next terms// of a given polynomial sequence // Method to print next terms term of sequence function nextTermsInSequence(sequence, N,terms) { let diff = new Array(N + terms); // First copy the sequence itself // into diff array for(let i = 0; i < N; i++) diff[i] = sequence[i]; //bool more = false; let first=[]; let len = N; // Loop until one difference remains // or all difference become constant while (len > 1) { // Keeping the first term of // sequence for later rebuilding first.push(diff[0]); len--; // Converting the difference to // difference of differences for(let i = 0; i < len; i++) diff[i] = diff[i + 1] - diff[i]; // Checking if all difference values // are same or not let j; for(j = 1; j < len; j++) if (diff[j] != diff[j - 1]) break; // If some difference values // were not same if (j != len) break; } let iteration = N - len; // Padding terms instance of constant // difference at the end of array for(let i = len; i < len + terms; i++) diff[i] = diff[i - 1]; len += terms; // Iterating to get actual sequence back for(let i = 0; i < iteration; i++) { len++; // Shifting all difference by one place for(let j = len - 1; j > 0; j--) diff[j] = diff[j - 1]; // Copying actual first element diff[0] = first[first.length - i - 1]; // Converting difference of differences // to difference array for(let j = 1; j < len; j++) diff[j] = diff[j - 1] + diff[j]; } // Printing the result for(let i = 0; i < len; i++) { document.write(diff[i] + \" \"); } document.write(\"<br>\"); } // Driver Code let sequence=[8, 11, 16, 23]; let N = sequence.length; let terms = 3; nextTermsInSequence(sequence, N, terms); // This code is contributed by avanitrachhadiya2155 </script>", "e": 12674, "s": 10233, "text": null }, { "code": null, "e": 12682, "s": 12674, "text": "Output:" }, { "code": null, "e": 12702, "s": 12682, "text": "8 11 16 23 30 37 44" }, { "code": null, "e": 13126, "s": 12702, "text": "This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 13132, "s": 13126, "text": "ukasp" }, { "code": null, "e": 13142, "s": 13132, "text": "rutvik_56" }, { "code": null, "e": 13152, "s": 13142, "text": "pratham76" }, { "code": null, "e": 13173, "s": 13152, "text": "avanitrachhadiya2155" }, { "code": null, "e": 13182, "s": 13173, "text": "sooda367" }, { "code": null, "e": 13199, "s": 13182, "text": "maths-polynomial" }, { "code": null, "e": 13212, "s": 13199, "text": "Mathematical" }, { "code": null, "e": 13225, "s": 13212, "text": "Mathematical" } ]
Tailwind CSS vs Bootstrap
02 Nov, 2021 Tailwind CSS was initially developed by Adam Wathan, and the first version was released back on the 1st of November, 2017. Tailwind CSS is a utility-first CSS framework for building custom user interfaces rapidly and efficiently. It is an inline styling used to achieve a sleek interface without writing code for your own CSS. Tailwind CSS offers customizability and flexibility to transform the appearance and feel of the elements. Tailwind CSS is not the first utility-first CSS library, but it is one of the most popular and light ones. It is a highly customizable, low-level CSS framework, and it provides all the building blocks the developer needs to build a fantastic interface for any website. CDN link: <link href=”https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css” rel=”stylesheet”> Sample page made using Tailwind CSS: HTML <!DOCTYPE html><html> <head> <!-- Tailwind CSS --> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> <title>Tailwind CSS</title></head> <body style="background-color: gray;"> <!--Card 1--> <div class=" w-full lg:max-w-full lg:flex"> <div class="border-r border-b border-l border-gray-400 lg:border-l-0 lg:border-t lg:border-gray-400 bg-white \rounded-b lg:rounded-b-none lg:rounded-r p-4 leading-normal"> <p class="text-gray-700 text-base"> This Card is made using Tailwind CSS. </p> </div> </div></body> </html> Output: Card made using Tailwind CSS Bootstrap was developed by Mark Otto and Jacob Thorton during an internal competition at Twitter in August 2011. It is an open-source framework that is used to design responsive websites better, faster, and easier. It is a beginner-friendly and the most popular open-source framework that includes HTML, CSS, and JavaScript. Bootstrap can be used to create web applications with any server-side Technology like Java, PHP, etc., and its responsive design allows platforms like Mobile phones, tablets, and computers. Bootstrap contains CSS and JavaScript-based design templates for typography, forms, buttons, navigation, icons, and other interface components. It is based on object-oriented CSS. Bootstrap helps to design and develop website templates quickly. CDN link: <link rel=”stylesheet” href=”https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css” integrity=”sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T” crossorigin=”anonymous”> Sample page made using BOOTSTRAP: HTML <!DOCTYPE html><html> <head> <!-- BOOTSTRAP --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <title>BOOTSTRAP</title></head> <body style="background-color: gray;"> <div class="card"> <div class="card-body"> This Card is made using BOOTSTRAP. </div> </div></body> </html> Output: Card made using BOOTSTRAP Different versions of Bootstrap: Version 2.0 supports responsive web design. Version 3.0 supports mobile-first design. Version 4.0 introduces SASS and Flexbox support. Tailwind CSS vs Bootstrap: Bootstrap-Questions CSS-Questions Picked Tailwind CSS Bootstrap CSS Difference Between Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to pass data into a bootstrap modal? How to Show Images on Click using HTML ? How to Use Bootstrap with React? How to set Bootstrap Timepicker using datetimepicker library ? Difference between Bootstrap 4 and Bootstrap 5 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": "\n02 Nov, 2021" }, { "code": null, "e": 730, "s": 28, "text": "Tailwind CSS was initially developed by Adam Wathan, and the first version was released back on the 1st of November, 2017. Tailwind CSS is a utility-first CSS framework for building custom user interfaces rapidly and efficiently. It is an inline styling used to achieve a sleek interface without writing code for your own CSS. Tailwind CSS offers customizability and flexibility to transform the appearance and feel of the elements. Tailwind CSS is not the first utility-first CSS library, but it is one of the most popular and light ones. It is a highly customizable, low-level CSS framework, and it provides all the building blocks the developer needs to build a fantastic interface for any website." }, { "code": null, "e": 740, "s": 730, "text": "CDN link:" }, { "code": null, "e": 828, "s": 740, "text": "<link href=”https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css” rel=”stylesheet”>" }, { "code": null, "e": 865, "s": 828, "text": "Sample page made using Tailwind CSS:" }, { "code": null, "e": 870, "s": 865, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <!-- Tailwind CSS --> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> <title>Tailwind CSS</title></head> <body style=\"background-color: gray;\"> <!--Card 1--> <div class=\" w-full lg:max-w-full lg:flex\"> <div class=\"border-r border-b border-l border-gray-400 lg:border-l-0 lg:border-t lg:border-gray-400 bg-white \\rounded-b lg:rounded-b-none lg:rounded-r p-4 leading-normal\"> <p class=\"text-gray-700 text-base\"> This Card is made using Tailwind CSS. </p> </div> </div></body> </html>", "e": 1548, "s": 870, "text": null }, { "code": null, "e": 1556, "s": 1548, "text": "Output:" }, { "code": null, "e": 1585, "s": 1556, "text": "Card made using Tailwind CSS" }, { "code": null, "e": 2345, "s": 1585, "text": "Bootstrap was developed by Mark Otto and Jacob Thorton during an internal competition at Twitter in August 2011. It is an open-source framework that is used to design responsive websites better, faster, and easier. It is a beginner-friendly and the most popular open-source framework that includes HTML, CSS, and JavaScript. Bootstrap can be used to create web applications with any server-side Technology like Java, PHP, etc., and its responsive design allows platforms like Mobile phones, tablets, and computers. Bootstrap contains CSS and JavaScript-based design templates for typography, forms, buttons, navigation, icons, and other interface components. It is based on object-oriented CSS. Bootstrap helps to design and develop website templates quickly." }, { "code": null, "e": 2355, "s": 2345, "text": "CDN link:" }, { "code": null, "e": 2567, "s": 2355, "text": "<link rel=”stylesheet” href=”https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css” integrity=”sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T” crossorigin=”anonymous”>" }, { "code": null, "e": 2601, "s": 2567, "text": "Sample page made using BOOTSTRAP:" }, { "code": null, "e": 2606, "s": 2601, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <!-- BOOTSTRAP --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\" integrity=\"sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T\" crossorigin=\"anonymous\"> <title>BOOTSTRAP</title></head> <body style=\"background-color: gray;\"> <div class=\"card\"> <div class=\"card-body\"> This Card is made using BOOTSTRAP. </div> </div></body> </html>", "e": 3101, "s": 2606, "text": null }, { "code": null, "e": 3109, "s": 3101, "text": "Output:" }, { "code": null, "e": 3135, "s": 3109, "text": "Card made using BOOTSTRAP" }, { "code": null, "e": 3170, "s": 3135, "text": "Different versions of Bootstrap: " }, { "code": null, "e": 3214, "s": 3170, "text": "Version 2.0 supports responsive web design." }, { "code": null, "e": 3256, "s": 3214, "text": "Version 3.0 supports mobile-first design." }, { "code": null, "e": 3305, "s": 3256, "text": "Version 4.0 introduces SASS and Flexbox support." }, { "code": null, "e": 3332, "s": 3305, "text": "Tailwind CSS vs Bootstrap:" }, { "code": null, "e": 3352, "s": 3332, "text": "Bootstrap-Questions" }, { "code": null, "e": 3366, "s": 3352, "text": "CSS-Questions" }, { "code": null, "e": 3373, "s": 3366, "text": "Picked" }, { "code": null, "e": 3386, "s": 3373, "text": "Tailwind CSS" }, { "code": null, "e": 3396, "s": 3386, "text": "Bootstrap" }, { "code": null, "e": 3400, "s": 3396, "text": "CSS" }, { "code": null, "e": 3419, "s": 3400, "text": "Difference Between" }, { "code": null, "e": 3436, "s": 3419, "text": "Web Technologies" }, { "code": null, "e": 3534, "s": 3436, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3575, "s": 3534, "text": "How to pass data into a bootstrap modal?" }, { "code": null, "e": 3616, "s": 3575, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 3649, "s": 3616, "text": "How to Use Bootstrap with React?" }, { "code": null, "e": 3712, "s": 3649, "text": "How to set Bootstrap Timepicker using datetimepicker library ?" }, { "code": null, "e": 3759, "s": 3712, "text": "Difference between Bootstrap 4 and Bootstrap 5" }, { "code": null, "e": 3807, "s": 3759, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 3869, "s": 3807, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3919, "s": 3869, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 3977, "s": 3919, "text": "How to create footer to stay at the bottom of a Web page?" } ]
Python | Pandas dataframe.bfill()
13 Feb, 2020 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas dataframe.bfill() is used to backward fill the missing values in the dataset. It will backward fill the NaN values that are present in the pandas dataframe. Syntax: DataFrame.bfill(axis=None, inplace=False, limit=None, downcast=None) Parameters:axis : ‘rows’ or ‘columns’inplace : boolean, default Falselimit : integer value, No. of consecutive na cells to be populated. Example #1: Use bfill() function to populate missing values na values in the dataframe across rows. # importing pandas as pdimport pandas as pd # Creating a dataframe with "na" values. df = pd.DataFrame({"A":[None, 1, 2, 3, None, None], "B":[11, 5, None, None, None, 8], "C":[None, 5, 10, 11, None, 8]}) # Printing the dataframedf When axis='rows', then value in current na cells are filled from the corresponding value in the next row. If the next row is also na value then it won’t be populated. # Fill across the rowdf.bfill(axis ='rows') Output : Example #2: Use bfill() function to populate missing values na values in the dataframe across columns. when axis='columns', then the current na cells will be filled from the value present in the next column in the same row. If the next column is also na cell then it won’t be filled. # importing pandas as pdimport pandas as pd # Creating a dataframe with "na" values. df = pd.DataFrame({"A":[None, 1, 2, 3, None, None], "B":[11, 5, None, None, None, 8], "C":[None, 5, 10, 11, None, 8]}) # bfill values using values from next columndf.bfill(axis ='columns') Output : Notice the 4th row. All values are na because the rightmost cell was originally na and there is no cell to its right from which it can populate itself. So, it could not populate the previous na cells as well. smbrtprmnkreg Python pandas-dataFrame Python pandas-dataFrame-methods Python-pandas 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 Iterate over a list in Python Python Classes and Objects Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Feb, 2020" }, { "code": null, "e": 242, "s": 28, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 406, "s": 242, "text": "Pandas dataframe.bfill() is used to backward fill the missing values in the dataset. It will backward fill the NaN values that are present in the pandas dataframe." }, { "code": null, "e": 483, "s": 406, "text": "Syntax: DataFrame.bfill(axis=None, inplace=False, limit=None, downcast=None)" }, { "code": null, "e": 620, "s": 483, "text": "Parameters:axis : ‘rows’ or ‘columns’inplace : boolean, default Falselimit : integer value, No. of consecutive na cells to be populated." }, { "code": null, "e": 720, "s": 620, "text": "Example #1: Use bfill() function to populate missing values na values in the dataframe across rows." }, { "code": "# importing pandas as pdimport pandas as pd # Creating a dataframe with \"na\" values. df = pd.DataFrame({\"A\":[None, 1, 2, 3, None, None], \"B\":[11, 5, None, None, None, 8], \"C\":[None, 5, 10, 11, None, 8]}) # Printing the dataframedf", "e": 991, "s": 720, "text": null }, { "code": null, "e": 1158, "s": 991, "text": "When axis='rows', then value in current na cells are filled from the corresponding value in the next row. If the next row is also na value then it won’t be populated." }, { "code": "# Fill across the rowdf.bfill(axis ='rows')", "e": 1202, "s": 1158, "text": null }, { "code": null, "e": 1211, "s": 1202, "text": "Output :" }, { "code": null, "e": 1315, "s": 1211, "text": " Example #2: Use bfill() function to populate missing values na values in the dataframe across columns." }, { "code": null, "e": 1496, "s": 1315, "text": "when axis='columns', then the current na cells will be filled from the value present in the next column in the same row. If the next column is also na cell then it won’t be filled." }, { "code": "# importing pandas as pdimport pandas as pd # Creating a dataframe with \"na\" values. df = pd.DataFrame({\"A\":[None, 1, 2, 3, None, None], \"B\":[11, 5, None, None, None, 8], \"C\":[None, 5, 10, 11, None, 8]}) # bfill values using values from next columndf.bfill(axis ='columns')", "e": 1809, "s": 1496, "text": null }, { "code": null, "e": 1818, "s": 1809, "text": "Output :" }, { "code": null, "e": 2027, "s": 1818, "text": "Notice the 4th row. All values are na because the rightmost cell was originally na and there is no cell to its right from which it can populate itself. So, it could not populate the previous na cells as well." }, { "code": null, "e": 2041, "s": 2027, "text": "smbrtprmnkreg" }, { "code": null, "e": 2065, "s": 2041, "text": "Python pandas-dataFrame" }, { "code": null, "e": 2097, "s": 2065, "text": "Python pandas-dataFrame-methods" }, { "code": null, "e": 2111, "s": 2097, "text": "Python-pandas" }, { "code": null, "e": 2118, "s": 2111, "text": "Python" }, { "code": null, "e": 2216, "s": 2118, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2234, "s": 2216, "text": "Python Dictionary" }, { "code": null, "e": 2276, "s": 2234, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2298, "s": 2276, "text": "Enumerate() in Python" }, { "code": null, "e": 2333, "s": 2298, "text": "Read a file line by line in Python" }, { "code": null, "e": 2359, "s": 2333, "text": "Python String | replace()" }, { "code": null, "e": 2391, "s": 2359, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2420, "s": 2391, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2450, "s": 2420, "text": "Iterate over a list in Python" }, { "code": null, "e": 2477, "s": 2450, "text": "Python Classes and Objects" } ]
Minimum Index Sum for Common Elements of Two Lists
14 Mar, 2022 Ram and Shyam want to choose a website to learn programming and they both have a list of favorite websites represented by strings.You need to help them find out their common interest with the least index sum. If there is a choice tie between answers, print all of them with no order requirement. Assume there always exists an answer. Examples: Input : ["GeeksforGeeks", "Udemy", "Coursera", "edX"] ["Codecademy", "Khan Academy", "GeeksforGeeks"] Output : "GeeksforGeeks" Explanation : GeeksforGeeks is the only common website in two lists Input : ["Udemy", "GeeksforGeeks", "Coursera", "edX"] ["GeeksforGeeks", "Udemy", "Khan Academy", "Udacity"] Output : "GeeksforGeeks" "Udemy" Explanation : There are two common websites and index sum of both is same. Naive Method: The idea is to try all index sums from 0 to sum of sizes. For every sum, check if there are pairs with given sum. Once we find one or more pairs, we print them and return. C++ Java Python3 C# Javascript #include <bits/stdc++.h>using namespace std; // Function to print common strings with minimum index sumvoid find(vector<string> list1, vector<string> list2){ vector<string> res; // resultant list int max_possible_sum = list1.size() + list2.size() - 2; // iterating over sum in ascending order for (int sum = 0; sum <= max_possible_sum ; sum++) { // iterating over one list and check index // (Corresponding to given sum) in other list for (int i = 0; i <= sum; i++) // put common strings in resultant list if (i < list1.size() && (sum - i) < list2.size() && list1[i] == list2[sum - i]) res.push_back(list1[i]); // if common string found then break as we are // considering index sums in increasing order. if (res.size() > 0) break; } // print the resultant list for (int i = 0; i < res.size(); i++) cout << res[i] << " ";} // Driver codeint main(){ // Creating list1 vector<string> list1; list1.push_back("GeeksforGeeks"); list1.push_back("Udemy"); list1.push_back("Coursera"); list1.push_back("edX"); // Creating list2 vector<string> list2; list2.push_back("Codecademy"); list2.push_back("Khan Academy"); list2.push_back("GeeksforGeeks"); find(list1, list2); return 0;} import java.util.*; class GFG{ // Function to print common Strings with minimum index sumstatic void find(Vector<String> list1, Vector<String> list2){ Vector<String> res = new Vector<>(); // resultant list int max_possible_sum = list1.size() + list2.size() - 2; // iterating over sum in ascending order for (int sum = 0; sum <= max_possible_sum ; sum++) { // iterating over one list and check index // (Corresponding to given sum) in other list for (int i = 0; i <= sum; i++) // put common Strings in resultant list if (i < list1.size() && (sum - i) < list2.size() && list1.get(i) == list2.get(sum - i)) res.add(list1.get(i)); // if common String found then break as we are // considering index sums in increasing order. if (res.size() > 0) break; } // print the resultant list for (int i = 0; i < res.size(); i++) System.out.print(res.get(i)+" ");} // Driver codepublic static void main(String[] args){ // Creating list1 Vector<String> list1 = new Vector<>(); list1.add("GeeksforGeeks"); list1.add("Udemy"); list1.add("Coursera"); list1.add("edX"); // Creating list2 Vector<String> list2= new Vector<>(); list2.add("Codecademy"); list2.add("Khan Academy"); list2.add("GeeksforGeeks"); find(list1, list2); }} // This code contributed by Rajput-Ji # Function to print common strings# with minimum index sumdef find(list1, list2): res = [] # resultant list max_possible_sum = len(list1) + len(list2) - 2 # iterating over sum in ascending order for sum in range(max_possible_sum + 1): # iterating over one list and check index # (Corresponding to given sum) in other list for i in range(sum + 1): # put common strings in resultant list if (i < len(list1) and (sum - i) < len(list2) and list1[i] == list2[sum - i]): res.append(list1[i]) # if common string found then break as we are # considering index sums in increasing order. if (len(res) > 0): break # print the resultant list for i in range(len(res)): print(res[i], end = " ") # Driver code # Creating list1list1 = []list1.append("GeeksforGeeks")list1.append("Udemy")list1.append("Coursera")list1.append("edX") # Creating list2list2 = []list2.append("Codecademy")list2.append("Khan Academy")list2.append("GeeksforGeeks") find(list1, list2) # This code is contributed by Mohit Kumar using System;using System.Collections.Generic; class GFG{ // Function to print common Strings with minimum index sumstatic void find(List<String> list1, List<String> list2){ List<String> res = new List<String>(); // resultant list int max_possible_sum = list1.Count + list2.Count - 2; // iterating over sum in ascending order for (int sum = 0; sum <= max_possible_sum ; sum++) { // iterating over one list and check index // (Corresponding to given sum) in other list for (int i = 0; i <= sum; i++) // put common Strings in resultant list if (i < list1.Count && (sum - i) < list2.Count && list1[i] == list2[sum - i]) res.Add(list1[i]); // if common String found then break as we are // considering index sums in increasing order. if (res.Count > 0) break; } // print the resultant list for (int i = 0; i < res.Count; i++) Console.Write(res[i]+" ");} // Driver codepublic static void Main(String[] args){ // Creating list1 List<String> list1 = new List<String>(); list1.Add("GeeksforGeeks"); list1.Add("Udemy"); list1.Add("Coursera"); list1.Add("edX"); // Creating list2 List<String> list2= new List<String>(); list2.Add("Codecademy"); list2.Add("Khan Academy"); list2.Add("GeeksforGeeks"); find(list1, list2); }} // This code is contributed by 29AjayKumar <script> // Function to print common Strings with minimum index sum function find(list1, list2) { let res = []; // resultant list let max_possible_sum = list1.length + list2.length - 2; // iterating over sum in ascending order for (let sum = 0; sum <= max_possible_sum ; sum++) { // iterating over one list and check index // (Corresponding to given sum) in other list for (let i = 0; i <= sum; i++) // put common Strings in resultant list if (i < list1.length && (sum - i) < list2.length && list1[i] == list2[sum - i]) res.push(list1[i]); // if common String found then break as we are // considering index sums in increasing order. if (res.length > 0) break; } // print the resultant list for (let i = 0; i < res.length; i++) document.write(res[i]+" "); } // Creating list1 let list1 = []; list1.push("GeeksforGeeks"); list1.push("Udemy"); list1.push("Coursera"); list1.push("edX"); // Creating list2 let list2= []; list2.push("Codecademy"); list2.push("Khan Academy"); list2.push("GeeksforGeeks"); find(list1, list2); // This code is contributed by mukesh07.</script> Output: GeeksforGeeks Time Complexity : O((l1+l2)2 *x), where l1 and l2 are the lengths of list1 and list2 respectively and x refers to string length.Auxiliary Space : O(l*x), where x refers to length of resultant list and l is length of maximum size word. Using Hash: Traverse over the list1 and create an entry for index each element of list1 in a Hash Table.Traverse over list2 and for every element, check if the same element already exists as a key in the map. If so, it means that the element exists in both the lists.Find out the sum of indices corresponding to common element in the two lists. If this sum is lesser than the minimum sum obtained till now, update the resultant list.If the sum is equal to the minimum sum obtained till now, put an extra entry corresponding to the element in list2 in the resultant list. Traverse over the list1 and create an entry for index each element of list1 in a Hash Table. Traverse over list2 and for every element, check if the same element already exists as a key in the map. If so, it means that the element exists in both the lists. Find out the sum of indices corresponding to common element in the two lists. If this sum is lesser than the minimum sum obtained till now, update the resultant list. If the sum is equal to the minimum sum obtained till now, put an extra entry corresponding to the element in list2 in the resultant list. C++ Java Python3 C# Javascript // Hashing based C++ program to find common elements// with minimum index sum.#include <bits/stdc++.h>using namespace std; // Function to print common strings with minimum index sumvoid find(vector<string> list1, vector<string> list2){ // mapping strings to their indices unordered_map<string, int> map; for (int i = 0; i < list1.size(); i++) map[list1[i]] = i; vector<string> res; // resultant list int minsum = INT_MAX; for (int j = 0; j < list2.size(); j++) { if (map.count(list2[j])) { // If current sum is smaller than minsum int sum = j + map[list2[j]]; if (sum < minsum) { minsum = sum; res.clear(); res.push_back(list2[j]); } // if index sum is same then put this // string in resultant list as well else if (sum == minsum) res.push_back(list2[j]); } } // Print result for (int i = 0; i < res.size(); i++) cout << res[i] << " ";} // Driver codeint main(){ // Creating list1 vector<string> list1; list1.push_back("GeeksforGeeks"); list1.push_back("Udemy"); list1.push_back("Coursera"); list1.push_back("edX"); // Creating list2 vector<string> list2; list2.push_back("Codecademy"); list2.push_back("Khan Academy"); list2.push_back("GeeksforGeeks"); find(list1, list2); return 0;} // Hashing based Java program to find common elements// with minimum index sum.import java.util.*; class GFG{ // Function to print common Strings with minimum index sum static void find(Vector<String> list1, Vector<String> list2) { // mapping Strings to their indices Map<String, Integer> map = new HashMap<>(); for (int i = 0; i < list1.size(); i++) map.put(list1.get(i), i); Vector<String> res = new Vector<String>(); // resultant list int minsum = Integer.MAX_VALUE; for (int j = 0; j < list2.size(); j++) { if (map.containsKey(list2.get(j))) { // If current sum is smaller than minsum int sum = j + map.get(list2.get(j)); if (sum < minsum) { minsum = sum; res.clear(); res.add(list2.get(j)); } // if index sum is same then put this // String in resultant list as well else if (sum == minsum) res.add(list2.get(j)); } } // Print result for (int i = 0; i < res.size(); i++) System.out.print(res.get(i) + " "); } // Driver code public static void main(String[] args) { // Creating list1 Vector<String> list1 = new Vector<String>(); list1.add("GeeksforGeeks"); list1.add("Udemy"); list1.add("Coursera"); list1.add("edX"); // Creating list2 Vector<String> list2 = new Vector<String>(); list2.add("Codecademy"); list2.add("Khan Academy"); list2.add("GeeksforGeeks"); find(list1, list2); }} // This code is contributed by PrinciRaj1992 # Hashing based Python3 program to find# common elements with minimum index sumimport sys # Function to print common strings# with minimum index sumdef find(list1, list2): # Mapping strings to their indices Map = {} for i in range(len(list1)): Map[list1[i]] = i # Resultant list res = [] minsum = sys.maxsize for j in range(len(list2)): if list2[j] in Map: # If current sum is smaller # than minsum Sum = j + Map[list2[j]] if (Sum < minsum): minsum = Sum res.clear() res.append(list2[j]) # If index sum is same then put this # string in resultant list as well else if (Sum == minsum): res.append(list2[j]) # Print result print(*res, sep = " ") # Driver code # Creating list1list1 = []list1.append("GeeksforGeeks")list1.append("Udemy")list1.append("Coursera")list1.append("edX") # Creating list2list2 = []list2.append("Codecademy")list2.append("Khan Academy")list2.append("GeeksforGeeks")find(list1, list2) # This code is contributed by avanitrachhadiya2155 // Hashing based C# program to find common elements// with minimum index sum.using System;using System.Collections.Generic; class GFG{ // Function to print common Strings with minimum index sum static void find(List<String> list1, List<String> list2) { // mapping Strings to their indices Dictionary<String, int> map = new Dictionary<String, int>(); for (int i = 0; i < list1.Count; i++) map.Add(list1[i], i); List<String> res = new List<String>(); // resultant list int minsum = int.MaxValue; for (int j = 0; j < list2.Count; j++) { if (map.ContainsKey(list2[j])) { // If current sum is smaller than minsum int sum = j + map[list2[j]]; if (sum < minsum) { minsum = sum; res.Clear(); res.Add(list2[j]); } // if index sum is same then put this // String in resultant list as well else if (sum == minsum) res.Add(list2[j]); } } // Print result for (int i = 0; i < res.Count; i++) Console.Write(res[i] + " "); } // Driver code public static void Main(String[] args) { // Creating list1 List<String> list1 = new List<String>(); list1.Add("GeeksforGeeks"); list1.Add("Udemy"); list1.Add("Coursera"); list1.Add("edX"); // Creating list2 List<String> list2 = new List<String>(); list2.Add("Codecademy"); list2.Add("Khan Academy"); list2.Add("GeeksforGeeks"); find(list1, list2); }} // This code is contributed by Rajput-Ji <script> // Hashing based Javascript program to// find common elements with minimum// index sum. // Function to print common Strings// with minimum index sumfunction find(list1, list2){ // Mapping Strings to their indices let map = new Map(); for(let i = 0; i < list1.length; i++) map.set(list1[i], i); // Resultant list let res = []; let minsum = Number.MAX_VALUE; for(let j = 0; j < list2.length; j++) { if (map.has(list2[j])) { // If current sum is smaller than minsum let sum = j + map.get(list2[j]); if (sum < minsum) { minsum = sum; res = []; res.push(list2[j]); } // If index sum is same then put this // String in resultant list as well else if (sum == minsum) res.push(list2[j]); } } // Print result for(let i = 0; i < res.length; i++) document.write(res[i] + " ");} // Driver code // Creating list1let list1 = [];list1.push("GeeksforGeeks");list1.push("Udemy");list1.push("Coursera");list1.push("edX"); // Creating list2let list2 = [];list2.push("Codecademy");list2.push("Khan Academy");list2.push("GeeksforGeeks"); find(list1, list2); // This code is contributed by rameshtravel07 </script> Output: GeeksforGeeks Time Complexity : O(l1+l2), where l1 and l2 are the lengths of list1 and list2 respectively.Auxiliary Space : O(l1*x), where x refers to length of resultant list and l is length of maximum size word. This article is contributed by Aakash Pal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Rajput-Ji 29AjayKumar mohit kumar 29 princiraj1992 Code_Mech avanitrachhadiya2155 mukesh07 rameshtravel07 simmytarika5 cpp-unordered_map Hash Strings Hash Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n14 Mar, 2022" }, { "code": null, "e": 388, "s": 54, "text": "Ram and Shyam want to choose a website to learn programming and they both have a list of favorite websites represented by strings.You need to help them find out their common interest with the least index sum. If there is a choice tie between answers, print all of them with no order requirement. Assume there always exists an answer." }, { "code": null, "e": 398, "s": 388, "text": "Examples:" }, { "code": null, "e": 855, "s": 398, "text": "Input : [\"GeeksforGeeks\", \"Udemy\", \"Coursera\", \"edX\"]\n [\"Codecademy\", \"Khan Academy\", \"GeeksforGeeks\"]\nOutput : \"GeeksforGeeks\"\nExplanation : GeeksforGeeks is the only common website \n in two lists\n\nInput : [\"Udemy\", \"GeeksforGeeks\", \"Coursera\", \"edX\"]\n [\"GeeksforGeeks\", \"Udemy\", \"Khan Academy\", \"Udacity\"]\nOutput : \"GeeksforGeeks\" \"Udemy\"\nExplanation : There are two common websites and index sum\n of both is same." }, { "code": null, "e": 869, "s": 855, "text": "Naive Method:" }, { "code": null, "e": 1041, "s": 869, "text": "The idea is to try all index sums from 0 to sum of sizes. For every sum, check if there are pairs with given sum. Once we find one or more pairs, we print them and return." }, { "code": null, "e": 1045, "s": 1041, "text": "C++" }, { "code": null, "e": 1050, "s": 1045, "text": "Java" }, { "code": null, "e": 1058, "s": 1050, "text": "Python3" }, { "code": null, "e": 1061, "s": 1058, "text": "C#" }, { "code": null, "e": 1072, "s": 1061, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; // Function to print common strings with minimum index sumvoid find(vector<string> list1, vector<string> list2){ vector<string> res; // resultant list int max_possible_sum = list1.size() + list2.size() - 2; // iterating over sum in ascending order for (int sum = 0; sum <= max_possible_sum ; sum++) { // iterating over one list and check index // (Corresponding to given sum) in other list for (int i = 0; i <= sum; i++) // put common strings in resultant list if (i < list1.size() && (sum - i) < list2.size() && list1[i] == list2[sum - i]) res.push_back(list1[i]); // if common string found then break as we are // considering index sums in increasing order. if (res.size() > 0) break; } // print the resultant list for (int i = 0; i < res.size(); i++) cout << res[i] << \" \";} // Driver codeint main(){ // Creating list1 vector<string> list1; list1.push_back(\"GeeksforGeeks\"); list1.push_back(\"Udemy\"); list1.push_back(\"Coursera\"); list1.push_back(\"edX\"); // Creating list2 vector<string> list2; list2.push_back(\"Codecademy\"); list2.push_back(\"Khan Academy\"); list2.push_back(\"GeeksforGeeks\"); find(list1, list2); return 0;}", "e": 2456, "s": 1072, "text": null }, { "code": "import java.util.*; class GFG{ // Function to print common Strings with minimum index sumstatic void find(Vector<String> list1, Vector<String> list2){ Vector<String> res = new Vector<>(); // resultant list int max_possible_sum = list1.size() + list2.size() - 2; // iterating over sum in ascending order for (int sum = 0; sum <= max_possible_sum ; sum++) { // iterating over one list and check index // (Corresponding to given sum) in other list for (int i = 0; i <= sum; i++) // put common Strings in resultant list if (i < list1.size() && (sum - i) < list2.size() && list1.get(i) == list2.get(sum - i)) res.add(list1.get(i)); // if common String found then break as we are // considering index sums in increasing order. if (res.size() > 0) break; } // print the resultant list for (int i = 0; i < res.size(); i++) System.out.print(res.get(i)+\" \");} // Driver codepublic static void main(String[] args){ // Creating list1 Vector<String> list1 = new Vector<>(); list1.add(\"GeeksforGeeks\"); list1.add(\"Udemy\"); list1.add(\"Coursera\"); list1.add(\"edX\"); // Creating list2 Vector<String> list2= new Vector<>(); list2.add(\"Codecademy\"); list2.add(\"Khan Academy\"); list2.add(\"GeeksforGeeks\"); find(list1, list2); }} // This code contributed by Rajput-Ji", "e": 3912, "s": 2456, "text": null }, { "code": "# Function to print common strings# with minimum index sumdef find(list1, list2): res = [] # resultant list max_possible_sum = len(list1) + len(list2) - 2 # iterating over sum in ascending order for sum in range(max_possible_sum + 1): # iterating over one list and check index # (Corresponding to given sum) in other list for i in range(sum + 1): # put common strings in resultant list if (i < len(list1) and (sum - i) < len(list2) and list1[i] == list2[sum - i]): res.append(list1[i]) # if common string found then break as we are # considering index sums in increasing order. if (len(res) > 0): break # print the resultant list for i in range(len(res)): print(res[i], end = \" \") # Driver code # Creating list1list1 = []list1.append(\"GeeksforGeeks\")list1.append(\"Udemy\")list1.append(\"Coursera\")list1.append(\"edX\") # Creating list2list2 = []list2.append(\"Codecademy\")list2.append(\"Khan Academy\")list2.append(\"GeeksforGeeks\") find(list1, list2) # This code is contributed by Mohit Kumar", "e": 5055, "s": 3912, "text": null }, { "code": "using System;using System.Collections.Generic; class GFG{ // Function to print common Strings with minimum index sumstatic void find(List<String> list1, List<String> list2){ List<String> res = new List<String>(); // resultant list int max_possible_sum = list1.Count + list2.Count - 2; // iterating over sum in ascending order for (int sum = 0; sum <= max_possible_sum ; sum++) { // iterating over one list and check index // (Corresponding to given sum) in other list for (int i = 0; i <= sum; i++) // put common Strings in resultant list if (i < list1.Count && (sum - i) < list2.Count && list1[i] == list2[sum - i]) res.Add(list1[i]); // if common String found then break as we are // considering index sums in increasing order. if (res.Count > 0) break; } // print the resultant list for (int i = 0; i < res.Count; i++) Console.Write(res[i]+\" \");} // Driver codepublic static void Main(String[] args){ // Creating list1 List<String> list1 = new List<String>(); list1.Add(\"GeeksforGeeks\"); list1.Add(\"Udemy\"); list1.Add(\"Coursera\"); list1.Add(\"edX\"); // Creating list2 List<String> list2= new List<String>(); list2.Add(\"Codecademy\"); list2.Add(\"Khan Academy\"); list2.Add(\"GeeksforGeeks\"); find(list1, list2); }} // This code is contributed by 29AjayKumar", "e": 6512, "s": 5055, "text": null }, { "code": "<script> // Function to print common Strings with minimum index sum function find(list1, list2) { let res = []; // resultant list let max_possible_sum = list1.length + list2.length - 2; // iterating over sum in ascending order for (let sum = 0; sum <= max_possible_sum ; sum++) { // iterating over one list and check index // (Corresponding to given sum) in other list for (let i = 0; i <= sum; i++) // put common Strings in resultant list if (i < list1.length && (sum - i) < list2.length && list1[i] == list2[sum - i]) res.push(list1[i]); // if common String found then break as we are // considering index sums in increasing order. if (res.length > 0) break; } // print the resultant list for (let i = 0; i < res.length; i++) document.write(res[i]+\" \"); } // Creating list1 let list1 = []; list1.push(\"GeeksforGeeks\"); list1.push(\"Udemy\"); list1.push(\"Coursera\"); list1.push(\"edX\"); // Creating list2 let list2= []; list2.push(\"Codecademy\"); list2.push(\"Khan Academy\"); list2.push(\"GeeksforGeeks\"); find(list1, list2); // This code is contributed by mukesh07.</script>", "e": 7879, "s": 6512, "text": null }, { "code": null, "e": 7888, "s": 7879, "text": "Output: " }, { "code": null, "e": 7902, "s": 7888, "text": "GeeksforGeeks" }, { "code": null, "e": 8138, "s": 7902, "text": "Time Complexity : O((l1+l2)2 *x), where l1 and l2 are the lengths of list1 and list2 respectively and x refers to string length.Auxiliary Space : O(l*x), where x refers to length of resultant list and l is length of maximum size word. " }, { "code": null, "e": 8150, "s": 8138, "text": "Using Hash:" }, { "code": null, "e": 8709, "s": 8150, "text": "Traverse over the list1 and create an entry for index each element of list1 in a Hash Table.Traverse over list2 and for every element, check if the same element already exists as a key in the map. If so, it means that the element exists in both the lists.Find out the sum of indices corresponding to common element in the two lists. If this sum is lesser than the minimum sum obtained till now, update the resultant list.If the sum is equal to the minimum sum obtained till now, put an extra entry corresponding to the element in list2 in the resultant list." }, { "code": null, "e": 8802, "s": 8709, "text": "Traverse over the list1 and create an entry for index each element of list1 in a Hash Table." }, { "code": null, "e": 8966, "s": 8802, "text": "Traverse over list2 and for every element, check if the same element already exists as a key in the map. If so, it means that the element exists in both the lists." }, { "code": null, "e": 9133, "s": 8966, "text": "Find out the sum of indices corresponding to common element in the two lists. If this sum is lesser than the minimum sum obtained till now, update the resultant list." }, { "code": null, "e": 9271, "s": 9133, "text": "If the sum is equal to the minimum sum obtained till now, put an extra entry corresponding to the element in list2 in the resultant list." }, { "code": null, "e": 9275, "s": 9271, "text": "C++" }, { "code": null, "e": 9280, "s": 9275, "text": "Java" }, { "code": null, "e": 9288, "s": 9280, "text": "Python3" }, { "code": null, "e": 9291, "s": 9288, "text": "C#" }, { "code": null, "e": 9302, "s": 9291, "text": "Javascript" }, { "code": "// Hashing based C++ program to find common elements// with minimum index sum.#include <bits/stdc++.h>using namespace std; // Function to print common strings with minimum index sumvoid find(vector<string> list1, vector<string> list2){ // mapping strings to their indices unordered_map<string, int> map; for (int i = 0; i < list1.size(); i++) map[list1[i]] = i; vector<string> res; // resultant list int minsum = INT_MAX; for (int j = 0; j < list2.size(); j++) { if (map.count(list2[j])) { // If current sum is smaller than minsum int sum = j + map[list2[j]]; if (sum < minsum) { minsum = sum; res.clear(); res.push_back(list2[j]); } // if index sum is same then put this // string in resultant list as well else if (sum == minsum) res.push_back(list2[j]); } } // Print result for (int i = 0; i < res.size(); i++) cout << res[i] << \" \";} // Driver codeint main(){ // Creating list1 vector<string> list1; list1.push_back(\"GeeksforGeeks\"); list1.push_back(\"Udemy\"); list1.push_back(\"Coursera\"); list1.push_back(\"edX\"); // Creating list2 vector<string> list2; list2.push_back(\"Codecademy\"); list2.push_back(\"Khan Academy\"); list2.push_back(\"GeeksforGeeks\"); find(list1, list2); return 0;}", "e": 10747, "s": 9302, "text": null }, { "code": "// Hashing based Java program to find common elements// with minimum index sum.import java.util.*; class GFG{ // Function to print common Strings with minimum index sum static void find(Vector<String> list1, Vector<String> list2) { // mapping Strings to their indices Map<String, Integer> map = new HashMap<>(); for (int i = 0; i < list1.size(); i++) map.put(list1.get(i), i); Vector<String> res = new Vector<String>(); // resultant list int minsum = Integer.MAX_VALUE; for (int j = 0; j < list2.size(); j++) { if (map.containsKey(list2.get(j))) { // If current sum is smaller than minsum int sum = j + map.get(list2.get(j)); if (sum < minsum) { minsum = sum; res.clear(); res.add(list2.get(j)); } // if index sum is same then put this // String in resultant list as well else if (sum == minsum) res.add(list2.get(j)); } } // Print result for (int i = 0; i < res.size(); i++) System.out.print(res.get(i) + \" \"); } // Driver code public static void main(String[] args) { // Creating list1 Vector<String> list1 = new Vector<String>(); list1.add(\"GeeksforGeeks\"); list1.add(\"Udemy\"); list1.add(\"Coursera\"); list1.add(\"edX\"); // Creating list2 Vector<String> list2 = new Vector<String>(); list2.add(\"Codecademy\"); list2.add(\"Khan Academy\"); list2.add(\"GeeksforGeeks\"); find(list1, list2); }} // This code is contributed by PrinciRaj1992", "e": 12517, "s": 10747, "text": null }, { "code": "# Hashing based Python3 program to find# common elements with minimum index sumimport sys # Function to print common strings# with minimum index sumdef find(list1, list2): # Mapping strings to their indices Map = {} for i in range(len(list1)): Map[list1[i]] = i # Resultant list res = [] minsum = sys.maxsize for j in range(len(list2)): if list2[j] in Map: # If current sum is smaller # than minsum Sum = j + Map[list2[j]] if (Sum < minsum): minsum = Sum res.clear() res.append(list2[j]) # If index sum is same then put this # string in resultant list as well else if (Sum == minsum): res.append(list2[j]) # Print result print(*res, sep = \" \") # Driver code # Creating list1list1 = []list1.append(\"GeeksforGeeks\")list1.append(\"Udemy\")list1.append(\"Coursera\")list1.append(\"edX\") # Creating list2list2 = []list2.append(\"Codecademy\")list2.append(\"Khan Academy\")list2.append(\"GeeksforGeeks\")find(list1, list2) # This code is contributed by avanitrachhadiya2155", "e": 13713, "s": 12517, "text": null }, { "code": "// Hashing based C# program to find common elements// with minimum index sum.using System;using System.Collections.Generic; class GFG{ // Function to print common Strings with minimum index sum static void find(List<String> list1, List<String> list2) { // mapping Strings to their indices Dictionary<String, int> map = new Dictionary<String, int>(); for (int i = 0; i < list1.Count; i++) map.Add(list1[i], i); List<String> res = new List<String>(); // resultant list int minsum = int.MaxValue; for (int j = 0; j < list2.Count; j++) { if (map.ContainsKey(list2[j])) { // If current sum is smaller than minsum int sum = j + map[list2[j]]; if (sum < minsum) { minsum = sum; res.Clear(); res.Add(list2[j]); } // if index sum is same then put this // String in resultant list as well else if (sum == minsum) res.Add(list2[j]); } } // Print result for (int i = 0; i < res.Count; i++) Console.Write(res[i] + \" \"); } // Driver code public static void Main(String[] args) { // Creating list1 List<String> list1 = new List<String>(); list1.Add(\"GeeksforGeeks\"); list1.Add(\"Udemy\"); list1.Add(\"Coursera\"); list1.Add(\"edX\"); // Creating list2 List<String> list2 = new List<String>(); list2.Add(\"Codecademy\"); list2.Add(\"Khan Academy\"); list2.Add(\"GeeksforGeeks\"); find(list1, list2); }} // This code is contributed by Rajput-Ji", "e": 15466, "s": 13713, "text": null }, { "code": "<script> // Hashing based Javascript program to// find common elements with minimum// index sum. // Function to print common Strings// with minimum index sumfunction find(list1, list2){ // Mapping Strings to their indices let map = new Map(); for(let i = 0; i < list1.length; i++) map.set(list1[i], i); // Resultant list let res = []; let minsum = Number.MAX_VALUE; for(let j = 0; j < list2.length; j++) { if (map.has(list2[j])) { // If current sum is smaller than minsum let sum = j + map.get(list2[j]); if (sum < minsum) { minsum = sum; res = []; res.push(list2[j]); } // If index sum is same then put this // String in resultant list as well else if (sum == minsum) res.push(list2[j]); } } // Print result for(let i = 0; i < res.length; i++) document.write(res[i] + \" \");} // Driver code // Creating list1let list1 = [];list1.push(\"GeeksforGeeks\");list1.push(\"Udemy\");list1.push(\"Coursera\");list1.push(\"edX\"); // Creating list2let list2 = [];list2.push(\"Codecademy\");list2.push(\"Khan Academy\");list2.push(\"GeeksforGeeks\"); find(list1, list2); // This code is contributed by rameshtravel07 </script>", "e": 16814, "s": 15466, "text": null }, { "code": null, "e": 16823, "s": 16814, "text": "Output: " }, { "code": null, "e": 16837, "s": 16823, "text": "GeeksforGeeks" }, { "code": null, "e": 17037, "s": 16837, "text": "Time Complexity : O(l1+l2), where l1 and l2 are the lengths of list1 and list2 respectively.Auxiliary Space : O(l1*x), where x refers to length of resultant list and l is length of maximum size word." }, { "code": null, "e": 17456, "s": 17037, "text": "This article is contributed by Aakash Pal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 17466, "s": 17456, "text": "Rajput-Ji" }, { "code": null, "e": 17478, "s": 17466, "text": "29AjayKumar" }, { "code": null, "e": 17493, "s": 17478, "text": "mohit kumar 29" }, { "code": null, "e": 17507, "s": 17493, "text": "princiraj1992" }, { "code": null, "e": 17517, "s": 17507, "text": "Code_Mech" }, { "code": null, "e": 17538, "s": 17517, "text": "avanitrachhadiya2155" }, { "code": null, "e": 17547, "s": 17538, "text": "mukesh07" }, { "code": null, "e": 17562, "s": 17547, "text": "rameshtravel07" }, { "code": null, "e": 17575, "s": 17562, "text": "simmytarika5" }, { "code": null, "e": 17593, "s": 17575, "text": "cpp-unordered_map" }, { "code": null, "e": 17598, "s": 17593, "text": "Hash" }, { "code": null, "e": 17606, "s": 17598, "text": "Strings" }, { "code": null, "e": 17611, "s": 17606, "text": "Hash" }, { "code": null, "e": 17619, "s": 17611, "text": "Strings" } ]
numpy.dtype.kind() function – Python
18 Jun, 2020 numpy.dtype.kind() function determine the character code by identifying the general kind of data. Syntax : numpy.dtype.kind(type) Parameters :type : [dtype] The input data-type.Return : Return the character code by identifying the general kind of data. Code #1 : # Python program explaining# numpy.dtype.kind() function # importing numpy as geek import numpy as geek dtype = geek.dtype('f4') gfg = dtype.kind print (gfg) Output : f Code #2 : # Python program explaining# numpy.dtype.kind() function # importing numpy as geek import numpy as geek dtype = geek.dtype('i4') gfg = dtype.kind print (gfg) Output : i Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Jun, 2020" }, { "code": null, "e": 126, "s": 28, "text": "numpy.dtype.kind() function determine the character code by identifying the general kind of data." }, { "code": null, "e": 158, "s": 126, "text": "Syntax : numpy.dtype.kind(type)" }, { "code": null, "e": 281, "s": 158, "text": "Parameters :type : [dtype] The input data-type.Return : Return the character code by identifying the general kind of data." }, { "code": null, "e": 291, "s": 281, "text": "Code #1 :" }, { "code": "# Python program explaining# numpy.dtype.kind() function # importing numpy as geek import numpy as geek dtype = geek.dtype('f4') gfg = dtype.kind print (gfg)", "e": 464, "s": 291, "text": null }, { "code": null, "e": 473, "s": 464, "text": "Output :" }, { "code": null, "e": 476, "s": 473, "text": "f\n" }, { "code": null, "e": 487, "s": 476, "text": " Code #2 :" }, { "code": "# Python program explaining# numpy.dtype.kind() function # importing numpy as geek import numpy as geek dtype = geek.dtype('i4') gfg = dtype.kind print (gfg)", "e": 660, "s": 487, "text": null }, { "code": null, "e": 669, "s": 660, "text": "Output :" }, { "code": null, "e": 672, "s": 669, "text": "i\n" }, { "code": null, "e": 685, "s": 672, "text": "Python-numpy" }, { "code": null, "e": 692, "s": 685, "text": "Python" } ]
JavaScript Ternary Operator
11 Feb, 2021 Below is the example of the Ternary Operator. Example:Program 1:<script> function gfg() { //JavaScript to illustrate //Conditional operator let PMarks = 40 let result = (PMarks > 39)? "Pass":"Fail"; document.write(result); } gfg(); </script> <script> function gfg() { //JavaScript to illustrate //Conditional operator let PMarks = 40 let result = (PMarks > 39)? "Pass":"Fail"; document.write(result); } gfg(); </script> Output:Pass Pass “Question mark” or “conditional” operator in JavaScript is a ternary operator that has three operands. The expression consists of three operands: the condition, value if true and value if false. The evaluation of the condition should result in either true/false or a boolean value. The true value lies between “?” & “:” and is executed if the condition returns true. Similarly, the false value lies after “:” and is executed if the condition returns false. Syntax: condition ? value if true : value if false Expression to be evaluated which returns a boolean value. value if true: Value to be executed if condition results in true state. value if false: Value to be executed if condition results in false state. Examples: Input: let result = (10 > 0) ? true : false; Output: true Input: let message = (20 > 15) ? "Yes" : "No"; Output: Yes The following programs will illustrate conditional operator more extensively: Program 1: <script> function gfg() { //JavaScript to illustrate //Conditional operator let age = 60 let result = (age > 59)? "Senior Citizen":"Not a Senior Citizen"; document.write(result); } gfg(); </script> Output: Senior Citizen An example of multiple conditional operators.Program 2: <script> function gfg() { //JavaScript to illustrate //multiple Conditional operators let marks = 95; let result = (marks < 40) ? "Unsatisfactory" : (marks < 60) ? "Average" : (marks < 80) ? "Good" : "Excellent" ; document.write(result); } gfg(); </script> Output: Excellent javascript-operators Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Hide or show elements in HTML using display property Difference Between PUT and PATCH Request Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 52, "s": 24, "text": "\n11 Feb, 2021" }, { "code": null, "e": 98, "s": 52, "text": "Below is the example of the Ternary Operator." }, { "code": null, "e": 344, "s": 98, "text": "Example:Program 1:<script> function gfg() { //JavaScript to illustrate //Conditional operator let PMarks = 40 let result = (PMarks > 39)? \"Pass\":\"Fail\"; document.write(result); } gfg(); </script> " }, { "code": "<script> function gfg() { //JavaScript to illustrate //Conditional operator let PMarks = 40 let result = (PMarks > 39)? \"Pass\":\"Fail\"; document.write(result); } gfg(); </script> ", "e": 572, "s": 344, "text": null }, { "code": null, "e": 584, "s": 572, "text": "Output:Pass" }, { "code": null, "e": 589, "s": 584, "text": "Pass" }, { "code": null, "e": 692, "s": 589, "text": "“Question mark” or “conditional” operator in JavaScript is a ternary operator that has three operands." }, { "code": null, "e": 784, "s": 692, "text": "The expression consists of three operands: the condition, value if true and value if false." }, { "code": null, "e": 871, "s": 784, "text": "The evaluation of the condition should result in either true/false or a boolean value." }, { "code": null, "e": 1046, "s": 871, "text": "The true value lies between “?” & “:” and is executed if the condition returns true. Similarly, the false value lies after “:” and is executed if the condition returns false." }, { "code": null, "e": 1054, "s": 1046, "text": "Syntax:" }, { "code": null, "e": 1097, "s": 1054, "text": "condition ? value if true : value if false" }, { "code": null, "e": 1155, "s": 1097, "text": "Expression to be evaluated which returns a boolean value." }, { "code": null, "e": 1170, "s": 1155, "text": "value if true:" }, { "code": null, "e": 1227, "s": 1170, "text": "Value to be executed if condition results in true state." }, { "code": null, "e": 1243, "s": 1227, "text": "value if false:" }, { "code": null, "e": 1301, "s": 1243, "text": "Value to be executed if condition results in false state." }, { "code": null, "e": 1311, "s": 1301, "text": "Examples:" }, { "code": null, "e": 1430, "s": 1311, "text": "Input: let result = (10 > 0) ? true : false;\nOutput: true\n\nInput: let message = (20 > 15) ? \"Yes\" : \"No\";\nOutput: Yes\n" }, { "code": null, "e": 1508, "s": 1430, "text": "The following programs will illustrate conditional operator more extensively:" }, { "code": null, "e": 1519, "s": 1508, "text": "Program 1:" }, { "code": "<script> function gfg() { //JavaScript to illustrate //Conditional operator let age = 60 let result = (age > 59)? \"Senior Citizen\":\"Not a Senior Citizen\"; document.write(result); } gfg(); </script> ", "e": 1784, "s": 1519, "text": null }, { "code": null, "e": 1792, "s": 1784, "text": "Output:" }, { "code": null, "e": 1807, "s": 1792, "text": "Senior Citizen" }, { "code": null, "e": 1863, "s": 1807, "text": "An example of multiple conditional operators.Program 2:" }, { "code": "<script> function gfg() { //JavaScript to illustrate //multiple Conditional operators let marks = 95; let result = (marks < 40) ? \"Unsatisfactory\" : (marks < 60) ? \"Average\" : (marks < 80) ? \"Good\" : \"Excellent\" ; document.write(result); } gfg(); </script> ", "e": 2181, "s": 1863, "text": null }, { "code": null, "e": 2189, "s": 2181, "text": "Output:" }, { "code": null, "e": 2199, "s": 2189, "text": "Excellent" }, { "code": null, "e": 2220, "s": 2199, "text": "javascript-operators" }, { "code": null, "e": 2227, "s": 2220, "text": "Picked" }, { "code": null, "e": 2238, "s": 2227, "text": "JavaScript" }, { "code": null, "e": 2255, "s": 2238, "text": "Web Technologies" }, { "code": null, "e": 2353, "s": 2255, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2414, "s": 2353, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2486, "s": 2414, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 2526, "s": 2486, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2579, "s": 2526, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 2620, "s": 2579, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 2653, "s": 2620, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2715, "s": 2653, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2776, "s": 2715, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2826, "s": 2776, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
AWK - Increment and Decrement Operators
AWK supports the following increment and decrement operators − It is represented by ++. It increments the value of an operand by 1. This operator first increments the value of the operand, then returns the incremented value. For instance, in the following example, this operator sets the value of both the operands, a and b, to 11. awk 'BEGIN { a = 10; b = ++a; printf "a = %d, b = %d\n", a, b }' On executing this code, you get the following result − a = 11, b = 11 It is represented by --. It decrements the value of an operand by 1. This operator first decrements the value of the operand, then returns the decremented value. For instance, in the following example, this operator sets the value of both the operands, a and b, to 9. [jerry]$ awk 'BEGIN { a = 10; b = --a; printf "a = %d, b = %d\n", a, b }' On executing the above code, you get the following result − a = 9, b = 9 It is represented by ++. It increments the value of an operand by 1. This operator first returns the value of the operand, then it increments its value. For instance, the following code sets the value of operand a to 11 and b to 10. [jerry]$ awk 'BEGIN { a = 10; b = a++; printf "a = %d, b = %d\n", a, b }' On executing this code, you get the following result − a = 11, b = 10 It is represented by --. It decrements the value of an operand by 1. This operator first returns the value of the operand, then it decrements its value. For instance, the following code sets the value of the operand a to 9 and b to 10. [jerry]$ awk 'BEGIN { a = 10; b = a--; printf "a = %d, b = %d\n", a, b }' On executing this code, you get the following result − a = 9, b = 10 Print Add Notes Bookmark this page
[ { "code": null, "e": 1920, "s": 1857, "text": "AWK supports the following increment and decrement operators −" }, { "code": null, "e": 2189, "s": 1920, "text": "It is represented by ++. It increments the value of an operand by 1. This operator first increments the value of the operand, then returns the incremented value. For instance, in the following example, this operator sets the value of both the operands, a and b, to 11." }, { "code": null, "e": 2254, "s": 2189, "text": "awk 'BEGIN { a = 10; b = ++a; printf \"a = %d, b = %d\\n\", a, b }'" }, { "code": null, "e": 2309, "s": 2254, "text": "On executing this code, you get the following result −" }, { "code": null, "e": 2325, "s": 2309, "text": "a = 11, b = 11\n" }, { "code": null, "e": 2593, "s": 2325, "text": "It is represented by --. It decrements the value of an operand by 1. This operator first decrements the value of the operand, then returns the decremented value. For instance, in the following example, this operator sets the value of both the operands, a and b, to 9." }, { "code": null, "e": 2667, "s": 2593, "text": "[jerry]$ awk 'BEGIN { a = 10; b = --a; printf \"a = %d, b = %d\\n\", a, b }'" }, { "code": null, "e": 2727, "s": 2667, "text": "On executing the above code, you get the following result −" }, { "code": null, "e": 2741, "s": 2727, "text": "a = 9, b = 9\n" }, { "code": null, "e": 2974, "s": 2741, "text": "It is represented by ++. It increments the value of an operand by 1. This operator first returns the value of the operand, then it increments its value. For instance, the following code sets the value of operand a to 11 and b to 10." }, { "code": null, "e": 3048, "s": 2974, "text": "[jerry]$ awk 'BEGIN { a = 10; b = a++; printf \"a = %d, b = %d\\n\", a, b }'" }, { "code": null, "e": 3103, "s": 3048, "text": "On executing this code, you get the following result −" }, { "code": null, "e": 3119, "s": 3103, "text": "a = 11, b = 10\n" }, { "code": null, "e": 3355, "s": 3119, "text": "It is represented by --. It decrements the value of an operand by 1. This operator first returns the value of the operand, then it decrements its value. For instance, the following code sets the value of the operand a to 9 and b to 10." }, { "code": null, "e": 3429, "s": 3355, "text": "[jerry]$ awk 'BEGIN { a = 10; b = a--; printf \"a = %d, b = %d\\n\", a, b }'" }, { "code": null, "e": 3484, "s": 3429, "text": "On executing this code, you get the following result −" }, { "code": null, "e": 3499, "s": 3484, "text": "a = 9, b = 10\n" }, { "code": null, "e": 3506, "s": 3499, "text": " Print" }, { "code": null, "e": 3517, "s": 3506, "text": " Add Notes" } ]
Decision Trees and Random Forests for Classification and Regression pt.1 | by Haihan Lan | Towards Data Science
Want to use something more interpertable, something that trains faster and performs pretty much just as well as the old Logistic Regression or even Neural Networks? You should consider Decision Trees for classification and regression. Part 2 on Random Forests here. Much faster to train versus simple neural networks for comparable performance (The time complexity of decision trees is a function of [number of features, number of rows in dataset], whereas for neural networks it is a function of [number of features, number of rows in dataset, number of hidden layers, number of nodes in each hidden layer]) Easily interpretable, suitable for variable selection Fairly robust on smaller datasets Decision Trees and Decision Tree Learning are simple to understand Links to my other articles: Custom Loss Functions in TensorFlowSoftmax classificationClimate analysisHockey riots and extreme values Custom Loss Functions in TensorFlow Softmax classification Climate analysis Hockey riots and extreme values Decision Trees and their extension Random Forests are robust and easy-to-interpret machine learning algorithms for Classification and Regression tasks. Decision Trees and Decision Tree Learning together comprise a simple and fast way of learning a function that maps data x to outputs y, where x can be a mix of categorical and numeric variables and y can be categorical for classification, or numeric for regression. Methods such as SVMs, Logistic Regression and Deep Neural Nets pretty much do the same thing. However despite their power against larger and more complex datasets, they are extremely hard to interpret and neural nets can take many iterations and hyperparameter adjustments before a good result is had. As well, one of the biggest advantages of using Decision Trees and Random Forests is the ease in which we can see what features or variables contribute to the classification or regression and their relative importance based on their location depthwise in the tree. We’ll look at decision trees in this article and compare their classification performance using information derived from the Receiver Operating Characteristic (ROC) against logistic regression and a simple neural net. A Decision Tree is a tree (and a type of directed, acyclic graph) in which the nodes represent decisions (a square box), random transitions (a circular box) or terminal nodes, and the edges or branches are binary (yes/no, true/false) representing possible paths from one node to another. The specific type of decision tree used for machine learning contains no random transitions. To use a decision tree for classification or regression, one grabs a row of data or a set of features and starts at the root, and then through each subsequent decision node to the terminal node. The process is very intuitive and easy to interpret, which allows trained decision trees to be used for variable selection or more generally, feature engineering. To illustrate this, suppose you wanted to buy a new car to drive up a random dirt road into a random forest. You have a dataset of different cars with three features: Car Drive Type (Categorical), Displacement (Numeric) and Clearance (Numeric). An example of a learned decision tree to help you make your decision is below: The root or topmost node of the tree (and there is only one root) is the decision node that splits the dataset using a variable or feature that results in the the best splitting metric evaluated for each subset or class in the dataset that results from the split. The decision tree learns by recursively splitting the dataset from the root onwards (in a greedy, node by node manner) according to the splitting metric at each decision node. The terminal nodes are reached when the splitting metric is at a global extremum. Popular splitting metrics include the minimizing the Gini Impurity (used by CART) or maximizing the Information Gain (used by ID3, C4.5). Now that we have seen how decision tree training works, let’s use the scikit-learn package (scikit-learn contains many nice data processing, dimensionality reduction, clustering and shallow machine learning tools) and implement a simple decision tree for classification on the Wine Dataset (13 features/variables with 3 classes), and then visualize the learned tree with Graphviz. Right away, from the learned decision tree we can see that the feature proline (proline content in the wine) is the root node with the highest Gini Impurity value of 0.658, and this means that all three wine classes have this as their base separation. This also means that in principle, if we used only one feature in a predictive model, the proline content will allow us to predict correctly to a maximum 1-0.658 = 0.342 = 34.2% of the time, assuming that the original learned decision tree predicts perfectly. Then, from the root we see that the classes split off further with the od280/od315_of_dilute_wines feature and the flavinoid feature. We can also see that a majority of the class_1 wine (81.7%) have an alcohol content ≤ 13.175 and a flavinoid content ≤ 0.795. Also, recall that there are 13 features in the original dataset, but the decision tree picked only a subset of 7 features for the classification. We can use this information to select which features/variables in a general dataset are important (in cases where there may be non-useful, redundant or noisy features) for a more advanced model such a deep neural net. We’ll see how to do this with more robust random forests in part 2. The learned decision tree can be used to predict data using a simple function call on a row of input data. A regression tree for predicting numerical output values from input features can be created very easily as well: check out this scikit-learn tutorial. The Receiver Operating Characteristic (ROC) is a plot that can be used to determine the performance and robustness of a binary or multi-class classifier. The x-axis is the false positive rate (FPR) and the y-axis is the true positive rate (TPR). The ROC plot gives information about the about true postive/negative rate and false positive/negative rate and something called the C-statistic or area under ROC curve (AUROC) for each class predicted by the classifier (there is one ROC for each class predicted by the classifier). The AUROC is defined as the probability that a randomly selected positive sample will have a higher prediction value than a randomly selected negative sample. A quote from this article on the subject: “Assuming that one is not interested in a specific trade-off between true positive rate and false positive rate (that is, a particular point on the ROC curve), the AUC [AUROC] is useful in that it aggregates performance across the entire range of trade-offs. Interpretation of the AUC is easy: the higher the AUC, the better, with 0.50 indicating random performance and 1.00 denoting perfect performance.” The AUROCs for different classifiers can be compared against each other. Alternatives to this metric include using the scikit-learn confusion matrix calculator for the prediction results and using the resultant matrix to derive basic positive/negative accuracy, F1-scores, etc. {0: 0.98076923076923084, 1: 0.97499999999999998, 2: 1.0, 'micro': 0.97916666666666685} The above output is the AUROC for each class predicted by the decision tree. The compare, in scikit-learn we re-run the same dataset with 20% test set on a logistic regression model and a shallow MLP neural net model. The logistic regression model’s performance (with all default parameters) is below: {0: 0.96153846153846156, 1: 0.94999999999999996, 2: 1.0, 'micro': 0.95833333333333326} And for the shallow MLP net: hidden layers = 2, nodes per layer = 25, optimizer = adam, activation = logistic, iterations = 50000: {0: 1.0, 1: 1.0, 2: 1.0, 'micro': 1.0} We can see that the decision tree outperforms logistic regression, and although the Neural Net beats it, it is still much faster to train and has the advantage of interpretability. Decision Trees should always be in the toolkit of the adept Data Scientist and Machine Learning Engineer. For a more thorough user guide/manual of how to use decision trees in scikit-learm, refer to http://scikit-learn.org/stable/modules/tree.html#decision-trees. However, despite the ease of use and apparent power of decision trees, their reliance on a greedy strategy for learning may cause the tree to split the wrong features at each node or cause the tree to overfit. Stay tuned, in the next article I will be demonstrating ensemble decision trees, or so-called Random Forests and Bootstrap Aggregation which when used together drastically increase predictive power and robustness for larger and more complicated datasets. As well we’ll see how we can use random forests for robust Variable Selection.
[ { "code": null, "e": 438, "s": 172, "text": "Want to use something more interpertable, something that trains faster and performs pretty much just as well as the old Logistic Regression or even Neural Networks? You should consider Decision Trees for classification and regression. Part 2 on Random Forests here." }, { "code": null, "e": 781, "s": 438, "text": "Much faster to train versus simple neural networks for comparable performance (The time complexity of decision trees is a function of [number of features, number of rows in dataset], whereas for neural networks it is a function of [number of features, number of rows in dataset, number of hidden layers, number of nodes in each hidden layer])" }, { "code": null, "e": 835, "s": 781, "text": "Easily interpretable, suitable for variable selection" }, { "code": null, "e": 869, "s": 835, "text": "Fairly robust on smaller datasets" }, { "code": null, "e": 936, "s": 869, "text": "Decision Trees and Decision Tree Learning are simple to understand" }, { "code": null, "e": 964, "s": 936, "text": "Links to my other articles:" }, { "code": null, "e": 1069, "s": 964, "text": "Custom Loss Functions in TensorFlowSoftmax classificationClimate analysisHockey riots and extreme values" }, { "code": null, "e": 1105, "s": 1069, "text": "Custom Loss Functions in TensorFlow" }, { "code": null, "e": 1128, "s": 1105, "text": "Softmax classification" }, { "code": null, "e": 1145, "s": 1128, "text": "Climate analysis" }, { "code": null, "e": 1177, "s": 1145, "text": "Hockey riots and extreme values" }, { "code": null, "e": 2162, "s": 1177, "text": "Decision Trees and their extension Random Forests are robust and easy-to-interpret machine learning algorithms for Classification and Regression tasks. Decision Trees and Decision Tree Learning together comprise a simple and fast way of learning a function that maps data x to outputs y, where x can be a mix of categorical and numeric variables and y can be categorical for classification, or numeric for regression. Methods such as SVMs, Logistic Regression and Deep Neural Nets pretty much do the same thing. However despite their power against larger and more complex datasets, they are extremely hard to interpret and neural nets can take many iterations and hyperparameter adjustments before a good result is had. As well, one of the biggest advantages of using Decision Trees and Random Forests is the ease in which we can see what features or variables contribute to the classification or regression and their relative importance based on their location depthwise in the tree." }, { "code": null, "e": 2380, "s": 2162, "text": "We’ll look at decision trees in this article and compare their classification performance using information derived from the Receiver Operating Characteristic (ROC) against logistic regression and a simple neural net." }, { "code": null, "e": 3443, "s": 2380, "text": "A Decision Tree is a tree (and a type of directed, acyclic graph) in which the nodes represent decisions (a square box), random transitions (a circular box) or terminal nodes, and the edges or branches are binary (yes/no, true/false) representing possible paths from one node to another. The specific type of decision tree used for machine learning contains no random transitions. To use a decision tree for classification or regression, one grabs a row of data or a set of features and starts at the root, and then through each subsequent decision node to the terminal node. The process is very intuitive and easy to interpret, which allows trained decision trees to be used for variable selection or more generally, feature engineering. To illustrate this, suppose you wanted to buy a new car to drive up a random dirt road into a random forest. You have a dataset of different cars with three features: Car Drive Type (Categorical), Displacement (Numeric) and Clearance (Numeric). An example of a learned decision tree to help you make your decision is below:" }, { "code": null, "e": 4103, "s": 3443, "text": "The root or topmost node of the tree (and there is only one root) is the decision node that splits the dataset using a variable or feature that results in the the best splitting metric evaluated for each subset or class in the dataset that results from the split. The decision tree learns by recursively splitting the dataset from the root onwards (in a greedy, node by node manner) according to the splitting metric at each decision node. The terminal nodes are reached when the splitting metric is at a global extremum. Popular splitting metrics include the minimizing the Gini Impurity (used by CART) or maximizing the Information Gain (used by ID3, C4.5)." }, { "code": null, "e": 4484, "s": 4103, "text": "Now that we have seen how decision tree training works, let’s use the scikit-learn package (scikit-learn contains many nice data processing, dimensionality reduction, clustering and shallow machine learning tools) and implement a simple decision tree for classification on the Wine Dataset (13 features/variables with 3 classes), and then visualize the learned tree with Graphviz." }, { "code": null, "e": 5402, "s": 4484, "text": "Right away, from the learned decision tree we can see that the feature proline (proline content in the wine) is the root node with the highest Gini Impurity value of 0.658, and this means that all three wine classes have this as their base separation. This also means that in principle, if we used only one feature in a predictive model, the proline content will allow us to predict correctly to a maximum 1-0.658 = 0.342 = 34.2% of the time, assuming that the original learned decision tree predicts perfectly. Then, from the root we see that the classes split off further with the od280/od315_of_dilute_wines feature and the flavinoid feature. We can also see that a majority of the class_1 wine (81.7%) have an alcohol content ≤ 13.175 and a flavinoid content ≤ 0.795. Also, recall that there are 13 features in the original dataset, but the decision tree picked only a subset of 7 features for the classification." }, { "code": null, "e": 5946, "s": 5402, "text": "We can use this information to select which features/variables in a general dataset are important (in cases where there may be non-useful, redundant or noisy features) for a more advanced model such a deep neural net. We’ll see how to do this with more robust random forests in part 2. The learned decision tree can be used to predict data using a simple function call on a row of input data. A regression tree for predicting numerical output values from input features can be created very easily as well: check out this scikit-learn tutorial." }, { "code": null, "e": 6675, "s": 5946, "text": "The Receiver Operating Characteristic (ROC) is a plot that can be used to determine the performance and robustness of a binary or multi-class classifier. The x-axis is the false positive rate (FPR) and the y-axis is the true positive rate (TPR). The ROC plot gives information about the about true postive/negative rate and false positive/negative rate and something called the C-statistic or area under ROC curve (AUROC) for each class predicted by the classifier (there is one ROC for each class predicted by the classifier). The AUROC is defined as the probability that a randomly selected positive sample will have a higher prediction value than a randomly selected negative sample. A quote from this article on the subject:" }, { "code": null, "e": 7081, "s": 6675, "text": "“Assuming that one is not interested in a specific trade-off between true positive rate and false positive rate (that is, a particular point on the ROC curve), the AUC [AUROC] is useful in that it aggregates performance across the entire range of trade-offs. Interpretation of the AUC is easy: the higher the AUC, the better, with 0.50 indicating random performance and 1.00 denoting perfect performance.”" }, { "code": null, "e": 7359, "s": 7081, "text": "The AUROCs for different classifiers can be compared against each other. Alternatives to this metric include using the scikit-learn confusion matrix calculator for the prediction results and using the resultant matrix to derive basic positive/negative accuracy, F1-scores, etc." }, { "code": null, "e": 7446, "s": 7359, "text": "{0: 0.98076923076923084, 1: 0.97499999999999998, 2: 1.0, 'micro': 0.97916666666666685}" }, { "code": null, "e": 7748, "s": 7446, "text": "The above output is the AUROC for each class predicted by the decision tree. The compare, in scikit-learn we re-run the same dataset with 20% test set on a logistic regression model and a shallow MLP neural net model. The logistic regression model’s performance (with all default parameters) is below:" }, { "code": null, "e": 7835, "s": 7748, "text": "{0: 0.96153846153846156, 1: 0.94999999999999996, 2: 1.0, 'micro': 0.95833333333333326}" }, { "code": null, "e": 7966, "s": 7835, "text": "And for the shallow MLP net: hidden layers = 2, nodes per layer = 25, optimizer = adam, activation = logistic, iterations = 50000:" }, { "code": null, "e": 8005, "s": 7966, "text": "{0: 1.0, 1: 1.0, 2: 1.0, 'micro': 1.0}" }, { "code": null, "e": 8186, "s": 8005, "text": "We can see that the decision tree outperforms logistic regression, and although the Neural Net beats it, it is still much faster to train and has the advantage of interpretability." }, { "code": null, "e": 8450, "s": 8186, "text": "Decision Trees should always be in the toolkit of the adept Data Scientist and Machine Learning Engineer. For a more thorough user guide/manual of how to use decision trees in scikit-learm, refer to http://scikit-learn.org/stable/modules/tree.html#decision-trees." } ]
Geek and Subset Sum | Practice | GeeksforGeeks
Given an array arr of positive integers of size N and an integer K, the task is to find the sum of all subsets of size K. Input: 1. The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows. 2. The first line of each test case contains two integers N and K. 3. The next line contains N space-separated integers. Output: For each test case, print the answer Constraints: 1. 1 <= T <= 10 2. 1 <= K <= N <= 12 3. 1 <= arr[i] <= 100 Example: Input: 2 4 2 1 2 3 5 1 1 20 Output: 33 20 Explanation: Test Case 1: Subsets are {1, 2}, {1, 3}, {1, 5}, {2, 3}, {2, 5}, {3, 5}, Summation of all subsets sum = 3 + 4 + 6 + 5 + 7 + 8 = 33 0 anutiger5 months ago void helper(int ind,int curk,int k,int *arr,int n ,int s,int &sum){ if(curk == k){ sum += s; return; } if(ind == n) return; helper(ind + 1,curk + 1,k,arr,n,s + arr[ind],sum); helper(ind + 1,curk,k,arr,n,s,sum); } int main() { int t; cin>> t; while(t--){ int n,k; cin >> n >> k; int arr[n]; for(int i = 0 ;i < n ; i ++){ cin >> arr[i]; } int sum = 0; helper(0,0,k,arr,n,0,sum); cout<<sum<<endl; } return 0; } 0 Akash8 months ago Akash import sys def intReadLine(): return int(sys.stdin.readline()) def readLine(): return map(int, sys.stdin.readline().strip().split()) num_cases = intReadLine() def bitCount(num): count = 0 while num > 0: count += (num&1) num >>= 1 return count for cas in range(num_cases): N, K = readLine() arr = list(readLine()) pre_sum = sum(arr) mult = 0 for i in range(2**N): bitcount = bitCount(i) if bitcount == K and (i & 1 == 1): mult += 1 ans = int(mult*pre_sum) print(ans) 0 Shadab Anwar9 months ago Shadab Anwar 0 Amit Singh Negi11 months ago Amit Singh Negi import java.util.*;import java.lang.*;import java.io.*;import java.util.stream.*;class GFG { public static void main (String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); while(t-- > 0){ String[] ip = br.readLine().split(" "); int n = Integer.parseInt(ip[0]), k = Integer.parseInt(ip[1]), sum = 0; int[] nums = Stream.of(br.readLine().split(" ")).mapToInt(Integer::new).toArray(); for(int i = 1; i < (1 << n); i++){//iterate all the possible 2 ^ n subsets if(Integer.bitCount(i) != k) continue;//skip other than k for(int j = 0, temp = i; j < n; j++, temp >>= 1) if((temp & 1) == 1)//current bit is set add nums[i] to sum sum += nums[j]; } System.out.println(sum); } }} 0 pradeep kumar1 year ago pradeep kumar We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 348, "s": 226, "text": "Given an array arr of positive integers of size N and an integer K, the task is to find the sum of all subsets of size K." }, { "code": null, "e": 613, "s": 348, "text": "Input: \n1. The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.\n2. The first line of each test case contains two integers N and K.\n3. The next line contains N space-separated integers." }, { "code": null, "e": 771, "s": 613, "text": "\nOutput: For each test case, print the answer\n\nConstraints:\n1. 1 <= T <= 10\n2. 1 <= K <= N <= 12\n3. 1 <= arr[i] <= 100\n\nExample:\nInput:\n2\n4 2\n1 2 3 5\n1 1\n20" }, { "code": null, "e": 930, "s": 771, "text": "Output:\n33\n20\n\nExplanation:\nTest Case 1: Subsets are {1, 2}, {1, 3}, {1, 5}, {2, 3}, {2, 5}, {3, 5}, Summation of all subsets sum = 3 + 4 + 6 + 5 + 7 + 8 = 33" }, { "code": null, "e": 932, "s": 930, "text": "0" }, { "code": null, "e": 953, "s": 932, "text": "anutiger5 months ago" }, { "code": null, "e": 1461, "s": 953, "text": "void helper(int ind,int curk,int k,int *arr,int n ,int s,int &sum){\n if(curk == k){\n sum += s;\n return;\n }\n if(ind == n)\n return;\n helper(ind + 1,curk + 1,k,arr,n,s + arr[ind],sum);\n helper(ind + 1,curk,k,arr,n,s,sum);\n}\nint main()\n {\n\tint t;\n\tcin>> t;\n\twhile(t--){\n\t int n,k;\n\t cin >> n >> k;\n\t int arr[n];\n\t for(int i = 0 ;i < n ; i ++){\n\t cin >> arr[i];\n\t }\n\t int sum = 0;\n\t helper(0,0,k,arr,n,0,sum);\n\t cout<<sum<<endl;\n\t}\n\treturn 0;\n}" }, { "code": null, "e": 1463, "s": 1461, "text": "0" }, { "code": null, "e": 1481, "s": 1463, "text": "Akash8 months ago" }, { "code": null, "e": 1487, "s": 1481, "text": "Akash" }, { "code": null, "e": 1498, "s": 1487, "text": "import sys" }, { "code": null, "e": 1553, "s": 1498, "text": "def intReadLine(): return int(sys.stdin.readline())" }, { "code": null, "e": 1626, "s": 1553, "text": "def readLine(): return map(int, sys.stdin.readline().strip().split())" }, { "code": null, "e": 1652, "s": 1626, "text": "num_cases = intReadLine()" }, { "code": null, "e": 1759, "s": 1652, "text": "def bitCount(num): count = 0 while num > 0: count += (num&1) num >>= 1 return count" }, { "code": null, "e": 1857, "s": 1759, "text": "for cas in range(num_cases): N, K = readLine() arr = list(readLine()) pre_sum = sum(arr)" }, { "code": null, "e": 1870, "s": 1857, "text": " mult = 0" }, { "code": null, "e": 1989, "s": 1870, "text": " for i in range(2**N): bitcount = bitCount(i) if bitcount == K and (i & 1 == 1): mult += 1" }, { "code": null, "e": 2017, "s": 1989, "text": " ans = int(mult*pre_sum)" }, { "code": null, "e": 2032, "s": 2017, "text": " print(ans)" }, { "code": null, "e": 2034, "s": 2032, "text": "0" }, { "code": null, "e": 2059, "s": 2034, "text": "Shadab Anwar9 months ago" }, { "code": null, "e": 2072, "s": 2059, "text": "Shadab Anwar" }, { "code": null, "e": 2074, "s": 2072, "text": "0" }, { "code": null, "e": 2103, "s": 2074, "text": "Amit Singh Negi11 months ago" }, { "code": null, "e": 2119, "s": 2103, "text": "Amit Singh Negi" }, { "code": null, "e": 3061, "s": 2119, "text": "import java.util.*;import java.lang.*;import java.io.*;import java.util.stream.*;class GFG { public static void main (String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); while(t-- > 0){ String[] ip = br.readLine().split(\" \"); int n = Integer.parseInt(ip[0]), k = Integer.parseInt(ip[1]), sum = 0; int[] nums = Stream.of(br.readLine().split(\" \")).mapToInt(Integer::new).toArray(); for(int i = 1; i < (1 << n); i++){//iterate all the possible 2 ^ n subsets if(Integer.bitCount(i) != k) continue;//skip other than k for(int j = 0, temp = i; j < n; j++, temp >>= 1) if((temp & 1) == 1)//current bit is set add nums[i] to sum sum += nums[j]; } System.out.println(sum); } }}" }, { "code": null, "e": 3063, "s": 3061, "text": "0" }, { "code": null, "e": 3087, "s": 3063, "text": "pradeep kumar1 year ago" }, { "code": null, "e": 3101, "s": 3087, "text": "pradeep kumar" }, { "code": null, "e": 3247, "s": 3101, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 3283, "s": 3247, "text": " Login to access your submissions. " }, { "code": null, "e": 3293, "s": 3283, "text": "\nProblem\n" }, { "code": null, "e": 3303, "s": 3293, "text": "\nContest\n" }, { "code": null, "e": 3366, "s": 3303, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 3514, "s": 3366, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 3722, "s": 3514, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 3828, "s": 3722, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Data Scientist vs Data Engineer Salary | Towards Data Science
IntroductionData ScientistData EngineerSummaryReferences Introduction Data Scientist Data Engineer Summary References Note: This article is the third, a part of a continuing series on reported salaries between popular data/tech roles. I will link the other two at the end of this article. This article aims not to compare roles as if one deserves more money or not, but is instead a guide allowing professionals in these two fields to assess against their current salary. However cliche, it is still important to remember these two things when asking for a higher salary: it does not hurt to ask, and sometimes, you will not get what you do not ask for. Please keep in mind that these are more general statistics, as you could be specific as you want to be to see what your salary should be. Instead, these values are instead a directional guide for you to use. Data scientists and data engineers share certain skills and experiences with one another, however, there are some key differences, and those can lead to different salaries. With that being said, let’s jump right into some salary examples for both of these roles below from real data. Since I have already written a few articles on data science salaries, I will include the most important information here, along with a few different examples. Here are some of the expected titles you can see as a data scientist that might have a significant change in salary as well: Entry Level Data Scientist → Data Scientist → Senior Data Scientist Lead Data Scientist — Data Science Manager — Data Science Director In addition to these titles, there are also some seniority levels like I, II, and III. Below, I will show the range of salaries by title with their respective years required or expected. Keep in mind that these roles are based on a US average (based on PayScale [3]): Average Overall Data Scientist → $96,455 Average Entry-Level Data Scientist → $85,312 (1 year) Average Early-Career Data Scientist → $95,121 (1–4 years) Average Mid-Career Data Scientist → $109,696 (5–9 years) Average Experienced Data Scientist → $136,051 (10–19 years) Do I agree with these numbers? No. If you have read previous articles, below, is where I will include reported salaries around different cities, along with different skillsets as well. Ann Arbor, Michigan → $88,197 Cambridge, Massachusetts → $110,213 Denver, Colorado → $92,924 Here are specific cities and skills: Charlotte, North Carolina + Natural Language Processing (NLP) → $70,000 Charlotte, North Carolina + Tableau Software → $79,096 Atlanta, Georgia + Java → $80,000 The average city salaries themselves seem more aligned with reality, whereas the specific skills associated with cities seem too low. I believe the reason that is, is because when you filter by specific skill, you are stripping away all the other skills. So, a workaround might be to find the average salary of the city and then compare the difference between the above skills to get a more realistic salary estimate. I do think it is interesting that the NLP skill is less lucrative than Tableau, however, I think NLP is perhaps too specific and maybe less misunderstood, whereas Tableau is widely understood, and most data scientists do not think to add that to their resume since it is more data analyst oriented— this note might be something to keep in mind as you realize your salary or edit your resume — the long story short, do not make assumptions, and look to be unique with your skillset. I do not know many data scientists who use Java, but I did think it was interesting that the data included in these reports had that skill as an option, so maybe there is a market out there for Java for a reason I am not sure of (perhaps, it is software engineers transitioning to data scientists). Now that we have a good sense of data science salaries including different factors like location and skills, let’s dive deeper into what a more specific data engineer salary looks like. Out of all of these salary comparisons, data engineers and data scientists seem to have a more similar range, as we will see below. Here are some of the expected titles you can see as a data engineer that might have a significant change in salary as well: Data Engineer → Senior Data Engineer → Data Engineering Manager Lead Software Engineer — Data Scientist (yes, with a specialization in data engineering) In addition to these titles, there are also some seniority levels like I, II, and III. Below, I will show the range of salaries by title with their respective years required or expected. Keep in mind that these roles are based on a US average (based on PayScale [5]): Average Overall Data Engineer → $92,519 Average Entry-Level Data Engineer → $77,350 (1 year) Average Early-Career Data Engineer → $87,851 (1–4 years) Average Mid-Career Data Engineer → $103,467 (5–9 years) Average Experienced Data Engineer → $117,918 (10–19 years) Do I agree with these numbers? No. I think each title should be shifted at least once, as in early-career salary should be that of a mid-career or experienced data engineer, depending on where you live, as well — so let’s dive deeper into specific location averages. New York, New York → $104,615 Seattle, Washington → $105,076 San Francisco, California → $123,859 Austin, Texas → $96,290 These city averages make more sense than the overall averages. The most interesting is the difference of San Francisco, however, still expected, as the cost of living there is incredibly high. Now, let’s look into specific skills for these cities: New York, New York + Scala → $121,755 Seattle, Washington + Big Data Analytics → $107,442 San Francisco, California+ Apache Hadoop Skills → $123,672 Austin, Texas + Amazon Web Services (AWS) → $97,436 Out of all of these salaries, the city of San Francisco saw a decrease in salary when adding a skill — this statement reiterates that you might want to add all of your skills and not just one, when looking into your personalized report. New York saw the biggest jump with Scala, which personally, I agree with, as it is a great skill and quite difficult to master. Salary has several characteristics that can either allow it to increase or decrease. We just talked about two factors, years of experience, location (city) and skills. There are other factors to consider as well, including, but not limited to: the interview itself, resume itself, negotiation skills, bonuses, shares, education, and certifications. To summarize, here are some key takeaways of data scientist versus data engineer salaries: * Average US data scientist salary $96,455* Average US data engineer salary $92,519* These two roles share perhaps the most similar salary ranges* Data scientists focus more on creating models from existing, packaged machine learning algorithms in Python, while data engineers focus more on utilizing SQL for ETL/ELT with regards to data* Several factors contribute to salary, the most important most likely being seniority, city, and skills I hope you found my article both interesting and useful. Please feel free to comment down below if you agree or disagree with these salary comparisons. Why or why not? What other factors do you think are important to point out in regards to salary? These can certainly be clarified even further, but I hope I was able to shed some light on the differences between data scientist and data engineer salaries. Lastly, I can ask the same question again, how do you see salaries being impacted by remote positions, especially when the city is such a big factor in determining salary? Thank you for reading! I am not affiliated with any of these companies. Please feel free to check out my profile, Matt Przybyla, and other articles, as well as subscribe to receive email notifications for my blogs by following the link below, or by clicking on the subscribe icon on the top of the screen by the follow icon, and reach out to me on LinkedIn if you have any questions or comments. Subscribe link: https://datascience2.medium.com/subscribe I have also written a similar article discussing machine learning engineer salaries versus data scientist salaries here [6], as well as the differences between data scientists and data analyst salaries here [7]. This article outlines and highlights similar characteristics of each, respective salary. Keep in mind that for both of these articles, these are not my salaries, and are reported by PayScale, and other actual data scientists, data engineers, data analysts, and machine learning engineers. So, these articles are in turn discussions around real data and are intended for you to better gain an understanding of what makes a role (in general), increase or decrease in salary amount based on certain factors. Once again, this salary data is gathered from PayScale, and if you would like a more specific estimate, then you can use the salary survey [8]. [1] Photo by Ryan Quintal on Unsplash, (2019) [2] Photo by Copernico on Unsplash, (2020) [3] PayScale, Data Scientist Salary, (2021) [4] Photo by Fotis Fotopoulos on Unsplash, (2018) [5] PayScale, Data Engineer Salary, (2021) [6] M.Przybyla, Data Scientist vs Machine Learning Engineer Salary, (2021) [7] M. Przybyla, Data Scientist vs Data Analyst Salary, (2021) [8] PayScale, PayScale Salary Survey, (2021)
[ { "code": null, "e": 229, "s": 172, "text": "IntroductionData ScientistData EngineerSummaryReferences" }, { "code": null, "e": 242, "s": 229, "text": "Introduction" }, { "code": null, "e": 257, "s": 242, "text": "Data Scientist" }, { "code": null, "e": 271, "s": 257, "text": "Data Engineer" }, { "code": null, "e": 279, "s": 271, "text": "Summary" }, { "code": null, "e": 290, "s": 279, "text": "References" }, { "code": null, "e": 296, "s": 290, "text": "Note:" }, { "code": null, "e": 461, "s": 296, "text": "This article is the third, a part of a continuing series on reported salaries between popular data/tech roles. I will link the other two at the end of this article." }, { "code": null, "e": 1034, "s": 461, "text": "This article aims not to compare roles as if one deserves more money or not, but is instead a guide allowing professionals in these two fields to assess against their current salary. However cliche, it is still important to remember these two things when asking for a higher salary: it does not hurt to ask, and sometimes, you will not get what you do not ask for. Please keep in mind that these are more general statistics, as you could be specific as you want to be to see what your salary should be. Instead, these values are instead a directional guide for you to use." }, { "code": null, "e": 1318, "s": 1034, "text": "Data scientists and data engineers share certain skills and experiences with one another, however, there are some key differences, and those can lead to different salaries. With that being said, let’s jump right into some salary examples for both of these roles below from real data." }, { "code": null, "e": 1477, "s": 1318, "text": "Since I have already written a few articles on data science salaries, I will include the most important information here, along with a few different examples." }, { "code": null, "e": 1602, "s": 1477, "text": "Here are some of the expected titles you can see as a data scientist that might have a significant change in salary as well:" }, { "code": null, "e": 1670, "s": 1602, "text": "Entry Level Data Scientist → Data Scientist → Senior Data Scientist" }, { "code": null, "e": 1737, "s": 1670, "text": "Lead Data Scientist — Data Science Manager — Data Science Director" }, { "code": null, "e": 1824, "s": 1737, "text": "In addition to these titles, there are also some seniority levels like I, II, and III." }, { "code": null, "e": 1924, "s": 1824, "text": "Below, I will show the range of salaries by title with their respective years required or expected." }, { "code": null, "e": 2005, "s": 1924, "text": "Keep in mind that these roles are based on a US average (based on PayScale [3]):" }, { "code": null, "e": 2046, "s": 2005, "text": "Average Overall Data Scientist → $96,455" }, { "code": null, "e": 2100, "s": 2046, "text": "Average Entry-Level Data Scientist → $85,312 (1 year)" }, { "code": null, "e": 2158, "s": 2100, "text": "Average Early-Career Data Scientist → $95,121 (1–4 years)" }, { "code": null, "e": 2215, "s": 2158, "text": "Average Mid-Career Data Scientist → $109,696 (5–9 years)" }, { "code": null, "e": 2275, "s": 2215, "text": "Average Experienced Data Scientist → $136,051 (10–19 years)" }, { "code": null, "e": 2306, "s": 2275, "text": "Do I agree with these numbers?" }, { "code": null, "e": 2310, "s": 2306, "text": "No." }, { "code": null, "e": 2460, "s": 2310, "text": "If you have read previous articles, below, is where I will include reported salaries around different cities, along with different skillsets as well." }, { "code": null, "e": 2490, "s": 2460, "text": "Ann Arbor, Michigan → $88,197" }, { "code": null, "e": 2526, "s": 2490, "text": "Cambridge, Massachusetts → $110,213" }, { "code": null, "e": 2553, "s": 2526, "text": "Denver, Colorado → $92,924" }, { "code": null, "e": 2590, "s": 2553, "text": "Here are specific cities and skills:" }, { "code": null, "e": 2662, "s": 2590, "text": "Charlotte, North Carolina + Natural Language Processing (NLP) → $70,000" }, { "code": null, "e": 2717, "s": 2662, "text": "Charlotte, North Carolina + Tableau Software → $79,096" }, { "code": null, "e": 2751, "s": 2717, "text": "Atlanta, Georgia + Java → $80,000" }, { "code": null, "e": 3169, "s": 2751, "text": "The average city salaries themselves seem more aligned with reality, whereas the specific skills associated with cities seem too low. I believe the reason that is, is because when you filter by specific skill, you are stripping away all the other skills. So, a workaround might be to find the average salary of the city and then compare the difference between the above skills to get a more realistic salary estimate." }, { "code": null, "e": 3651, "s": 3169, "text": "I do think it is interesting that the NLP skill is less lucrative than Tableau, however, I think NLP is perhaps too specific and maybe less misunderstood, whereas Tableau is widely understood, and most data scientists do not think to add that to their resume since it is more data analyst oriented— this note might be something to keep in mind as you realize your salary or edit your resume — the long story short, do not make assumptions, and look to be unique with your skillset." }, { "code": null, "e": 3950, "s": 3651, "text": "I do not know many data scientists who use Java, but I did think it was interesting that the data included in these reports had that skill as an option, so maybe there is a market out there for Java for a reason I am not sure of (perhaps, it is software engineers transitioning to data scientists)." }, { "code": null, "e": 4136, "s": 3950, "text": "Now that we have a good sense of data science salaries including different factors like location and skills, let’s dive deeper into what a more specific data engineer salary looks like." }, { "code": null, "e": 4268, "s": 4136, "text": "Out of all of these salary comparisons, data engineers and data scientists seem to have a more similar range, as we will see below." }, { "code": null, "e": 4392, "s": 4268, "text": "Here are some of the expected titles you can see as a data engineer that might have a significant change in salary as well:" }, { "code": null, "e": 4456, "s": 4392, "text": "Data Engineer → Senior Data Engineer → Data Engineering Manager" }, { "code": null, "e": 4545, "s": 4456, "text": "Lead Software Engineer — Data Scientist (yes, with a specialization in data engineering)" }, { "code": null, "e": 4632, "s": 4545, "text": "In addition to these titles, there are also some seniority levels like I, II, and III." }, { "code": null, "e": 4732, "s": 4632, "text": "Below, I will show the range of salaries by title with their respective years required or expected." }, { "code": null, "e": 4813, "s": 4732, "text": "Keep in mind that these roles are based on a US average (based on PayScale [5]):" }, { "code": null, "e": 4853, "s": 4813, "text": "Average Overall Data Engineer → $92,519" }, { "code": null, "e": 4906, "s": 4853, "text": "Average Entry-Level Data Engineer → $77,350 (1 year)" }, { "code": null, "e": 4963, "s": 4906, "text": "Average Early-Career Data Engineer → $87,851 (1–4 years)" }, { "code": null, "e": 5019, "s": 4963, "text": "Average Mid-Career Data Engineer → $103,467 (5–9 years)" }, { "code": null, "e": 5078, "s": 5019, "text": "Average Experienced Data Engineer → $117,918 (10–19 years)" }, { "code": null, "e": 5109, "s": 5078, "text": "Do I agree with these numbers?" }, { "code": null, "e": 5113, "s": 5109, "text": "No." }, { "code": null, "e": 5345, "s": 5113, "text": "I think each title should be shifted at least once, as in early-career salary should be that of a mid-career or experienced data engineer, depending on where you live, as well — so let’s dive deeper into specific location averages." }, { "code": null, "e": 5375, "s": 5345, "text": "New York, New York → $104,615" }, { "code": null, "e": 5406, "s": 5375, "text": "Seattle, Washington → $105,076" }, { "code": null, "e": 5443, "s": 5406, "text": "San Francisco, California → $123,859" }, { "code": null, "e": 5467, "s": 5443, "text": "Austin, Texas → $96,290" }, { "code": null, "e": 5660, "s": 5467, "text": "These city averages make more sense than the overall averages. The most interesting is the difference of San Francisco, however, still expected, as the cost of living there is incredibly high." }, { "code": null, "e": 5715, "s": 5660, "text": "Now, let’s look into specific skills for these cities:" }, { "code": null, "e": 5753, "s": 5715, "text": "New York, New York + Scala → $121,755" }, { "code": null, "e": 5805, "s": 5753, "text": "Seattle, Washington + Big Data Analytics → $107,442" }, { "code": null, "e": 5864, "s": 5805, "text": "San Francisco, California+ Apache Hadoop Skills → $123,672" }, { "code": null, "e": 5916, "s": 5864, "text": "Austin, Texas + Amazon Web Services (AWS) → $97,436" }, { "code": null, "e": 6281, "s": 5916, "text": "Out of all of these salaries, the city of San Francisco saw a decrease in salary when adding a skill — this statement reiterates that you might want to add all of your skills and not just one, when looking into your personalized report. New York saw the biggest jump with Scala, which personally, I agree with, as it is a great skill and quite difficult to master." }, { "code": null, "e": 6630, "s": 6281, "text": "Salary has several characteristics that can either allow it to increase or decrease. We just talked about two factors, years of experience, location (city) and skills. There are other factors to consider as well, including, but not limited to: the interview itself, resume itself, negotiation skills, bonuses, shares, education, and certifications." }, { "code": null, "e": 6721, "s": 6630, "text": "To summarize, here are some key takeaways of data scientist versus data engineer salaries:" }, { "code": null, "e": 7163, "s": 6721, "text": "* Average US data scientist salary $96,455* Average US data engineer salary $92,519* These two roles share perhaps the most similar salary ranges* Data scientists focus more on creating models from existing, packaged machine learning algorithms in Python, while data engineers focus more on utilizing SQL for ETL/ELT with regards to data* Several factors contribute to salary, the most important most likely being seniority, city, and skills" }, { "code": null, "e": 7570, "s": 7163, "text": "I hope you found my article both interesting and useful. Please feel free to comment down below if you agree or disagree with these salary comparisons. Why or why not? What other factors do you think are important to point out in regards to salary? These can certainly be clarified even further, but I hope I was able to shed some light on the differences between data scientist and data engineer salaries." }, { "code": null, "e": 7742, "s": 7570, "text": "Lastly, I can ask the same question again, how do you see salaries being impacted by remote positions, especially when the city is such a big factor in determining salary?" }, { "code": null, "e": 7765, "s": 7742, "text": "Thank you for reading!" }, { "code": null, "e": 7814, "s": 7765, "text": "I am not affiliated with any of these companies." }, { "code": null, "e": 8138, "s": 7814, "text": "Please feel free to check out my profile, Matt Przybyla, and other articles, as well as subscribe to receive email notifications for my blogs by following the link below, or by clicking on the subscribe icon on the top of the screen by the follow icon, and reach out to me on LinkedIn if you have any questions or comments." }, { "code": null, "e": 8196, "s": 8138, "text": "Subscribe link: https://datascience2.medium.com/subscribe" }, { "code": null, "e": 8913, "s": 8196, "text": "I have also written a similar article discussing machine learning engineer salaries versus data scientist salaries here [6], as well as the differences between data scientists and data analyst salaries here [7]. This article outlines and highlights similar characteristics of each, respective salary. Keep in mind that for both of these articles, these are not my salaries, and are reported by PayScale, and other actual data scientists, data engineers, data analysts, and machine learning engineers. So, these articles are in turn discussions around real data and are intended for you to better gain an understanding of what makes a role (in general), increase or decrease in salary amount based on certain factors." }, { "code": null, "e": 9057, "s": 8913, "text": "Once again, this salary data is gathered from PayScale, and if you would like a more specific estimate, then you can use the salary survey [8]." }, { "code": null, "e": 9103, "s": 9057, "text": "[1] Photo by Ryan Quintal on Unsplash, (2019)" }, { "code": null, "e": 9146, "s": 9103, "text": "[2] Photo by Copernico on Unsplash, (2020)" }, { "code": null, "e": 9190, "s": 9146, "text": "[3] PayScale, Data Scientist Salary, (2021)" }, { "code": null, "e": 9240, "s": 9190, "text": "[4] Photo by Fotis Fotopoulos on Unsplash, (2018)" }, { "code": null, "e": 9283, "s": 9240, "text": "[5] PayScale, Data Engineer Salary, (2021)" }, { "code": null, "e": 9358, "s": 9283, "text": "[6] M.Przybyla, Data Scientist vs Machine Learning Engineer Salary, (2021)" }, { "code": null, "e": 9421, "s": 9358, "text": "[7] M. Przybyla, Data Scientist vs Data Analyst Salary, (2021)" } ]
Android - Environment Setup
You will be glad to know that you can start your Android application development on either of the following operating systems − Microsoft Windows XP or later version. Microsoft Windows XP or later version. Mac OS X 10.5.8 or later version with Intel chip. Mac OS X 10.5.8 or later version with Intel chip. Linux including GNU C Library 2.7 or later. Linux including GNU C Library 2.7 or later. Second point is that all the required tools to develop Android applications are freely available and can be downloaded from the Web. Following is the list of software's you will need before you start your Android application programming. Java JDK5 or later version Java JDK5 or later version Android Studio Android Studio Here last two components are optional and if you are working on Windows machine then these components make your life easy while doing Java based application development. So let us have a look how to proceed to set required environment. You can download the latest version of Java JDK from Oracle's Java site − Java SE Downloads. You will find instructions for installing JDK in downloaded files, follow the given instructions to install and configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively. If you are running Windows and installed the JDK in C:\jdk1.8.0_102, you would have to put the following line in your C:\autoexec.bat file. set PATH=C:\jdk1.8.0_102\bin;%PATH% set JAVA_HOME=C:\jdk1.8.0_102 Alternatively, you could also right-click on My Computer, select Properties, then Advanced, then Environment Variables. Then, you would update the PATH value and press the OK button. On Linux, if the SDK is installed in /usr/local/jdk1.8.0_102 and you use the C shell, you would put the following code into your .cshrc file. setenv PATH /usr/local/jdk1.8.0_102/bin:$PATH setenv JAVA_HOME /usr/local/jdk1.8.0_102 Alternatively, if you use Android studio, then it will know automatically where you have installed your Java. There are so many sophisticated Technologies are available to develop android applications, the familiar technologies, which are predominantly using tools as follows Android Studio Android Studio Eclipse IDE(Deprecated) Eclipse IDE(Deprecated) 46 Lectures 7.5 hours Aditya Dua 32 Lectures 3.5 hours Sharad Kumar 9 Lectures 1 hours Abhilash Nelson 14 Lectures 1.5 hours Abhilash Nelson 15 Lectures 1.5 hours Abhilash Nelson 10 Lectures 1 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 3735, "s": 3607, "text": "You will be glad to know that you can start your Android application development on either of the following operating systems −" }, { "code": null, "e": 3774, "s": 3735, "text": "Microsoft Windows XP or later version." }, { "code": null, "e": 3813, "s": 3774, "text": "Microsoft Windows XP or later version." }, { "code": null, "e": 3863, "s": 3813, "text": "Mac OS X 10.5.8 or later version with Intel chip." }, { "code": null, "e": 3913, "s": 3863, "text": "Mac OS X 10.5.8 or later version with Intel chip." }, { "code": null, "e": 3957, "s": 3913, "text": "Linux including GNU C Library 2.7 or later." }, { "code": null, "e": 4001, "s": 3957, "text": "Linux including GNU C Library 2.7 or later." }, { "code": null, "e": 4239, "s": 4001, "text": "Second point is that all the required tools to develop Android applications are freely available and can be downloaded from the Web. Following is the list of software's you will need before you start your Android application programming." }, { "code": null, "e": 4266, "s": 4239, "text": "Java JDK5 or later version" }, { "code": null, "e": 4293, "s": 4266, "text": "Java JDK5 or later version" }, { "code": null, "e": 4309, "s": 4293, "text": "Android Studio " }, { "code": null, "e": 4325, "s": 4309, "text": "Android Studio " }, { "code": null, "e": 4561, "s": 4325, "text": "Here last two components are optional and if you are working on Windows machine then these components make your life easy while doing Java based application development. So let us have a look how to proceed to set required environment." }, { "code": null, "e": 4962, "s": 4561, "text": "You can download the latest version of Java JDK from Oracle's Java site − Java SE Downloads. You will find instructions for installing JDK in downloaded files, follow the given instructions to install and configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively." }, { "code": null, "e": 5102, "s": 4962, "text": "If you are running Windows and installed the JDK in C:\\jdk1.8.0_102, you would have to put the following line in your C:\\autoexec.bat file." }, { "code": null, "e": 5169, "s": 5102, "text": "set PATH=C:\\jdk1.8.0_102\\bin;%PATH%\nset JAVA_HOME=C:\\jdk1.8.0_102\n" }, { "code": null, "e": 5352, "s": 5169, "text": "Alternatively, you could also right-click on My Computer, select Properties, then Advanced, then Environment Variables. Then, you would update the PATH value and press the OK button." }, { "code": null, "e": 5494, "s": 5352, "text": "On Linux, if the SDK is installed in /usr/local/jdk1.8.0_102 and you use the C shell, you would put the following code into your .cshrc file." }, { "code": null, "e": 5582, "s": 5494, "text": "setenv PATH /usr/local/jdk1.8.0_102/bin:$PATH\nsetenv JAVA_HOME /usr/local/jdk1.8.0_102\n" }, { "code": null, "e": 5692, "s": 5582, "text": "Alternatively, if you use Android studio, then it will know automatically where you have installed your Java." }, { "code": null, "e": 5858, "s": 5692, "text": "There are so many sophisticated Technologies are available to develop android applications, the familiar technologies, which are predominantly using tools as follows" }, { "code": null, "e": 5873, "s": 5858, "text": "Android Studio" }, { "code": null, "e": 5888, "s": 5873, "text": "Android Studio" }, { "code": null, "e": 5912, "s": 5888, "text": "Eclipse IDE(Deprecated)" }, { "code": null, "e": 5936, "s": 5912, "text": "Eclipse IDE(Deprecated)" }, { "code": null, "e": 5971, "s": 5936, "text": "\n 46 Lectures \n 7.5 hours \n" }, { "code": null, "e": 5983, "s": 5971, "text": " Aditya Dua" }, { "code": null, "e": 6018, "s": 5983, "text": "\n 32 Lectures \n 3.5 hours \n" }, { "code": null, "e": 6032, "s": 6018, "text": " Sharad Kumar" }, { "code": null, "e": 6064, "s": 6032, "text": "\n 9 Lectures \n 1 hours \n" }, { "code": null, "e": 6081, "s": 6064, "text": " Abhilash Nelson" }, { "code": null, "e": 6116, "s": 6081, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6133, "s": 6116, "text": " Abhilash Nelson" }, { "code": null, "e": 6168, "s": 6133, "text": "\n 15 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6185, "s": 6168, "text": " Abhilash Nelson" }, { "code": null, "e": 6218, "s": 6185, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 6235, "s": 6218, "text": " Abhilash Nelson" }, { "code": null, "e": 6242, "s": 6235, "text": " Print" }, { "code": null, "e": 6253, "s": 6242, "text": " Add Notes" } ]
Minimum move to end operations to make all strings equal
13 Jun, 2022 Given n strings that are permutations of each other. We need to make all strings same with an operation that takes front character of any string and moves it to the end.Examples: Input : n = 2 arr[] = {"molzv", "lzvmo"} Output : 2 Explanation: In first string, we remove first element("m") from first string and append it end. Then we move second character of first string and move it to end. So after 2 operations, both strings become same. Input : n = 3 arr[] = {"kc", "kc", "kc"} Output : 0 Explanation: already all strings are equal. The move to end operation is basically left rotation. We use the approach discussed in check if strings are rotations of each other or not to count a number of move to front operations required to make two strings the same. We one by one consider every string as the target string. We count rotations required to make all other strings the same as the current target and finally return a minimum of all counts.Below is the implementation of the above approach. C++ Java Python 3 C# Javascript // CPP program to make all strings same using// move to end operations.#include <bits/stdc++.h>using namespace std; // Returns minimum number of moves to end// operations to make all strings same.int minimunMoves(string arr[], int n){ int ans = INT_MAX; for (int i = 0; i < n; i++) { int curr_count = 0; // Consider s[i] as target string and // count rotations required to make // all other strings same as str[i]. for (int j = 0; j < n; j++) { string tmp = arr[j] + arr[j]; // find function returns the index where we // found arr[i] which is actually count of // move-to-front operations. int index = tmp.find(arr[i]); // If any two strings are not rotations of // each other, we can't make them same. if (index == string::npos) return -1; curr_count += index; } ans = min(curr_count, ans); } return ans;} // driver code for above function.int main(){ string arr[] = {"xzzwo", "zwoxz", "zzwox", "xzzwo"}; int n = sizeof(arr)/sizeof(arr[0]); cout << minimunMoves(arr, n); return 0;} // Java program to make all// strings same using move// to end operations.import java.util.*;class GFG{ // Returns minimum number of// moves to end operations// to make all strings same.static int minimunMoves(String arr[], int n){ int ans = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { int curr_count = 0; // Consider s[i] as target // string and count rotations // required to make all other // strings same as str[i]. String tmp = ""; for (int j = 0; j < n; j++) { tmp = arr[j] + arr[j]; // find function returns the // index where we found arr[i] // which is actually count of // move-to-front operations. int index = tmp.indexOf(arr[i]); // If any two strings are not // rotations of each other, // we can't make them same. if (index != -1) curr_count += index; else curr_count = -1; } ans = Math.min(curr_count, ans); } return ans;} // Driver codepublic static void main(String args[]){ String arr[] = {"xzzwo", "zwoxz", "zzwox", "xzzwo"}; int n = arr.length; System.out.println(minimunMoves(arr, n));}} // This code is contributed// by Kirti_Mangal # Python 3 program to make all strings# same using move to end operations.import sys # Returns minimum number of moves to end# operations to make all strings same.def minimunMoves(arr, n): ans = sys.maxsize for i in range(n): curr_count = 0 # Consider s[i] as target string and # count rotations required to make # all other strings same as str[i]. for j in range(n): tmp = arr[j] + arr[j] # find function returns the index where # we found arr[i] which is actually # count of move-to-front operations. index = tmp.find(arr[i]) # If any two strings are not rotations of # each other, we can't make them same. if (index == len(arr[i])): return -1 curr_count += index ans = min(curr_count, ans) return ans # Driver Codeif __name__ == "__main__": arr = ["xzzwo", "zwoxz", "zzwox", "xzzwo"] n = len(arr) print( minimunMoves(arr, n)) # This code is contributed by ita_c using System; // C# program to make all// strings same using move// to end operations.public class GFG{ // Returns minimum number of// moves to end operations// to make all strings same.public static int minimunMoves(string[] arr, int n){ int ans = int.MaxValue; for (int i = 0; i < n; i++) { int curr_count = 0; // Consider s[i] as target // string and count rotations // required to make all other // strings same as str[i]. string tmp = ""; for (int j = 0; j < n; j++) { tmp = arr[j] + arr[j]; // find function returns the // index where we found arr[i] // which is actually count of // move-to-front operations. int index = tmp.IndexOf(arr[i], StringComparison.Ordinal); // If any two strings are not // rotations of each other, // we can't make them same. if (index == arr[i].Length) { return -1; } curr_count += index; } ans = Math.Min(curr_count, ans); } return ans;} // Driver codepublic static void Main(string[] args){ string[] arr = new string[] {"xzzwo", "zwoxz", "zzwox", "xzzwo"}; int n = arr.Length; Console.WriteLine(minimunMoves(arr, n));}} // This code is contributed by Shrikant13 <script> // Javascript program to make all// strings same using move// to end operations. // Returns minimum number of // moves to end operations // to make all strings same. function minimunMoves(arr,n) { let ans = Number.MAX_VALUE; for (let i = 0; i < n; i++) { let curr_count = 0; // Consider s[i] as target // string and count rotations // required to make all other // strings same as str[i]. let tmp = ""; for (let j = 0; j < n; j++) { tmp = arr[j] + arr[j]; // find function returns the // index where we found arr[i] // which is actually count of // move-to-front operations. let index = tmp.indexOf(arr[i]); // If any two strings are not // rotations of each other, // we can't make them same. if (index == arr[i].length) return -1; curr_count += index; } ans = Math.min(curr_count, ans); } return ans; } // Driver code let arr=["xzzwo", "zwoxz", "zzwox", "xzzwo"]; let n = arr.length; document.write(minimunMoves(arr, n)); // This code is contributed by avanitrachhadiya2155 </script> Output: 5 Time Complexity : O(n3), Where n is the size of given string (n2 for the two nested for loops and n is for the function used as find())Auxiliary Space: O(n) This article is contributed by Pawan Asipu. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Kirti_Mangal shrikanth13 ukasp avanitrachhadiya2155 karthikkrapa18 codewithmini rotation Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different Methods to Reverse a String in C++ Python program to check if a string is palindrome or not Check for Balanced Brackets in an expression (well-formedness) using Stack KMP Algorithm for Pattern Searching Longest Palindromic Substring | Set 1 Length of the longest substring without repeating characters Top 50 String Coding Problems for Interviews Check whether two strings are anagram of each other Convert string to char array in C++ Reverse words in a given string
[ { "code": null, "e": 54, "s": 26, "text": "\n13 Jun, 2022" }, { "code": null, "e": 235, "s": 54, "text": "Given n strings that are permutations of each other. We need to make all strings same with an operation that takes front character of any string and moves it to the end.Examples: " }, { "code": null, "e": 612, "s": 235, "text": "Input : n = 2\n arr[] = {\"molzv\", \"lzvmo\"}\nOutput : 2\nExplanation: In first string, we remove\nfirst element(\"m\") from first string and \nappend it end. Then we move second character\nof first string and move it to end. So after\n2 operations, both strings become same.\n\nInput : n = 3\n arr[] = {\"kc\", \"kc\", \"kc\"}\nOutput : 0\nExplanation: already all strings are equal." }, { "code": null, "e": 1077, "s": 614, "text": "The move to end operation is basically left rotation. We use the approach discussed in check if strings are rotations of each other or not to count a number of move to front operations required to make two strings the same. We one by one consider every string as the target string. We count rotations required to make all other strings the same as the current target and finally return a minimum of all counts.Below is the implementation of the above approach. " }, { "code": null, "e": 1081, "s": 1077, "text": "C++" }, { "code": null, "e": 1086, "s": 1081, "text": "Java" }, { "code": null, "e": 1095, "s": 1086, "text": "Python 3" }, { "code": null, "e": 1098, "s": 1095, "text": "C#" }, { "code": null, "e": 1109, "s": 1098, "text": "Javascript" }, { "code": "// CPP program to make all strings same using// move to end operations.#include <bits/stdc++.h>using namespace std; // Returns minimum number of moves to end// operations to make all strings same.int minimunMoves(string arr[], int n){ int ans = INT_MAX; for (int i = 0; i < n; i++) { int curr_count = 0; // Consider s[i] as target string and // count rotations required to make // all other strings same as str[i]. for (int j = 0; j < n; j++) { string tmp = arr[j] + arr[j]; // find function returns the index where we // found arr[i] which is actually count of // move-to-front operations. int index = tmp.find(arr[i]); // If any two strings are not rotations of // each other, we can't make them same. if (index == string::npos) return -1; curr_count += index; } ans = min(curr_count, ans); } return ans;} // driver code for above function.int main(){ string arr[] = {\"xzzwo\", \"zwoxz\", \"zzwox\", \"xzzwo\"}; int n = sizeof(arr)/sizeof(arr[0]); cout << minimunMoves(arr, n); return 0;}", "e": 2293, "s": 1109, "text": null }, { "code": "// Java program to make all// strings same using move// to end operations.import java.util.*;class GFG{ // Returns minimum number of// moves to end operations// to make all strings same.static int minimunMoves(String arr[], int n){ int ans = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { int curr_count = 0; // Consider s[i] as target // string and count rotations // required to make all other // strings same as str[i]. String tmp = \"\"; for (int j = 0; j < n; j++) { tmp = arr[j] + arr[j]; // find function returns the // index where we found arr[i] // which is actually count of // move-to-front operations. int index = tmp.indexOf(arr[i]); // If any two strings are not // rotations of each other, // we can't make them same. if (index != -1) curr_count += index; else curr_count = -1; } ans = Math.min(curr_count, ans); } return ans;} // Driver codepublic static void main(String args[]){ String arr[] = {\"xzzwo\", \"zwoxz\", \"zzwox\", \"xzzwo\"}; int n = arr.length; System.out.println(minimunMoves(arr, n));}} // This code is contributed// by Kirti_Mangal", "e": 3623, "s": 2293, "text": null }, { "code": "# Python 3 program to make all strings# same using move to end operations.import sys # Returns minimum number of moves to end# operations to make all strings same.def minimunMoves(arr, n): ans = sys.maxsize for i in range(n): curr_count = 0 # Consider s[i] as target string and # count rotations required to make # all other strings same as str[i]. for j in range(n): tmp = arr[j] + arr[j] # find function returns the index where # we found arr[i] which is actually # count of move-to-front operations. index = tmp.find(arr[i]) # If any two strings are not rotations of # each other, we can't make them same. if (index == len(arr[i])): return -1 curr_count += index ans = min(curr_count, ans) return ans # Driver Codeif __name__ == \"__main__\": arr = [\"xzzwo\", \"zwoxz\", \"zzwox\", \"xzzwo\"] n = len(arr) print( minimunMoves(arr, n)) # This code is contributed by ita_c", "e": 4676, "s": 3623, "text": null }, { "code": "using System; // C# program to make all// strings same using move// to end operations.public class GFG{ // Returns minimum number of// moves to end operations// to make all strings same.public static int minimunMoves(string[] arr, int n){ int ans = int.MaxValue; for (int i = 0; i < n; i++) { int curr_count = 0; // Consider s[i] as target // string and count rotations // required to make all other // strings same as str[i]. string tmp = \"\"; for (int j = 0; j < n; j++) { tmp = arr[j] + arr[j]; // find function returns the // index where we found arr[i] // which is actually count of // move-to-front operations. int index = tmp.IndexOf(arr[i], StringComparison.Ordinal); // If any two strings are not // rotations of each other, // we can't make them same. if (index == arr[i].Length) { return -1; } curr_count += index; } ans = Math.Min(curr_count, ans); } return ans;} // Driver codepublic static void Main(string[] args){ string[] arr = new string[] {\"xzzwo\", \"zwoxz\", \"zzwox\", \"xzzwo\"}; int n = arr.Length; Console.WriteLine(minimunMoves(arr, n));}} // This code is contributed by Shrikant13", "e": 6035, "s": 4676, "text": null }, { "code": "<script> // Javascript program to make all// strings same using move// to end operations. // Returns minimum number of // moves to end operations // to make all strings same. function minimunMoves(arr,n) { let ans = Number.MAX_VALUE; for (let i = 0; i < n; i++) { let curr_count = 0; // Consider s[i] as target // string and count rotations // required to make all other // strings same as str[i]. let tmp = \"\"; for (let j = 0; j < n; j++) { tmp = arr[j] + arr[j]; // find function returns the // index where we found arr[i] // which is actually count of // move-to-front operations. let index = tmp.indexOf(arr[i]); // If any two strings are not // rotations of each other, // we can't make them same. if (index == arr[i].length) return -1; curr_count += index; } ans = Math.min(curr_count, ans); } return ans; } // Driver code let arr=[\"xzzwo\", \"zwoxz\", \"zzwox\", \"xzzwo\"]; let n = arr.length; document.write(minimunMoves(arr, n)); // This code is contributed by avanitrachhadiya2155 </script>", "e": 7364, "s": 6035, "text": null }, { "code": null, "e": 7374, "s": 7364, "text": "Output: " }, { "code": null, "e": 7376, "s": 7374, "text": "5" }, { "code": null, "e": 7533, "s": 7376, "text": "Time Complexity : O(n3), Where n is the size of given string (n2 for the two nested for loops and n is for the function used as find())Auxiliary Space: O(n)" }, { "code": null, "e": 7953, "s": 7533, "text": "This article is contributed by Pawan Asipu. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 7966, "s": 7953, "text": "Kirti_Mangal" }, { "code": null, "e": 7978, "s": 7966, "text": "shrikanth13" }, { "code": null, "e": 7984, "s": 7978, "text": "ukasp" }, { "code": null, "e": 8005, "s": 7984, "text": "avanitrachhadiya2155" }, { "code": null, "e": 8020, "s": 8005, "text": "karthikkrapa18" }, { "code": null, "e": 8033, "s": 8020, "text": "codewithmini" }, { "code": null, "e": 8042, "s": 8033, "text": "rotation" }, { "code": null, "e": 8050, "s": 8042, "text": "Strings" }, { "code": null, "e": 8058, "s": 8050, "text": "Strings" }, { "code": null, "e": 8156, "s": 8058, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8201, "s": 8156, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 8258, "s": 8201, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 8333, "s": 8258, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" }, { "code": null, "e": 8369, "s": 8333, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 8407, "s": 8369, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 8468, "s": 8407, "text": "Length of the longest substring without repeating characters" }, { "code": null, "e": 8513, "s": 8468, "text": "Top 50 String Coding Problems for Interviews" }, { "code": null, "e": 8565, "s": 8513, "text": "Check whether two strings are anagram of each other" }, { "code": null, "e": 8601, "s": 8565, "text": "Convert string to char array in C++" } ]
Draw Clock Design using Turtle in Python
26 Jul, 2021 Turtle is an inbuilt module in Python. It provides drawing using a screen (cardboard) and turtle (pen). To draw something on the screen, we need to move the turtle (pen). To move turtle, there are some functions i.e forward(), backward(), etc. Following steps are used : Import turtle. Create Screen object and set Screen configuration. Create Turtle object and set its position and speed. Draw a dashed line and print number in circular shape. Draw center and fill color black in it Write “GFG” and “CLOCK” at required position. Below is the implementation: Python3 # import packageimport turtle # create a Screen Objectscreen = turtle.Screen() # Screen configurationscreen.setup(500, 500) # Make turtle Objectclk = turtle.Turtle() # set a Turtle object colorclk.color('Green') # set a Turtle object widthclk.width(4) def draw_hour_hand(): clk.penup() clk.home() clk.right(90) clk.pendown() clk.forward(100) # value for numbers in clockval = 0 # loop for print clock numbersfor i in range(12): # increment value by 1 val += 1 # move turtle in air clk.penup() # for circular motion clk.setheading(-30 * (i + 3) + 75) # move forward for space clk.forward(22) # move turtle to surface clk.pendown() # move forward for dash line clk.forward(15) # move turtle in air clk.penup() # move forward for space clk.forward(20) # write clock integer clk.write(str(val), align="center", font=("Arial", 12, "normal")) # colored centre by setting position# sets position of turtle at given positionclk.setpos(2, -112)clk.pendown()clk.width(2) # To fill color greenclk.fillcolor('Green') # start fillingclk.begin_fill() # make a circle of radius 5clk.circle(5) # end fillingclk.end_fill() clk.penup()draw_hour_hand()clk.setpos(-20, -64)clk.pendown()clk.penup() # Write Clock by setting positionclk.setpos(-30, -170)clk.pendown()clk.write(' GfG Clock', font=("Arial", 14, "normal"))clk.hideturtle()turtle.done() Output: pulkitagarwal03pulkit anikakapoor Python-projects Python-turtle Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Convert integer to string in Python Introduction To PYTHON Python | os.path.join() method Create a Pandas DataFrame from Lists How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON?
[ { "code": null, "e": 53, "s": 25, "text": "\n26 Jul, 2021" }, { "code": null, "e": 297, "s": 53, "text": "Turtle is an inbuilt module in Python. It provides drawing using a screen (cardboard) and turtle (pen). To draw something on the screen, we need to move the turtle (pen). To move turtle, there are some functions i.e forward(), backward(), etc." }, { "code": null, "e": 324, "s": 297, "text": "Following steps are used :" }, { "code": null, "e": 339, "s": 324, "text": "Import turtle." }, { "code": null, "e": 390, "s": 339, "text": "Create Screen object and set Screen configuration." }, { "code": null, "e": 443, "s": 390, "text": "Create Turtle object and set its position and speed." }, { "code": null, "e": 498, "s": 443, "text": "Draw a dashed line and print number in circular shape." }, { "code": null, "e": 537, "s": 498, "text": "Draw center and fill color black in it" }, { "code": null, "e": 583, "s": 537, "text": "Write “GFG” and “CLOCK” at required position." }, { "code": null, "e": 612, "s": 583, "text": "Below is the implementation:" }, { "code": null, "e": 620, "s": 612, "text": "Python3" }, { "code": "# import packageimport turtle # create a Screen Objectscreen = turtle.Screen() # Screen configurationscreen.setup(500, 500) # Make turtle Objectclk = turtle.Turtle() # set a Turtle object colorclk.color('Green') # set a Turtle object widthclk.width(4) def draw_hour_hand(): clk.penup() clk.home() clk.right(90) clk.pendown() clk.forward(100) # value for numbers in clockval = 0 # loop for print clock numbersfor i in range(12): # increment value by 1 val += 1 # move turtle in air clk.penup() # for circular motion clk.setheading(-30 * (i + 3) + 75) # move forward for space clk.forward(22) # move turtle to surface clk.pendown() # move forward for dash line clk.forward(15) # move turtle in air clk.penup() # move forward for space clk.forward(20) # write clock integer clk.write(str(val), align=\"center\", font=(\"Arial\", 12, \"normal\")) # colored centre by setting position# sets position of turtle at given positionclk.setpos(2, -112)clk.pendown()clk.width(2) # To fill color greenclk.fillcolor('Green') # start fillingclk.begin_fill() # make a circle of radius 5clk.circle(5) # end fillingclk.end_fill() clk.penup()draw_hour_hand()clk.setpos(-20, -64)clk.pendown()clk.penup() # Write Clock by setting positionclk.setpos(-30, -170)clk.pendown()clk.write(' GfG Clock', font=(\"Arial\", 14, \"normal\"))clk.hideturtle()turtle.done()", "e": 2088, "s": 620, "text": null }, { "code": null, "e": 2097, "s": 2088, "text": "Output: " }, { "code": null, "e": 2121, "s": 2099, "text": "pulkitagarwal03pulkit" }, { "code": null, "e": 2133, "s": 2121, "text": "anikakapoor" }, { "code": null, "e": 2149, "s": 2133, "text": "Python-projects" }, { "code": null, "e": 2163, "s": 2149, "text": "Python-turtle" }, { "code": null, "e": 2170, "s": 2163, "text": "Python" }, { "code": null, "e": 2268, "s": 2170, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2300, "s": 2268, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2329, "s": 2300, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2356, "s": 2329, "text": "Python Classes and Objects" }, { "code": null, "e": 2377, "s": 2356, "text": "Python OOPs Concepts" }, { "code": null, "e": 2413, "s": 2377, "text": "Convert integer to string in Python" }, { "code": null, "e": 2436, "s": 2413, "text": "Introduction To PYTHON" }, { "code": null, "e": 2467, "s": 2436, "text": "Python | os.path.join() method" }, { "code": null, "e": 2504, "s": 2467, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 2560, "s": 2504, "text": "How to drop one or multiple columns in Pandas Dataframe" } ]
Design a Tribute Page using HTML & CSS
06 Oct, 2021 A tribute page is basically an overview of someone whom we admire in our life. In this article, we are creating a tribute webpage of Late A.P.J. Abdul Kalam Sir using HTML and CSS. We will add an image of him at the center (below the title) and create a box beneath that image. Inside that box, we will write a few of his achievements and details. We will use div tag and p tag to write the details and img tag for image. Then using CSS, we will align and beautify the design. Approach: In the <body> element, we will give the title of the page using h1 tag after that we will add an image of him in the img tag with some caption. We will create another div tag and write all the contents (using p tags). We have also given ID for each tag so that we can beautify the design using respective-ID in the CSS file. In the CSS section we have basically maintained a central design and used box-shadow to create box effect around the main content. Example: HTML <!DOCTYPE html><html lang="en"> <head> <style> /* Styling the body element like body color and margin */ body { background-color: #00FA9A; margin: 20%; } /* Styling the Title and giving shadow to the title */ #title { text-align: center; text-shadow: 5px 5px 10px white; font-size: 7vh; } /* Setting width and display type of image */ img { display: inline-block; width: 100%; } /* Setting font color and font size of the image-caption */ #caption { font-size: 17px; font-family: Gill Sans; color: black; } /* Styling the content of the page like- padding, font-size, font color etc.*/ div#tribute-data { background-color: rgb(46, 139, 87, 0.25); box-shadow: 20px 20px 20px #98FB98; font-family: Georgia; padding: 25px 25px; margin: 11px; margin-top: 50px; } /* Styling the title of the content */ h1.title-APJ { font-size: 35px; color: white; text-align: center; text-shadow: 5px 5px 10px black; } /* Styling the link provided at the end */ #tribute-link { text-decoration: none; color: black; } </style></head> <body> <main id="main"> <!-- Title of the page --> <h1 id="title"> A. P. J. Abdul Kalam </h1> <div id="img"> <!--Image of the Tribute Person--> <img src="APJ Kalam.png" id="image" alt="Error Loading Image"> <small id="caption"> Great Indian scientist and politician who played a leading role in the development of India’s missile and nuclear weapons programs. </small> </div> <div id="tribute-data"> <!--Achievements and other details of the person--> <h1 class="title-APJ"> About the Legend </h1> <p> ☛ A.P.J. Abdul Kalam, in full Avul Pakir Jainulabdeen Abdul Kalam, was born on October 15, 1931, in Rameswaram, Tamil Nadu, India.<br><br> ☛ He served as the 11th President of India from 2002 to 2007.<br><br> ☛ Kalam earned a degree in aeronautical engineering from the Madras Institute of Technology and in 1958 joined the Defence Research and Development Organisation (DRDO).<br><br> ☛ In 1969, he moved to the Indian Space Research Organisation, where he was project director of the SLV-III, the first satellite launch vehicle that was both designed and produced in India. <br><br> ☛ Rejoining DRDO in 1982, Kalam planned the program that produced a number of successful missiles, which helped earn him the nickname <strong> “Missile Man.”</strong> <br><br> ☛ Among those successes was Agni, India’s first intermediate-range ballistic missile, which incorporated aspects of the SLV-III and was launched in 1989. <br><br> ☛ He also played a pivotal organisational, technical, and political role in India's Pokhran-II nuclear tests in 1998, the first since the original nuclear test by India in 1974. <br><br> ☛ From 1992 to 1997 Kalam was scientific adviser to the defense minister, and he later served as principal scientific adviser (1999–2001) to the government with the rank of cabinet minister. <br><br> ☛ His prominent role in the country’s 1998 nuclear weapons tests solidified India as a nuclear power and established Kalam as a national hero, although the tests caused great concern in the international community. <br><br> ☛ In 1998 Kalam put forward a countrywide plan called Technology Vision 2020, which he described as a road map for transforming India from a less-developed to a developed society in 20 years. The plan called for, among other measures, increasing agricultural productivity, emphasizing technology as a vehicle for economic growth, and widening access to health care and education. <br><br> ☛ Kalam received <b>7</b> honorary doctorates from <b>40</b> universities. The Government of India honoured him with the <b>Padma Bhushan in 1981</b> and the <b>Padma Vibhushan in 1990</b> for his work with ISRO and DRDO and his role as a scientific advisor to the Government. <br><br> ☛ In 1997, Kalam received India's highest civilian honour, the Bharat Ratna, for his contribution to the scientific research and modernisation of defence technology in India. <br><br> ☛ In 2013, he was the recipient of the Von Braun Award from the National Space Society "to recognize excellence in the management and leadership of a space-related project". <br><br> ☛ While delivering a lecture at the Indian Institute of Management Shillong, Kalam collapsed and died from an apparent cardiac arrest on <b>27 July 2015</b>, aged 83. <br><br> ☛ Wheeler Island, a national missile test site in Odisha, was renamed <b>Kalam Island</b> in September 2015. <br><br> ☛ A prominent road in New Delhi was renamed from Aurangzeb Road to <b>Dr APJ Abdul Kalam Road</b> in August 2015. <br><br> ☛ In February 2018, scientists from the Botanical Survey of India named a newly found plant species as Drypetes kalamii, in his honour. <br><br><br> </p> </div> <br> For more information, check out <a id="tribute-link" href="#"> <b>A.P.J. Abdul Kalam</b> on Wikipedia. [ <small>Developed by @<a href="#"> Sushant Gaurav.</a></a> </small>] </main></body> </html> Output: Supported Browser: Google Chrome Microsoft Edge Firefox Opera Safari ysachin2314 kashishsoda CSS-Properties CSS-Questions HTML-Questions HTML-Tags CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 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 Design a webpage for online food delivery system using HTML and CSS 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 ? How to Insert Form Data into Database using PHP ?
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Oct, 2021" }, { "code": null, "e": 530, "s": 52, "text": "A tribute page is basically an overview of someone whom we admire in our life. In this article, we are creating a tribute webpage of Late A.P.J. Abdul Kalam Sir using HTML and CSS. We will add an image of him at the center (below the title) and create a box beneath that image. Inside that box, we will write a few of his achievements and details. We will use div tag and p tag to write the details and img tag for image. Then using CSS, we will align and beautify the design. " }, { "code": null, "e": 540, "s": 530, "text": "Approach:" }, { "code": null, "e": 865, "s": 540, "text": "In the <body> element, we will give the title of the page using h1 tag after that we will add an image of him in the img tag with some caption. We will create another div tag and write all the contents (using p tags). We have also given ID for each tag so that we can beautify the design using respective-ID in the CSS file." }, { "code": null, "e": 996, "s": 865, "text": "In the CSS section we have basically maintained a central design and used box-shadow to create box effect around the main content." }, { "code": null, "e": 1005, "s": 996, "text": "Example:" }, { "code": null, "e": 1010, "s": 1005, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <style> /* Styling the body element like body color and margin */ body { background-color: #00FA9A; margin: 20%; } /* Styling the Title and giving shadow to the title */ #title { text-align: center; text-shadow: 5px 5px 10px white; font-size: 7vh; } /* Setting width and display type of image */ img { display: inline-block; width: 100%; } /* Setting font color and font size of the image-caption */ #caption { font-size: 17px; font-family: Gill Sans; color: black; } /* Styling the content of the page like- padding, font-size, font color etc.*/ div#tribute-data { background-color: rgb(46, 139, 87, 0.25); box-shadow: 20px 20px 20px #98FB98; font-family: Georgia; padding: 25px 25px; margin: 11px; margin-top: 50px; } /* Styling the title of the content */ h1.title-APJ { font-size: 35px; color: white; text-align: center; text-shadow: 5px 5px 10px black; } /* Styling the link provided at the end */ #tribute-link { text-decoration: none; color: black; } </style></head> <body> <main id=\"main\"> <!-- Title of the page --> <h1 id=\"title\"> A. P. J. Abdul Kalam </h1> <div id=\"img\"> <!--Image of the Tribute Person--> <img src=\"APJ Kalam.png\" id=\"image\" alt=\"Error Loading Image\"> <small id=\"caption\"> Great Indian scientist and politician who played a leading role in the development of India’s missile and nuclear weapons programs. </small> </div> <div id=\"tribute-data\"> <!--Achievements and other details of the person--> <h1 class=\"title-APJ\"> About the Legend </h1> <p> ☛ A.P.J. Abdul Kalam, in full Avul Pakir Jainulabdeen Abdul Kalam, was born on October 15, 1931, in Rameswaram, Tamil Nadu, India.<br><br> ☛ He served as the 11th President of India from 2002 to 2007.<br><br> ☛ Kalam earned a degree in aeronautical engineering from the Madras Institute of Technology and in 1958 joined the Defence Research and Development Organisation (DRDO).<br><br> ☛ In 1969, he moved to the Indian Space Research Organisation, where he was project director of the SLV-III, the first satellite launch vehicle that was both designed and produced in India. <br><br> ☛ Rejoining DRDO in 1982, Kalam planned the program that produced a number of successful missiles, which helped earn him the nickname <strong> “Missile Man.”</strong> <br><br> ☛ Among those successes was Agni, India’s first intermediate-range ballistic missile, which incorporated aspects of the SLV-III and was launched in 1989. <br><br> ☛ He also played a pivotal organisational, technical, and political role in India's Pokhran-II nuclear tests in 1998, the first since the original nuclear test by India in 1974. <br><br> ☛ From 1992 to 1997 Kalam was scientific adviser to the defense minister, and he later served as principal scientific adviser (1999–2001) to the government with the rank of cabinet minister. <br><br> ☛ His prominent role in the country’s 1998 nuclear weapons tests solidified India as a nuclear power and established Kalam as a national hero, although the tests caused great concern in the international community. <br><br> ☛ In 1998 Kalam put forward a countrywide plan called Technology Vision 2020, which he described as a road map for transforming India from a less-developed to a developed society in 20 years. The plan called for, among other measures, increasing agricultural productivity, emphasizing technology as a vehicle for economic growth, and widening access to health care and education. <br><br> ☛ Kalam received <b>7</b> honorary doctorates from <b>40</b> universities. The Government of India honoured him with the <b>Padma Bhushan in 1981</b> and the <b>Padma Vibhushan in 1990</b> for his work with ISRO and DRDO and his role as a scientific advisor to the Government. <br><br> ☛ In 1997, Kalam received India's highest civilian honour, the Bharat Ratna, for his contribution to the scientific research and modernisation of defence technology in India. <br><br> ☛ In 2013, he was the recipient of the Von Braun Award from the National Space Society \"to recognize excellence in the management and leadership of a space-related project\". <br><br> ☛ While delivering a lecture at the Indian Institute of Management Shillong, Kalam collapsed and died from an apparent cardiac arrest on <b>27 July 2015</b>, aged 83. <br><br> ☛ Wheeler Island, a national missile test site in Odisha, was renamed <b>Kalam Island</b> in September 2015. <br><br> ☛ A prominent road in New Delhi was renamed from Aurangzeb Road to <b>Dr APJ Abdul Kalam Road</b> in August 2015. <br><br> ☛ In February 2018, scientists from the Botanical Survey of India named a newly found plant species as Drypetes kalamii, in his honour. <br><br><br> </p> </div> <br> For more information, check out <a id=\"tribute-link\" href=\"#\"> <b>A.P.J. Abdul Kalam</b> on Wikipedia. [ <small>Developed by @<a href=\"#\"> Sushant Gaurav.</a></a> </small>] </main></body> </html>", "e": 8052, "s": 1010, "text": null }, { "code": null, "e": 8060, "s": 8052, "text": "Output:" }, { "code": null, "e": 8079, "s": 8060, "text": "Supported Browser:" }, { "code": null, "e": 8093, "s": 8079, "text": "Google Chrome" }, { "code": null, "e": 8108, "s": 8093, "text": "Microsoft Edge" }, { "code": null, "e": 8116, "s": 8108, "text": "Firefox" }, { "code": null, "e": 8122, "s": 8116, "text": "Opera" }, { "code": null, "e": 8129, "s": 8122, "text": "Safari" }, { "code": null, "e": 8141, "s": 8129, "text": "ysachin2314" }, { "code": null, "e": 8153, "s": 8141, "text": "kashishsoda" }, { "code": null, "e": 8168, "s": 8153, "text": "CSS-Properties" }, { "code": null, "e": 8182, "s": 8168, "text": "CSS-Questions" }, { "code": null, "e": 8197, "s": 8182, "text": "HTML-Questions" }, { "code": null, "e": 8207, "s": 8197, "text": "HTML-Tags" }, { "code": null, "e": 8211, "s": 8207, "text": "CSS" }, { "code": null, "e": 8216, "s": 8211, "text": "HTML" }, { "code": null, "e": 8233, "s": 8216, "text": "Web Technologies" }, { "code": null, "e": 8238, "s": 8233, "text": "HTML" }, { "code": null, "e": 8336, "s": 8238, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8375, "s": 8336, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 8414, "s": 8375, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 8451, "s": 8414, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 8480, "s": 8451, "text": "Form validation using jQuery" }, { "code": null, "e": 8548, "s": 8480, "text": "Design a webpage for online food delivery system using HTML and CSS" }, { "code": null, "e": 8572, "s": 8548, "text": "REST API (Introduction)" }, { "code": null, "e": 8625, "s": 8572, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 8685, "s": 8625, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 8746, "s": 8685, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Nested Dictionary to Multiindex Dataframe
24 Feb, 2021 Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). A Data frame is a two-dimensional data structure, i.e., data is aligned in a tabular fashion in rows and columns. Pandas DataFrame consists of three principal components, the data, rows, and columns. A Multiindex Dataframe is a pandas dataframe having multi-level indexing or hierarchical indexing. Pandas needs multi-index values as tuples, not as a nested dictionary. So, first, we need to convert the nested index values into tuples. Example #1: Python3 # Import moduleimport pandas as pd # Nested dictionary to convert it# into multiindex dataframenested_dict = {'A': {'a': [1, 2, 3, 4, 5], 'b': [6, 7, 8, 9, 10]}, 'B': {'a': [11, 12, 13, 14, 15], 'b': [16, 17, 18, 19, 20]}} reformed_dict = {}for outerKey, innerDict in nested_dict.items(): for innerKey, values in innerDict.items(): reformed_dict[(outerKey, innerKey)] = values # Multiindex dataframereformed_dict Output: Notice that in the reformed_dict, index values are in the tuple. Now to convert reformed_dict into multiindex dataframe, we can use pd.DataFrame() method. Python3 multiIndex_df = pd.DataFrame(reformed_dict)multiIndex_df Output: Here in the output, we can see the hierarchical index/ multi index for the column. Example #2: Python3 # Import moduleimport pandas as pd # Nested dictionary to convert it into multiindex dataframenested_dict = {'India': {'State': ['Maharashtra', 'West Bengal', 'Uttar Pradesh', 'Bihar', 'Karnataka'], 'Capital': ['Mumbai', 'Kolkata', 'Lucknow', 'Patna', 'Bengaluru']}, 'America': {'State': ['California', 'Florida', 'Georgia', 'Massachusetts', 'New York'], 'Capital': ['Sacramento', 'Tallahassee', 'Atlanta', 'Boston', 'Albany']}} reformed_dict = {}for outerKey, innerDict in nested_dict.items(): for innerKey, values in innerDict.items(): reformed_dict[(outerKey, innerKey)] = values # Display multiindex dataframemultiIndex_df = pd.DataFrame(reformed_dict)multiIndex_df Output: Picked Python pandas-dataFrame Python Pandas-exercise Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Feb, 2021" }, { "code": null, "e": 466, "s": 28, "text": "Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). A Data frame is a two-dimensional data structure, i.e., data is aligned in a tabular fashion in rows and columns. Pandas DataFrame consists of three principal components, the data, rows, and columns. A Multiindex Dataframe is a pandas dataframe having multi-level indexing or hierarchical indexing." }, { "code": null, "e": 604, "s": 466, "text": "Pandas needs multi-index values as tuples, not as a nested dictionary. So, first, we need to convert the nested index values into tuples." }, { "code": null, "e": 616, "s": 604, "text": "Example #1:" }, { "code": null, "e": 624, "s": 616, "text": "Python3" }, { "code": "# Import moduleimport pandas as pd # Nested dictionary to convert it# into multiindex dataframenested_dict = {'A': {'a': [1, 2, 3, 4, 5], 'b': [6, 7, 8, 9, 10]}, 'B': {'a': [11, 12, 13, 14, 15], 'b': [16, 17, 18, 19, 20]}} reformed_dict = {}for outerKey, innerDict in nested_dict.items(): for innerKey, values in innerDict.items(): reformed_dict[(outerKey, innerKey)] = values # Multiindex dataframereformed_dict", "e": 1232, "s": 624, "text": null }, { "code": null, "e": 1240, "s": 1232, "text": "Output:" }, { "code": null, "e": 1395, "s": 1240, "text": "Notice that in the reformed_dict, index values are in the tuple. Now to convert reformed_dict into multiindex dataframe, we can use pd.DataFrame() method." }, { "code": null, "e": 1403, "s": 1395, "text": "Python3" }, { "code": "multiIndex_df = pd.DataFrame(reformed_dict)multiIndex_df", "e": 1460, "s": 1403, "text": null }, { "code": null, "e": 1468, "s": 1460, "text": "Output:" }, { "code": null, "e": 1551, "s": 1468, "text": "Here in the output, we can see the hierarchical index/ multi index for the column." }, { "code": null, "e": 1563, "s": 1551, "text": "Example #2:" }, { "code": null, "e": 1571, "s": 1563, "text": "Python3" }, { "code": "# Import moduleimport pandas as pd # Nested dictionary to convert it into multiindex dataframenested_dict = {'India': {'State': ['Maharashtra', 'West Bengal', 'Uttar Pradesh', 'Bihar', 'Karnataka'], 'Capital': ['Mumbai', 'Kolkata', 'Lucknow', 'Patna', 'Bengaluru']}, 'America': {'State': ['California', 'Florida', 'Georgia', 'Massachusetts', 'New York'], 'Capital': ['Sacramento', 'Tallahassee', 'Atlanta', 'Boston', 'Albany']}} reformed_dict = {}for outerKey, innerDict in nested_dict.items(): for innerKey, values in innerDict.items(): reformed_dict[(outerKey, innerKey)] = values # Display multiindex dataframemultiIndex_df = pd.DataFrame(reformed_dict)multiIndex_df", "e": 2464, "s": 1571, "text": null }, { "code": null, "e": 2472, "s": 2464, "text": "Output:" }, { "code": null, "e": 2479, "s": 2472, "text": "Picked" }, { "code": null, "e": 2503, "s": 2479, "text": "Python pandas-dataFrame" }, { "code": null, "e": 2526, "s": 2503, "text": "Python Pandas-exercise" }, { "code": null, "e": 2540, "s": 2526, "text": "Python-pandas" }, { "code": null, "e": 2547, "s": 2540, "text": "Python" }, { "code": null, "e": 2645, "s": 2547, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2677, "s": 2645, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2704, "s": 2677, "text": "Python Classes and Objects" }, { "code": null, "e": 2725, "s": 2704, "text": "Python OOPs Concepts" }, { "code": null, "e": 2748, "s": 2725, "text": "Introduction To PYTHON" }, { "code": null, "e": 2779, "s": 2748, "text": "Python | os.path.join() method" }, { "code": null, "e": 2835, "s": 2779, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2877, "s": 2835, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2919, "s": 2877, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2958, "s": 2919, "text": "Python | Get unique values from a list" } ]