title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
Multiprocessing In Python
|
The multiprocessing package supports spawning processes. It refers to a function that loads and executes a new child processes. For the child to terminate or to continue executing concurrent computing,then the current process hasto wait using an API, which is similar to threading module.
When we work with Multiprocessing,at first we create process object. Then it calls a start() method.
from multiprocessing import Process
def display():
print ('Hi !! I am Python')
if __name__ == '__main__':
p = Process(target=display)
p.start()
p.join()
In this example, at first we import the Process class then initiate Process object with the display() function.
Then process is started with start() method and then complete the process with the join() method.
We can also pass arguments to the function using args keyword.
from multiprocessing import Process
def display(my_name):
print ('Hi !!!' + " " + my_name)
if __name__ == '__main__':
p = Process(target=display, args=('Python',))
p.start()
p.join()
In this example, we create a process that calculates the cube of numbers and prints all results to the console.
from multiprocessing import Process
def cube(x):
for x in my_numbers:
print('%s cube is %s' % (x, x**3))
if __name__ == '__main__':
my_numbers = [3, 4, 5, 6, 7, 8]
p = Process(target=cube, args=('x',))
p.start()
p.join
print ("Done")
Done
3 cube is 27
4 cube is 64
5 cube is 125
6 cube is 216
7 cube is 343
8 cube is 512
We can also create more than one process at atime.
In this example, at first we create one process which is process1, this process just calculates the cube of a number and at the same time second process process2 is checking that this number is even or odd.
from multiprocessing import Process
def cube(x):
for x in my_numbers:
print('%s cube is %s' % (x, x**3))
def evenno(x):
for x in my_numbers:
if x % 2 == 0:
print('%s is an even number ' % (x))
if __name__ == '__main__':
my_numbers = [3, 4, 5, 6, 7, 8]
my_process1 = Process(target=cube, args=('x',))
my_process2 = Process(target=evenno, args=('x',))
my_process1.start()
my_process2.start()
my_process1.join()
my_process2.join()
print ("Done")
3 cube is 27
4 cube is 64
5 cube is 125
6 cube is 216
7 cube is 343
8 cube is 512
4 is an even number
6 is an even number
8 is an even number
Done
Multiprocessing supports Pipes and Queues, which are two types of communication channels between processes.
In multiprocessing, when we want to communicate between processes, in that situation Pipes areused.
from multiprocessing import Process, Pipe
def myfunction(conn):
conn.send(['hi!! I am Python'])
conn.close()
if __name__ == '__main__':
parent_conn, child_conn = Pipe()
p = Process(target=myfunction, args=(child_conn,))
p.start()
print (parent_conn.recv() )
p.join()
['hi !!! I am Python']
Pipes return two connection objects and these are representing the two ends of the pipe. Each connection object has two methods one is send() and another one is recv() method.
In this example, at first we create a process and this process prints the message "hi!! I am Python" and then shares the data across.
When we pass data between processes then at that time we can use Queue object.
import multiprocessing
def evenno(numbers, q):
for n in numbers:
if n % 2 == 0:
q.put(n)
if __name__ == "__main__":
q = multiprocessing.Queue()
p = multiprocessing.Process(target=evenno, args=(range(10), q))
p.start()
p.join()
while q:
print(q.get())
0
2
4
6
8
In this example, at first create a function that checks weather a number is even or not. If the number is even, then insert it at the end of the queue. Then we create a queue object and a process object then we start the process.
And finally check whether the queue is empty or not.
When we print the numbers, at first we print the value which is in front of the queue then next one and so on.
When we want that only one process is executed at a time in that situation Locks is use. That means that time blocks other process from executing similar code. Lock will be released after the process gets completed.
from multiprocessing import Process, Lock
def dispmay_name(l, i):
l.acquire()
print ('Hi', i)
l.release()
if __name__ == '__main__':
my_lock = Lock()
my_name = ['Aadrika', 'Adwaita', 'Sakya', 'Sanj']
for name in my_name:
Process(target=dispmay_name, args=(my_lock,name)).start()
Hi Aadrika
Hi Adwaita
Hi Sakya
Hi Sanj
The multiprocessing module also provides logging module to ensure that, if the logging package doesn't use locks function, the messages between processes mixed up during execution.
import multiprocessing, logging
logger = multiprocessing.log_to_stderr()
logger.setLevel(logging.INFO)
logger.warning('Error has occurred')
In this example at first we import the logging and multiprocessing module then we use multiprocessing.log_to_stderr() method. And it call get_logger() as well as adding to sys.stderr and finally we set the level of logger and convey the message.
|
[
{
"code": null,
"e": 1351,
"s": 1062,
"text": "The multiprocessing package supports spawning processes. It refers to a function that loads and executes a new child processes. For the child to terminate or to continue executing concurrent computing,then the current process hasto wait using an API, which is similar to threading module."
},
{
"code": null,
"e": 1452,
"s": 1351,
"text": "When we work with Multiprocessing,at first we create process object. Then it calls a start() method."
},
{
"code": null,
"e": 1638,
"s": 1452,
"text": "from multiprocessing import Process\n def display():\n print ('Hi !! I am Python')\n if __name__ == '__main__':\n p = Process(target=display)\n p.start()\n p.join()"
},
{
"code": null,
"e": 1750,
"s": 1638,
"text": "In this example, at first we import the Process class then initiate Process object with the display() function."
},
{
"code": null,
"e": 1848,
"s": 1750,
"text": "Then process is started with start() method and then complete the process with the join() method."
},
{
"code": null,
"e": 1911,
"s": 1848,
"text": "We can also pass arguments to the function using args keyword."
},
{
"code": null,
"e": 2121,
"s": 1911,
"text": "from multiprocessing import Process\n def display(my_name):\n print ('Hi !!!' + \" \" + my_name)\n if __name__ == '__main__':\n p = Process(target=display, args=('Python',))\n p.start()\n p.join()"
},
{
"code": null,
"e": 2233,
"s": 2121,
"text": "In this example, we create a process that calculates the cube of numbers and prints all results to the console."
},
{
"code": null,
"e": 2518,
"s": 2233,
"text": "from multiprocessing import Process\n def cube(x):\n for x in my_numbers:\n print('%s cube is %s' % (x, x**3))\n if __name__ == '__main__':\n my_numbers = [3, 4, 5, 6, 7, 8]\n p = Process(target=cube, args=('x',))\n p.start()\np.join\nprint (\"Done\")"
},
{
"code": null,
"e": 2605,
"s": 2518,
"text": "Done\n3 cube is 27\n4 cube is 64\n5 cube is 125\n6 cube is 216\n7 cube is 343\n8 cube is 512"
},
{
"code": null,
"e": 2656,
"s": 2605,
"text": "We can also create more than one process at atime."
},
{
"code": null,
"e": 2863,
"s": 2656,
"text": "In this example, at first we create one process which is process1, this process just calculates the cube of a number and at the same time second process process2 is checking that this number is even or odd."
},
{
"code": null,
"e": 3363,
"s": 2863,
"text": "from multiprocessing import Process\ndef cube(x):\n for x in my_numbers:\n print('%s cube is %s' % (x, x**3))\ndef evenno(x):\n for x in my_numbers:\n if x % 2 == 0:\n print('%s is an even number ' % (x))\n if __name__ == '__main__':\n my_numbers = [3, 4, 5, 6, 7, 8]\n my_process1 = Process(target=cube, args=('x',))\n my_process2 = Process(target=evenno, args=('x',))\n my_process1.start()\n my_process2.start()\n my_process1.join()\n my_process2.join()\nprint (\"Done\")"
},
{
"code": null,
"e": 3510,
"s": 3363,
"text": "3 cube is 27\n4 cube is 64\n5 cube is 125\n6 cube is 216\n7 cube is 343\n8 cube is 512\n4 is an even number\n6 is an even number\n8 is an even number\nDone"
},
{
"code": null,
"e": 3618,
"s": 3510,
"text": "Multiprocessing supports Pipes and Queues, which are two types of communication channels between processes."
},
{
"code": null,
"e": 3718,
"s": 3618,
"text": "In multiprocessing, when we want to communicate between processes, in that situation Pipes areused."
},
{
"code": null,
"e": 4039,
"s": 3718,
"text": "from multiprocessing import Process, Pipe\n def myfunction(conn):\n conn.send(['hi!! I am Python'])\n conn.close()\n if __name__ == '__main__':\n parent_conn, child_conn = Pipe()\n p = Process(target=myfunction, args=(child_conn,))\n p.start()\n print (parent_conn.recv() )\np.join()"
},
{
"code": null,
"e": 4062,
"s": 4039,
"text": "['hi !!! I am Python']"
},
{
"code": null,
"e": 4238,
"s": 4062,
"text": "Pipes return two connection objects and these are representing the two ends of the pipe. Each connection object has two methods one is send() and another one is recv() method."
},
{
"code": null,
"e": 4372,
"s": 4238,
"text": "In this example, at first we create a process and this process prints the message \"hi!! I am Python\" and then shares the data across."
},
{
"code": null,
"e": 4451,
"s": 4372,
"text": "When we pass data between processes then at that time we can use Queue object."
},
{
"code": null,
"e": 4768,
"s": 4451,
"text": "import multiprocessing\n def evenno(numbers, q):\n for n in numbers:\n if n % 2 == 0:\n q.put(n)\n if __name__ == \"__main__\":\n q = multiprocessing.Queue()\n p = multiprocessing.Process(target=evenno, args=(range(10), q))\n p.start()\n p.join()\n while q:\nprint(q.get())"
},
{
"code": null,
"e": 4778,
"s": 4768,
"text": "0\n2\n4\n6\n8"
},
{
"code": null,
"e": 5008,
"s": 4778,
"text": "In this example, at first create a function that checks weather a number is even or not. If the number is even, then insert it at the end of the queue. Then we create a queue object and a process object then we start the process."
},
{
"code": null,
"e": 5061,
"s": 5008,
"text": "And finally check whether the queue is empty or not."
},
{
"code": null,
"e": 5172,
"s": 5061,
"text": "When we print the numbers, at first we print the value which is in front of the queue then next one and so on."
},
{
"code": null,
"e": 5388,
"s": 5172,
"text": "When we want that only one process is executed at a time in that situation Locks is use. That means that time blocks other process from executing similar code. Lock will be released after the process gets completed."
},
{
"code": null,
"e": 5676,
"s": 5388,
"text": "from multiprocessing import Process, Lock\ndef dispmay_name(l, i):\nl.acquire()\nprint ('Hi', i)\n l.release()\nif __name__ == '__main__':\n my_lock = Lock()\n my_name = ['Aadrika', 'Adwaita', 'Sakya', 'Sanj']\nfor name in my_name:\nProcess(target=dispmay_name, args=(my_lock,name)).start()"
},
{
"code": null,
"e": 5715,
"s": 5676,
"text": "Hi Aadrika\nHi Adwaita\nHi Sakya\nHi Sanj"
},
{
"code": null,
"e": 5896,
"s": 5715,
"text": "The multiprocessing module also provides logging module to ensure that, if the logging package doesn't use locks function, the messages between processes mixed up during execution."
},
{
"code": null,
"e": 6036,
"s": 5896,
"text": "import multiprocessing, logging\nlogger = multiprocessing.log_to_stderr()\nlogger.setLevel(logging.INFO)\nlogger.warning('Error has occurred')"
},
{
"code": null,
"e": 6282,
"s": 6036,
"text": "In this example at first we import the logging and multiprocessing module then we use multiprocessing.log_to_stderr() method. And it call get_logger() as well as adding to sys.stderr and finally we set the level of logger and convey the message."
}
] |
Bringing Colab to a Jupyter Notebook near you... | by Robert Dargavel Smith | Towards Data Science
|
When programming in Python, it can be quite overwhelming when you hit an error deep down in a stack of nested function calls. One of the advantages of Python is that it has an enormous amount of high quality libraries available and for which the source code is readily available. Sometimes, it is useful just to be able to dig in to it in order to be able to understand what is going on.
To help you do just this, Google Colab automatically displays clickable links to the source files in the stack trace, as well as a handy button that searches for the error in Stack Overflow. Wouldn’t it be nice if Jupyter Notebook could do the same? That’s what I thought, so I decided to create a Notebook Extension that does exactly that.
If you have not already installed Jupyter Notebook extensions, you can do this by typing
pip install jupyter_contrib_nbextensions
Download the Goto Error code from GitHub with
git clone git://github.com/teticio/nbextension-gotoerror
install it like so
jupyter nbextension install nbextension-gotoerror
and finally, enable it thusly
jupyter nbextension enable nbextension-gotoerror/main
If all goes to plan, you should be able to configure the Goto Error extension in the nbextensions tab of Jupyter Notebook.
As the Jupyter server is only able to access files in the directory in which it is run or a subdirectory, for the notebook to be able to open the source files it is necessary to provide a soft link to the source file directory. For example, if you don’t use virtual environments, make soft link in the Jupyter launch directory to the site-packages directory of your Python installation (e.g. ~/lib/python3.6/site-packages) and call this site-packages. Then set the prefix parameter in the nbextension configuration to ~/lib/python3.6.
If you do use virtual environments, then point the soft link to the envs directory and set the prefix parameter accordingly.
To make a soft link in Linux:
ln -s ~/.local/lib/python3.6/site-packages site-packages
To make a soft link in Windows:
mklink -d envs C:\users\teticio\Anaconda\python\envs
It should now work just like the following example.
Google Colab has some other great features (apart from free access to GPUs and TPUs!). For example, if you add a #@param comment to the end of a line, it will automatically create a form which allows the user to input a value. For example
fred = 123 #@param {type : 'number'}
pops up a form with ‘fred’ and the number 123. If you change the number in the form to 456, say, the code is changed to
fred = 456 #@param {type : 'number'}
I’d like to develop an extension for Jupyter Notebook that does the same thing and, while I’m at it, port both of these extensions to Jupyter Lab. Please let me know if this is something that you would use.
|
[
{
"code": null,
"e": 560,
"s": 172,
"text": "When programming in Python, it can be quite overwhelming when you hit an error deep down in a stack of nested function calls. One of the advantages of Python is that it has an enormous amount of high quality libraries available and for which the source code is readily available. Sometimes, it is useful just to be able to dig in to it in order to be able to understand what is going on."
},
{
"code": null,
"e": 901,
"s": 560,
"text": "To help you do just this, Google Colab automatically displays clickable links to the source files in the stack trace, as well as a handy button that searches for the error in Stack Overflow. Wouldn’t it be nice if Jupyter Notebook could do the same? That’s what I thought, so I decided to create a Notebook Extension that does exactly that."
},
{
"code": null,
"e": 990,
"s": 901,
"text": "If you have not already installed Jupyter Notebook extensions, you can do this by typing"
},
{
"code": null,
"e": 1031,
"s": 990,
"text": "pip install jupyter_contrib_nbextensions"
},
{
"code": null,
"e": 1077,
"s": 1031,
"text": "Download the Goto Error code from GitHub with"
},
{
"code": null,
"e": 1134,
"s": 1077,
"text": "git clone git://github.com/teticio/nbextension-gotoerror"
},
{
"code": null,
"e": 1153,
"s": 1134,
"text": "install it like so"
},
{
"code": null,
"e": 1203,
"s": 1153,
"text": "jupyter nbextension install nbextension-gotoerror"
},
{
"code": null,
"e": 1233,
"s": 1203,
"text": "and finally, enable it thusly"
},
{
"code": null,
"e": 1287,
"s": 1233,
"text": "jupyter nbextension enable nbextension-gotoerror/main"
},
{
"code": null,
"e": 1410,
"s": 1287,
"text": "If all goes to plan, you should be able to configure the Goto Error extension in the nbextensions tab of Jupyter Notebook."
},
{
"code": null,
"e": 1945,
"s": 1410,
"text": "As the Jupyter server is only able to access files in the directory in which it is run or a subdirectory, for the notebook to be able to open the source files it is necessary to provide a soft link to the source file directory. For example, if you don’t use virtual environments, make soft link in the Jupyter launch directory to the site-packages directory of your Python installation (e.g. ~/lib/python3.6/site-packages) and call this site-packages. Then set the prefix parameter in the nbextension configuration to ~/lib/python3.6."
},
{
"code": null,
"e": 2070,
"s": 1945,
"text": "If you do use virtual environments, then point the soft link to the envs directory and set the prefix parameter accordingly."
},
{
"code": null,
"e": 2100,
"s": 2070,
"text": "To make a soft link in Linux:"
},
{
"code": null,
"e": 2157,
"s": 2100,
"text": "ln -s ~/.local/lib/python3.6/site-packages site-packages"
},
{
"code": null,
"e": 2189,
"s": 2157,
"text": "To make a soft link in Windows:"
},
{
"code": null,
"e": 2242,
"s": 2189,
"text": "mklink -d envs C:\\users\\teticio\\Anaconda\\python\\envs"
},
{
"code": null,
"e": 2294,
"s": 2242,
"text": "It should now work just like the following example."
},
{
"code": null,
"e": 2533,
"s": 2294,
"text": "Google Colab has some other great features (apart from free access to GPUs and TPUs!). For example, if you add a #@param comment to the end of a line, it will automatically create a form which allows the user to input a value. For example"
},
{
"code": null,
"e": 2570,
"s": 2533,
"text": "fred = 123 #@param {type : 'number'}"
},
{
"code": null,
"e": 2690,
"s": 2570,
"text": "pops up a form with ‘fred’ and the number 123. If you change the number in the form to 456, say, the code is changed to"
},
{
"code": null,
"e": 2727,
"s": 2690,
"text": "fred = 456 #@param {type : 'number'}"
}
] |
C# | Tuple
|
30 Apr, 2019
The word Tuple means “a data structure which consists of the multiple parts”. So tuple is a data structure which gives you the easiest way to represent a data set which has multiple values that may/may not be related to each other. It introduced in .NET Framework 4.0. In tuple, you can add elements from 1 to 8. If you try to add elements greater than eight, then the compiler will throw an error. Tuples are generally used when you want to create a data structure which contains objects with their properties and you don’t want to create a separate type for that.
Features of Tuples:
It allows us to represent multiple data into a single data set.
It allows us to create, manipulate, and access data set.
It return multiple values from a method without using out parameter.
It can also store duplicate elements.
It allows us to pass multiple values to a method with the help of single parameters.
Before tuples, we have three ways to return more than one value from the method in C# which are Using Class or Struct types, Out parameters and Anonymous types which returned through a Dynamic Return Type. But after Tuples, it becomes easy to represent a single set of data.
For another reason, just imagine a case where you want to store the details of an Employee in just one entity, like Name, EmpID, Blood Group, Contact Number. Now the most common way that comes to the mind is to create a data structure which would take the required fields. This is where Tuples come into play. With Tuples, there is no need to create any separate data structure. Instead, for this case, you can use Tuple<T1, T2, T3, T4>.
The most common data structures like Array, List, etc. are only of a specific type and can store infinite elements. But Tuples are able to store a limited number of elements i.e 8 and can be of any type.
In C#, there are mainly 2 ways to create the tuple which are as follows:
Using Constructor of Tuple Class: You can create a tuple by using the constructor which is provided by Tuple<T> class. Where you can store elements starting from one to eight with their type. But you are not allowed to store elements greater than eight in a tuple. If you try to do so then the compiler will throw an error.Syntax:// Constructor for single elements
Tuple <T1>(T1)
// Constructor for two elements
Tuple <T1, T2>(T1, T2)
.
.
.
// Constructor for eight elements
Tuple <T1, T2, T3, T4, T5, T6, T7, TRest>(T1, T2, T3, T4, T5, T6, T7, TRest)Example:// C# program to create tuple using tuple constructor.using System; public class GFG{ // Main method static public void Main (){ // Tuple with one element Tuple<string>My_Tuple1 = new Tuple<string>("GeeksforGeeks"); // Tuple with three elements Tuple<string, string, int>My_Tuple2 = new Tuple<string, string, int>("Romil", "Python", 29); // Tuple with eight elements Tuple<int, int, int, int, int, int, int, Tuple<int>>My_Tuple3 = new Tuple<int, int, int, int, int, int, int, Tuple<int>>(1,2,3,4,5,6,7, new Tuple<int>(8)); }}
Syntax:
// Constructor for single elements
Tuple <T1>(T1)
// Constructor for two elements
Tuple <T1, T2>(T1, T2)
.
.
.
// Constructor for eight elements
Tuple <T1, T2, T3, T4, T5, T6, T7, TRest>(T1, T2, T3, T4, T5, T6, T7, TRest)
Example:
// C# program to create tuple using tuple constructor.using System; public class GFG{ // Main method static public void Main (){ // Tuple with one element Tuple<string>My_Tuple1 = new Tuple<string>("GeeksforGeeks"); // Tuple with three elements Tuple<string, string, int>My_Tuple2 = new Tuple<string, string, int>("Romil", "Python", 29); // Tuple with eight elements Tuple<int, int, int, int, int, int, int, Tuple<int>>My_Tuple3 = new Tuple<int, int, int, int, int, int, int, Tuple<int>>(1,2,3,4,5,6,7, new Tuple<int>(8)); }}
Using Create Method: When we use the tuple constructor to create a tuple we need to provide the type of each element stored in the tuple which makes your code cumbersome. So, C# provides another class that is Tuple class which contains the static methods for creating tuple object without providing the type of each element.Syntax:// Method for 1-tuple
Create(T1)
// Method for 2-tuple
Create(T1, T2)
.
.
.
// Method for 8-tuple
Create(T1, T2, T3, T4, T5, T6, T7, T8)
Example:// C# program to create tuple // using Create Methodusing System; public class GFG { // Main method static public void Main() { // Creating 1-tuple // Using Create Method var My_Tuple1 = Tuple.Create("GeeksforGeeks"); // Creating 4-tuple // Using Create Method var My_Tuple2 = Tuple.Create(12, 30, 40, 50); // Creating 8-tuple // Using Create Method var My_Tuple3 = Tuple.Create(13, "Geeks", 67, 89.90, 'g', 39939, "geek", 10); }}
Syntax:
// Method for 1-tuple
Create(T1)
// Method for 2-tuple
Create(T1, T2)
.
.
.
// Method for 8-tuple
Create(T1, T2, T3, T4, T5, T6, T7, T8)
Example:
// C# program to create tuple // using Create Methodusing System; public class GFG { // Main method static public void Main() { // Creating 1-tuple // Using Create Method var My_Tuple1 = Tuple.Create("GeeksforGeeks"); // Creating 4-tuple // Using Create Method var My_Tuple2 = Tuple.Create(12, 30, 40, 50); // Creating 8-tuple // Using Create Method var My_Tuple3 = Tuple.Create(13, "Geeks", 67, 89.90, 'g', 39939, "geek", 10); }}
You can access the elements of a tuple by using Item<elementNumber> property, here elementNumber is from 1 to 7 like Item1, Item 2, Item3, Item4, Item5, Item6, Item 7, etc. and the last element of 8-tuple is accessible by using Rest property. As shown in below example:
Example:
// C# program to access the tuple // using Item and Rest propertyusing System; public class GFG { // Main method static public void Main() { // Creating 1-tuple // Using Create Method var My_Tuple1 = Tuple.Create("GeeksforGeeks"); // Accessing the element of Tuple // Using Item property Console.WriteLine("Element of My_Tuple1: " + My_Tuple1.Item1); Console.WriteLine(); // Creating 4-tuple // Using Create Method var My_Tuple2 = Tuple.Create(12, 30, 40, 50); // Accessing the element of Tuple // Using Item property Console.WriteLine("Element of My_Tuple2: " + My_Tuple2.Item1); Console.WriteLine("Element of My_Tuple2: " + My_Tuple2.Item2); Console.WriteLine("Element of My_Tuple2: " + My_Tuple2.Item3); Console.WriteLine("Element of My_Tuple2: " + My_Tuple2.Item4); Console.WriteLine(); // Creating 8-tuple // Using Create Method var My_Tuple3 = Tuple.Create(13, "Geeks", 67, 89.90, 'g', 39939, "geek", 10); // Accessing the element of Tuple // Using Item property // And print the 8th element of tuple // using Rest property Console.WriteLine("Element of My_Tuple3: " + My_Tuple3.Item1); Console.WriteLine("Element of My_Tuple3: " + My_Tuple3.Item2); Console.WriteLine("Element of My_Tuple3: " + My_Tuple3.Item3); Console.WriteLine("Element of My_Tuple3: " + My_Tuple3.Item4); Console.WriteLine("Element of My_Tuple3: " + My_Tuple3.Item5); Console.WriteLine("Element of My_Tuple3: " + My_Tuple3.Item6); Console.WriteLine("Element of My_Tuple3: " + My_Tuple3.Item7); Console.WriteLine("Element of My_Tuple3: " + My_Tuple3.Rest); }}
Output:
Element of My_Tuple1: GeeksforGeeks
Element of My_Tuple2: 12
Element of My_Tuple2: 30
Element of My_Tuple2: 40
Element of My_Tuple2: 50
Element of My_Tuple3: 13
Element of My_Tuple3: Geeks
Element of My_Tuple3: 67
Element of My_Tuple3: 89.9
Element of My_Tuple3: g
Element of My_Tuple3: 39939
Element of My_Tuple3: geek
Element of My_Tuple3: (10)
In C#, you are allowed to create a tuple into another tuple. You can use nested tuples when you want to add more than eight elements in the same tuple. The nested tuple is accessible by using the Rest property as shown in Example 1. You are allowed to add a nested tuple anywhere in the sequence, but it is recommended that you can place nested tuple at the end of the sequence so that they can easily access from the Rest property. If you place nested tuple other than the last place, then the tuple is accessible according to Item<elementNumber> property as shown in example 2.
Example 1:
// C# program to illustrate nested tupleusing System; public class GFG{ // Main method static public void Main () { // Nested Tuple var My_Tuple = Tuple.Create(13, "Geeks", 67, 89.90, 'g', 39939, "geek", Tuple.Create(12, 30, 40, 50)); // Accessing the element of Tuple // Using Item property // And accessing the elements of nested tuple // Using Rest property Console.WriteLine("Element of My_Tuple: "+My_Tuple.Item1); Console.WriteLine("Element of My_Tuple: "+My_Tuple.Item2); Console.WriteLine("Element of My_Tuple: "+My_Tuple.Item3); Console.WriteLine("Element of My_Tuple: "+My_Tuple.Item4); Console.WriteLine("Element of My_Tuple: "+My_Tuple.Item5); Console.WriteLine("Element of My_Tuple: "+My_Tuple.Item6); Console.WriteLine("Element of My_Tuple: "+My_Tuple.Item7); Console.WriteLine("Element of Nested tuple: "+My_Tuple.Rest); Console.WriteLine("Element of Nested tuple: "+My_Tuple.Rest.Item1.Item1); Console.WriteLine("Element of Nested tuple: "+My_Tuple.Rest.Item1.Item2); Console.WriteLine("Element of Nested tuple: "+My_Tuple.Rest.Item1.Item3); Console.WriteLine("Element of Nested tuple: "+My_Tuple.Rest.Item1.Item4); }}
Output:
Element of My_Tuple: 13
Element of My_Tuple: Geeks
Element of My_Tuple: 67
Element of My_Tuple: 89.9
Element of My_Tuple: g
Element of My_Tuple: 39939
Element of My_Tuple: geek
Element of Nested tuple: ((12, 30, 40, 50))
Element of Nested tuple: 12
Element of Nested tuple: 30
Element of Nested tuple: 40
Element of Nested tuple: 50
Example 2:
// C# program to illustrate nested tupleusing System; public class GFG{ // Main method static public void Main () { // Nested Tuple // Here nested tuple is present // at the place of 2nd element var My_Tuple = Tuple.Create(13, Tuple.Create(12, 30, 40, 50),67, 89.90, 'g', 39939, 123, "geeks"); // Accessing the element of Tuple // Using Item property // And accessing the elements of // nested tuple Using Rest property Console.WriteLine("Element of My_Tuple: "+My_Tuple.Item1); Console.WriteLine("Element of Nested Tuple: "+My_Tuple.Item2.Item1); Console.WriteLine("Element of Nested Tuple: "+My_Tuple.Item2.Item2); Console.WriteLine("Element of Nested Tuple: "+My_Tuple.Item2.Item3); Console.WriteLine("Element of Nested Tuple: "+My_Tuple.Item2.Item4); Console.WriteLine("Element of My_Tuple: "+My_Tuple.Item3); Console.WriteLine("Element of My_Tuple: "+My_Tuple.Item4); Console.WriteLine("Element of My_Tuple: "+My_Tuple.Item5); Console.WriteLine("Element of My_Tuple: "+My_Tuple.Item6); Console.WriteLine("Element of My_Tuple: "+My_Tuple.Item7); Console.WriteLine("Element of My_Tuple: "+My_Tuple.Rest); }}
Output:
Element of My_Tuple: 13
Element of Nested Tuple: 12
Element of Nested Tuple: 30
Element of Nested Tuple: 40
Element of Nested Tuple: 50
Element of My_Tuple: 67
Element of My_Tuple: 89.9
Element of My_Tuple: g
Element of My_Tuple: 39939
Element of My_Tuple: 123
Element of My_Tuple: (geeks)
In C#, you are allowed to pass a tuple as a method parameter as shown in the below example. Here we pass a tuple named mytuple in the PrintTheTuple() method and the elements of the tuple are accessed by using Item<elementNumber> property.
Example:
// C# program to illustrate the // tuple as a method parameter.using System; public class GFG{ // Main method static public void Main () { // Creating a tuple var mytuple = Tuple.Create("GeeksforGeeks", 123, 90.8); // Pass the tuple in the // PrintTheTuple method PrintTheTuple(mytuple); } static void PrintTheTuple(Tuple<string, int, double>mytuple) { Console.WriteLine("Element: "+mytuple.Item1); Console.WriteLine("Element: "+mytuple.Item2); Console.WriteLine("Element: "+mytuple.Item3); }}
Output:
Element: GeeksforGeeks
Element: 123
Element: 90.8
In C#, methods are allowed to use tuple as a return type. Or in other words a method can return a tuple as shown in the below example:
Example:
// C# program to illustrate // how a method return tupleusing System; public class GFG{ // Main Method static public void Main () { // Return tuple is stored in mytuple var mytuple = PrintTuple(); Console.WriteLine(mytuple.Item1); Console.WriteLine(mytuple.Item2); Console.WriteLine(mytuple.Item3); } // PrintTuple method return a tuple static Tuple<string, string, string>PrintTuple() { return Tuple.Create("Geeks", "For", "Geeks"); }}
Output:
Geeks
For
Geeks
Limitation of Tuple:
It is of reference type not of value type.
It is limited to eight elements. Means you cannot store more than eight elements without nested tuple.
These are only accessed by using Item<elementNumber> property.
CSharp-Tuple
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Abstract Class and Interface in C#
C# | How to check whether a List contains a specified element
C# | Arrays of Strings
C# | IsNullOrEmpty() Method
String.Split() Method in C# with Examples
C# | Delegates
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
C# | String.IndexOf( ) Method | Set - 1
Extension Method in C#
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n30 Apr, 2019"
},
{
"code": null,
"e": 619,
"s": 53,
"text": "The word Tuple means “a data structure which consists of the multiple parts”. So tuple is a data structure which gives you the easiest way to represent a data set which has multiple values that may/may not be related to each other. It introduced in .NET Framework 4.0. In tuple, you can add elements from 1 to 8. If you try to add elements greater than eight, then the compiler will throw an error. Tuples are generally used when you want to create a data structure which contains objects with their properties and you don’t want to create a separate type for that."
},
{
"code": null,
"e": 639,
"s": 619,
"text": "Features of Tuples:"
},
{
"code": null,
"e": 703,
"s": 639,
"text": "It allows us to represent multiple data into a single data set."
},
{
"code": null,
"e": 760,
"s": 703,
"text": "It allows us to create, manipulate, and access data set."
},
{
"code": null,
"e": 829,
"s": 760,
"text": "It return multiple values from a method without using out parameter."
},
{
"code": null,
"e": 867,
"s": 829,
"text": "It can also store duplicate elements."
},
{
"code": null,
"e": 952,
"s": 867,
"text": "It allows us to pass multiple values to a method with the help of single parameters."
},
{
"code": null,
"e": 1227,
"s": 952,
"text": "Before tuples, we have three ways to return more than one value from the method in C# which are Using Class or Struct types, Out parameters and Anonymous types which returned through a Dynamic Return Type. But after Tuples, it becomes easy to represent a single set of data."
},
{
"code": null,
"e": 1665,
"s": 1227,
"text": "For another reason, just imagine a case where you want to store the details of an Employee in just one entity, like Name, EmpID, Blood Group, Contact Number. Now the most common way that comes to the mind is to create a data structure which would take the required fields. This is where Tuples come into play. With Tuples, there is no need to create any separate data structure. Instead, for this case, you can use Tuple<T1, T2, T3, T4>."
},
{
"code": null,
"e": 1869,
"s": 1665,
"text": "The most common data structures like Array, List, etc. are only of a specific type and can store infinite elements. But Tuples are able to store a limited number of elements i.e 8 and can be of any type."
},
{
"code": null,
"e": 1942,
"s": 1869,
"text": "In C#, there are mainly 2 ways to create the tuple which are as follows:"
},
{
"code": null,
"e": 3094,
"s": 1942,
"text": "Using Constructor of Tuple Class: You can create a tuple by using the constructor which is provided by Tuple<T> class. Where you can store elements starting from one to eight with their type. But you are not allowed to store elements greater than eight in a tuple. If you try to do so then the compiler will throw an error.Syntax:// Constructor for single elements\nTuple <T1>(T1)\n\n// Constructor for two elements\nTuple <T1, T2>(T1, T2)\n.\n.\n.\n // Constructor for eight elements\nTuple <T1, T2, T3, T4, T5, T6, T7, TRest>(T1, T2, T3, T4, T5, T6, T7, TRest)Example:// C# program to create tuple using tuple constructor.using System; public class GFG{ // Main method static public void Main (){ // Tuple with one element Tuple<string>My_Tuple1 = new Tuple<string>(\"GeeksforGeeks\"); // Tuple with three elements Tuple<string, string, int>My_Tuple2 = new Tuple<string, string, int>(\"Romil\", \"Python\", 29); // Tuple with eight elements Tuple<int, int, int, int, int, int, int, Tuple<int>>My_Tuple3 = new Tuple<int, int, int, int, int, int, int, Tuple<int>>(1,2,3,4,5,6,7, new Tuple<int>(8)); }}"
},
{
"code": null,
"e": 3102,
"s": 3094,
"text": "Syntax:"
},
{
"code": null,
"e": 3326,
"s": 3102,
"text": "// Constructor for single elements\nTuple <T1>(T1)\n\n// Constructor for two elements\nTuple <T1, T2>(T1, T2)\n.\n.\n.\n // Constructor for eight elements\nTuple <T1, T2, T3, T4, T5, T6, T7, TRest>(T1, T2, T3, T4, T5, T6, T7, TRest)"
},
{
"code": null,
"e": 3335,
"s": 3326,
"text": "Example:"
},
{
"code": "// C# program to create tuple using tuple constructor.using System; public class GFG{ // Main method static public void Main (){ // Tuple with one element Tuple<string>My_Tuple1 = new Tuple<string>(\"GeeksforGeeks\"); // Tuple with three elements Tuple<string, string, int>My_Tuple2 = new Tuple<string, string, int>(\"Romil\", \"Python\", 29); // Tuple with eight elements Tuple<int, int, int, int, int, int, int, Tuple<int>>My_Tuple3 = new Tuple<int, int, int, int, int, int, int, Tuple<int>>(1,2,3,4,5,6,7, new Tuple<int>(8)); }}",
"e": 3926,
"s": 3335,
"text": null
},
{
"code": null,
"e": 4940,
"s": 3926,
"text": "Using Create Method: When we use the tuple constructor to create a tuple we need to provide the type of each element stored in the tuple which makes your code cumbersome. So, C# provides another class that is Tuple class which contains the static methods for creating tuple object without providing the type of each element.Syntax:// Method for 1-tuple\nCreate(T1)\n\n// Method for 2-tuple\nCreate(T1, T2)\n.\n.\n.\n// Method for 8-tuple\nCreate(T1, T2, T3, T4, T5, T6, T7, T8)\nExample:// C# program to create tuple // using Create Methodusing System; public class GFG { // Main method static public void Main() { // Creating 1-tuple // Using Create Method var My_Tuple1 = Tuple.Create(\"GeeksforGeeks\"); // Creating 4-tuple // Using Create Method var My_Tuple2 = Tuple.Create(12, 30, 40, 50); // Creating 8-tuple // Using Create Method var My_Tuple3 = Tuple.Create(13, \"Geeks\", 67, 89.90, 'g', 39939, \"geek\", 10); }}"
},
{
"code": null,
"e": 4948,
"s": 4940,
"text": "Syntax:"
},
{
"code": null,
"e": 5087,
"s": 4948,
"text": "// Method for 1-tuple\nCreate(T1)\n\n// Method for 2-tuple\nCreate(T1, T2)\n.\n.\n.\n// Method for 8-tuple\nCreate(T1, T2, T3, T4, T5, T6, T7, T8)\n"
},
{
"code": null,
"e": 5096,
"s": 5087,
"text": "Example:"
},
{
"code": "// C# program to create tuple // using Create Methodusing System; public class GFG { // Main method static public void Main() { // Creating 1-tuple // Using Create Method var My_Tuple1 = Tuple.Create(\"GeeksforGeeks\"); // Creating 4-tuple // Using Create Method var My_Tuple2 = Tuple.Create(12, 30, 40, 50); // Creating 8-tuple // Using Create Method var My_Tuple3 = Tuple.Create(13, \"Geeks\", 67, 89.90, 'g', 39939, \"geek\", 10); }}",
"e": 5633,
"s": 5096,
"text": null
},
{
"code": null,
"e": 5903,
"s": 5633,
"text": "You can access the elements of a tuple by using Item<elementNumber> property, here elementNumber is from 1 to 7 like Item1, Item 2, Item3, Item4, Item5, Item6, Item 7, etc. and the last element of 8-tuple is accessible by using Rest property. As shown in below example:"
},
{
"code": null,
"e": 5912,
"s": 5903,
"text": "Example:"
},
{
"code": "// C# program to access the tuple // using Item and Rest propertyusing System; public class GFG { // Main method static public void Main() { // Creating 1-tuple // Using Create Method var My_Tuple1 = Tuple.Create(\"GeeksforGeeks\"); // Accessing the element of Tuple // Using Item property Console.WriteLine(\"Element of My_Tuple1: \" + My_Tuple1.Item1); Console.WriteLine(); // Creating 4-tuple // Using Create Method var My_Tuple2 = Tuple.Create(12, 30, 40, 50); // Accessing the element of Tuple // Using Item property Console.WriteLine(\"Element of My_Tuple2: \" + My_Tuple2.Item1); Console.WriteLine(\"Element of My_Tuple2: \" + My_Tuple2.Item2); Console.WriteLine(\"Element of My_Tuple2: \" + My_Tuple2.Item3); Console.WriteLine(\"Element of My_Tuple2: \" + My_Tuple2.Item4); Console.WriteLine(); // Creating 8-tuple // Using Create Method var My_Tuple3 = Tuple.Create(13, \"Geeks\", 67, 89.90, 'g', 39939, \"geek\", 10); // Accessing the element of Tuple // Using Item property // And print the 8th element of tuple // using Rest property Console.WriteLine(\"Element of My_Tuple3: \" + My_Tuple3.Item1); Console.WriteLine(\"Element of My_Tuple3: \" + My_Tuple3.Item2); Console.WriteLine(\"Element of My_Tuple3: \" + My_Tuple3.Item3); Console.WriteLine(\"Element of My_Tuple3: \" + My_Tuple3.Item4); Console.WriteLine(\"Element of My_Tuple3: \" + My_Tuple3.Item5); Console.WriteLine(\"Element of My_Tuple3: \" + My_Tuple3.Item6); Console.WriteLine(\"Element of My_Tuple3: \" + My_Tuple3.Item7); Console.WriteLine(\"Element of My_Tuple3: \" + My_Tuple3.Rest); }}",
"e": 7712,
"s": 5912,
"text": null
},
{
"code": null,
"e": 7720,
"s": 7712,
"text": "Output:"
},
{
"code": null,
"e": 8070,
"s": 7720,
"text": "Element of My_Tuple1: GeeksforGeeks\n\nElement of My_Tuple2: 12\nElement of My_Tuple2: 30\nElement of My_Tuple2: 40\nElement of My_Tuple2: 50\n\nElement of My_Tuple3: 13\nElement of My_Tuple3: Geeks\nElement of My_Tuple3: 67\nElement of My_Tuple3: 89.9\nElement of My_Tuple3: g\nElement of My_Tuple3: 39939\nElement of My_Tuple3: geek\nElement of My_Tuple3: (10)\n"
},
{
"code": null,
"e": 8650,
"s": 8070,
"text": "In C#, you are allowed to create a tuple into another tuple. You can use nested tuples when you want to add more than eight elements in the same tuple. The nested tuple is accessible by using the Rest property as shown in Example 1. You are allowed to add a nested tuple anywhere in the sequence, but it is recommended that you can place nested tuple at the end of the sequence so that they can easily access from the Rest property. If you place nested tuple other than the last place, then the tuple is accessible according to Item<elementNumber> property as shown in example 2."
},
{
"code": null,
"e": 8661,
"s": 8650,
"text": "Example 1:"
},
{
"code": "// C# program to illustrate nested tupleusing System; public class GFG{ // Main method static public void Main () { // Nested Tuple var My_Tuple = Tuple.Create(13, \"Geeks\", 67, 89.90, 'g', 39939, \"geek\", Tuple.Create(12, 30, 40, 50)); // Accessing the element of Tuple // Using Item property // And accessing the elements of nested tuple // Using Rest property Console.WriteLine(\"Element of My_Tuple: \"+My_Tuple.Item1); Console.WriteLine(\"Element of My_Tuple: \"+My_Tuple.Item2); Console.WriteLine(\"Element of My_Tuple: \"+My_Tuple.Item3); Console.WriteLine(\"Element of My_Tuple: \"+My_Tuple.Item4); Console.WriteLine(\"Element of My_Tuple: \"+My_Tuple.Item5); Console.WriteLine(\"Element of My_Tuple: \"+My_Tuple.Item6); Console.WriteLine(\"Element of My_Tuple: \"+My_Tuple.Item7); Console.WriteLine(\"Element of Nested tuple: \"+My_Tuple.Rest); Console.WriteLine(\"Element of Nested tuple: \"+My_Tuple.Rest.Item1.Item1); Console.WriteLine(\"Element of Nested tuple: \"+My_Tuple.Rest.Item1.Item2); Console.WriteLine(\"Element of Nested tuple: \"+My_Tuple.Rest.Item1.Item3); Console.WriteLine(\"Element of Nested tuple: \"+My_Tuple.Rest.Item1.Item4); }}",
"e": 9988,
"s": 8661,
"text": null
},
{
"code": null,
"e": 9996,
"s": 9988,
"text": "Output:"
},
{
"code": null,
"e": 10331,
"s": 9996,
"text": "Element of My_Tuple: 13\nElement of My_Tuple: Geeks\nElement of My_Tuple: 67\nElement of My_Tuple: 89.9\nElement of My_Tuple: g \nElement of My_Tuple: 39939\nElement of My_Tuple: geek\nElement of Nested tuple: ((12, 30, 40, 50))\nElement of Nested tuple: 12\nElement of Nested tuple: 30\nElement of Nested tuple: 40\nElement of Nested tuple: 50\n"
},
{
"code": null,
"e": 10342,
"s": 10331,
"text": "Example 2:"
},
{
"code": "// C# program to illustrate nested tupleusing System; public class GFG{ // Main method static public void Main () { // Nested Tuple // Here nested tuple is present // at the place of 2nd element var My_Tuple = Tuple.Create(13, Tuple.Create(12, 30, 40, 50),67, 89.90, 'g', 39939, 123, \"geeks\"); // Accessing the element of Tuple // Using Item property // And accessing the elements of // nested tuple Using Rest property Console.WriteLine(\"Element of My_Tuple: \"+My_Tuple.Item1); Console.WriteLine(\"Element of Nested Tuple: \"+My_Tuple.Item2.Item1); Console.WriteLine(\"Element of Nested Tuple: \"+My_Tuple.Item2.Item2); Console.WriteLine(\"Element of Nested Tuple: \"+My_Tuple.Item2.Item3); Console.WriteLine(\"Element of Nested Tuple: \"+My_Tuple.Item2.Item4); Console.WriteLine(\"Element of My_Tuple: \"+My_Tuple.Item3); Console.WriteLine(\"Element of My_Tuple: \"+My_Tuple.Item4); Console.WriteLine(\"Element of My_Tuple: \"+My_Tuple.Item5); Console.WriteLine(\"Element of My_Tuple: \"+My_Tuple.Item6); Console.WriteLine(\"Element of My_Tuple: \"+My_Tuple.Item7); Console.WriteLine(\"Element of My_Tuple: \"+My_Tuple.Rest); }}",
"e": 11688,
"s": 10342,
"text": null
},
{
"code": null,
"e": 11696,
"s": 11688,
"text": "Output:"
},
{
"code": null,
"e": 11986,
"s": 11696,
"text": "Element of My_Tuple: 13\nElement of Nested Tuple: 12\nElement of Nested Tuple: 30\nElement of Nested Tuple: 40\nElement of Nested Tuple: 50\nElement of My_Tuple: 67\nElement of My_Tuple: 89.9\nElement of My_Tuple: g\nElement of My_Tuple: 39939\nElement of My_Tuple: 123\nElement of My_Tuple: (geeks)"
},
{
"code": null,
"e": 12225,
"s": 11986,
"text": "In C#, you are allowed to pass a tuple as a method parameter as shown in the below example. Here we pass a tuple named mytuple in the PrintTheTuple() method and the elements of the tuple are accessed by using Item<elementNumber> property."
},
{
"code": null,
"e": 12234,
"s": 12225,
"text": "Example:"
},
{
"code": "// C# program to illustrate the // tuple as a method parameter.using System; public class GFG{ // Main method static public void Main () { // Creating a tuple var mytuple = Tuple.Create(\"GeeksforGeeks\", 123, 90.8); // Pass the tuple in the // PrintTheTuple method PrintTheTuple(mytuple); } static void PrintTheTuple(Tuple<string, int, double>mytuple) { Console.WriteLine(\"Element: \"+mytuple.Item1); Console.WriteLine(\"Element: \"+mytuple.Item2); Console.WriteLine(\"Element: \"+mytuple.Item3); }}",
"e": 12859,
"s": 12234,
"text": null
},
{
"code": null,
"e": 12867,
"s": 12859,
"text": "Output:"
},
{
"code": null,
"e": 12918,
"s": 12867,
"text": "Element: GeeksforGeeks\nElement: 123\nElement: 90.8\n"
},
{
"code": null,
"e": 13053,
"s": 12918,
"text": "In C#, methods are allowed to use tuple as a return type. Or in other words a method can return a tuple as shown in the below example:"
},
{
"code": null,
"e": 13062,
"s": 13053,
"text": "Example:"
},
{
"code": "// C# program to illustrate // how a method return tupleusing System; public class GFG{ // Main Method static public void Main () { // Return tuple is stored in mytuple var mytuple = PrintTuple(); Console.WriteLine(mytuple.Item1); Console.WriteLine(mytuple.Item2); Console.WriteLine(mytuple.Item3); } // PrintTuple method return a tuple static Tuple<string, string, string>PrintTuple() { return Tuple.Create(\"Geeks\", \"For\", \"Geeks\"); }}",
"e": 13595,
"s": 13062,
"text": null
},
{
"code": null,
"e": 13603,
"s": 13595,
"text": "Output:"
},
{
"code": null,
"e": 13620,
"s": 13603,
"text": "Geeks\nFor\nGeeks\n"
},
{
"code": null,
"e": 13641,
"s": 13620,
"text": "Limitation of Tuple:"
},
{
"code": null,
"e": 13684,
"s": 13641,
"text": "It is of reference type not of value type."
},
{
"code": null,
"e": 13787,
"s": 13684,
"text": "It is limited to eight elements. Means you cannot store more than eight elements without nested tuple."
},
{
"code": null,
"e": 13850,
"s": 13787,
"text": "These are only accessed by using Item<elementNumber> property."
},
{
"code": null,
"e": 13863,
"s": 13850,
"text": "CSharp-Tuple"
},
{
"code": null,
"e": 13866,
"s": 13863,
"text": "C#"
},
{
"code": null,
"e": 13964,
"s": 13866,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 14018,
"s": 13964,
"text": "Difference between Abstract Class and Interface in C#"
},
{
"code": null,
"e": 14080,
"s": 14018,
"text": "C# | How to check whether a List contains a specified element"
},
{
"code": null,
"e": 14103,
"s": 14080,
"text": "C# | Arrays of Strings"
},
{
"code": null,
"e": 14131,
"s": 14103,
"text": "C# | IsNullOrEmpty() Method"
},
{
"code": null,
"e": 14173,
"s": 14131,
"text": "String.Split() Method in C# with Examples"
},
{
"code": null,
"e": 14188,
"s": 14173,
"text": "C# | Delegates"
},
{
"code": null,
"e": 14231,
"s": 14188,
"text": "C# | Multiple inheritance using interfaces"
},
{
"code": null,
"e": 14280,
"s": 14231,
"text": "Differences Between .NET Core and .NET Framework"
},
{
"code": null,
"e": 14320,
"s": 14280,
"text": "C# | String.IndexOf( ) Method | Set - 1"
}
] |
Optimization techniques for Gradient Descent
|
20 Jun, 2022
Gradient Descent is an iterative optimization algorithm, used to find the minimum value for a function. The general idea is to initialize the parameters to random values, and then take small steps in the direction of the “slope” at each iteration. Gradient descent is highly used in supervised learning to minimize the error function and find the optimal values for the parameters. Various extensions have been designed for the gradient descent algorithms. Some of them are discussed below:
Momentum method: This method is used to accelerate the gradient descent algorithm by taking into consideration the exponentially weighted average of the gradients. Using averages makes the algorithm converge towards the minima in a faster way, as the gradients towards the uncommon directions are canceled out. The pseudocode for the momentum method is given below.
V = 0
for each iteration i:
compute dW
V = β V + (1 - β) dW
W = W - α V
V and dW are analogous to velocity and acceleration respectively. α is the learning rate, and β is analogous to momentum normally kept at 0.9. Physics interpretation is that the velocity of a ball rolling downhill builds up momentum according to the direction of slope(gradient) of the hill and therefore helps in better arrival of the ball at a minimum value (in our case – at a minimum loss).
RMSprop: RMSprop was proposed by the University of Toronto’s Geoffrey Hinton. The intuition is to apply an exponentially weighted average method to the second moment of the gradients (dW2). The pseudocode for this is as follows:
S = 0
for each iteration i
compute dW
S = β S + (1 - β) dW2
W = W - α dW⁄√S + ε
Adam Optimization: Adam optimization algorithm incorporates the momentum method and RMSprop, along with bias correction. The pseudocode for this approach is as follows:
V = 0
S = 0
for each iteration i
compute dW
V = β1 S + (1 - β1) dW
S = β2 S + (1 - β2) dW2
V = V⁄{1 - β1i}
S = S⁄{1 - β2i}
W = W - α V⁄√S + ε
Kingma and Ba, the proposers of Adam, recommended the following values for the hyperparameters.
α = 0.001
β1 = 0.9
β2 = 0.999
ε = 10-8
vaibhav29498
darsu2000sharma
jatingrg2399
Advanced Computer Subject
Machine Learning
Mathematical
Mathematical
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
System Design Tutorial
Docker - COPY Instruction
ML | Monte Carlo Tree Search (MCTS)
Getting started with Machine Learning
Markov Decision Process
Agents in Artificial Intelligence
Search Algorithms in AI
Introduction to Recurrent Neural Network
ML | Monte Carlo Tree Search (MCTS)
Getting started with Machine Learning
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n20 Jun, 2022"
},
{
"code": null,
"e": 545,
"s": 54,
"text": "Gradient Descent is an iterative optimization algorithm, used to find the minimum value for a function. The general idea is to initialize the parameters to random values, and then take small steps in the direction of the “slope” at each iteration. Gradient descent is highly used in supervised learning to minimize the error function and find the optimal values for the parameters. Various extensions have been designed for the gradient descent algorithms. Some of them are discussed below:"
},
{
"code": null,
"e": 911,
"s": 545,
"text": "Momentum method: This method is used to accelerate the gradient descent algorithm by taking into consideration the exponentially weighted average of the gradients. Using averages makes the algorithm converge towards the minima in a faster way, as the gradients towards the uncommon directions are canceled out. The pseudocode for the momentum method is given below."
},
{
"code": null,
"e": 995,
"s": 911,
"text": "V = 0\nfor each iteration i:\n compute dW\n V = β V + (1 - β) dW\n W = W - α V"
},
{
"code": null,
"e": 1390,
"s": 995,
"text": "V and dW are analogous to velocity and acceleration respectively. α is the learning rate, and β is analogous to momentum normally kept at 0.9. Physics interpretation is that the velocity of a ball rolling downhill builds up momentum according to the direction of slope(gradient) of the hill and therefore helps in better arrival of the ball at a minimum value (in our case – at a minimum loss)."
},
{
"code": null,
"e": 1619,
"s": 1390,
"text": "RMSprop: RMSprop was proposed by the University of Toronto’s Geoffrey Hinton. The intuition is to apply an exponentially weighted average method to the second moment of the gradients (dW2). The pseudocode for this is as follows:"
},
{
"code": null,
"e": 1711,
"s": 1619,
"text": "S = 0\nfor each iteration i\n compute dW\n S = β S + (1 - β) dW2\n W = W - α dW⁄√S + ε"
},
{
"code": null,
"e": 1880,
"s": 1711,
"text": "Adam Optimization: Adam optimization algorithm incorporates the momentum method and RMSprop, along with bias correction. The pseudocode for this approach is as follows:"
},
{
"code": null,
"e": 2046,
"s": 1880,
"text": "V = 0\nS = 0\nfor each iteration i\n compute dW\n V = β1 S + (1 - β1) dW\n S = β2 S + (1 - β2) dW2\n V = V⁄{1 - β1i}\n S = S⁄{1 - β2i}\n W = W - α V⁄√S + ε"
},
{
"code": null,
"e": 2142,
"s": 2046,
"text": "Kingma and Ba, the proposers of Adam, recommended the following values for the hyperparameters."
},
{
"code": null,
"e": 2181,
"s": 2142,
"text": "α = 0.001\nβ1 = 0.9\nβ2 = 0.999\nε = 10-8"
},
{
"code": null,
"e": 2194,
"s": 2181,
"text": "vaibhav29498"
},
{
"code": null,
"e": 2210,
"s": 2194,
"text": "darsu2000sharma"
},
{
"code": null,
"e": 2223,
"s": 2210,
"text": "jatingrg2399"
},
{
"code": null,
"e": 2249,
"s": 2223,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 2266,
"s": 2249,
"text": "Machine Learning"
},
{
"code": null,
"e": 2279,
"s": 2266,
"text": "Mathematical"
},
{
"code": null,
"e": 2292,
"s": 2279,
"text": "Mathematical"
},
{
"code": null,
"e": 2309,
"s": 2292,
"text": "Machine Learning"
},
{
"code": null,
"e": 2407,
"s": 2309,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2430,
"s": 2407,
"text": "System Design Tutorial"
},
{
"code": null,
"e": 2456,
"s": 2430,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 2492,
"s": 2456,
"text": "ML | Monte Carlo Tree Search (MCTS)"
},
{
"code": null,
"e": 2530,
"s": 2492,
"text": "Getting started with Machine Learning"
},
{
"code": null,
"e": 2554,
"s": 2530,
"text": "Markov Decision Process"
},
{
"code": null,
"e": 2588,
"s": 2554,
"text": "Agents in Artificial Intelligence"
},
{
"code": null,
"e": 2612,
"s": 2588,
"text": "Search Algorithms in AI"
},
{
"code": null,
"e": 2653,
"s": 2612,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 2689,
"s": 2653,
"text": "ML | Monte Carlo Tree Search (MCTS)"
}
] |
PyQt5 | How to create colorful border of Push Button ?
|
22 Apr, 2020
In this article we will see how to create colorful border of Push button. By default, push button have a button but we can also change the border color and size as well. PyQt5 allows us to change the color of push button with the help of style sheet.
Syntax :
button.setStyleSheet("border :5px solid ;"
"border-top-color : red; "
"border-left-color :pink;"
"border-right-color :yellow;"
"border-bottom-color : green")
Argument : It takes string as argument.
Action performed : It will set different color to different sides.
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, 40) # adding action to a button button.clicked.connect(self.clickme) # creating colorful border button.setStyleSheet("border :5px solid ;" "border-top-color : red; " "border-left-color :pink;" "border-right-color :yellow;" "border-bottom-color : green") # 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.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n22 Apr, 2020"
},
{
"code": null,
"e": 304,
"s": 53,
"text": "In this article we will see how to create colorful border of Push button. By default, push button have a button but we can also change the border color and size as well. PyQt5 allows us to change the color of push button with the help of style sheet."
},
{
"code": null,
"e": 313,
"s": 304,
"text": "Syntax :"
},
{
"code": null,
"e": 556,
"s": 313,
"text": "button.setStyleSheet(\"border :5px solid ;\"\n \"border-top-color : red; \"\n \"border-left-color :pink;\"\n \"border-right-color :yellow;\"\n \"border-bottom-color : green\")\n"
},
{
"code": null,
"e": 596,
"s": 556,
"text": "Argument : It takes string as argument."
},
{
"code": null,
"e": 663,
"s": 596,
"text": "Action performed : It will set different color to different sides."
},
{
"code": null,
"e": 670,
"s": 663,
"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, 40) # adding action to a button button.clicked.connect(self.clickme) # creating colorful border button.setStyleSheet(\"border :5px solid ;\" \"border-top-color : red; \" \"border-left-color :pink;\" \"border-right-color :yellow;\" \"border-bottom-color : green\") # 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": 1953,
"s": 670,
"text": null
},
{
"code": null,
"e": 1962,
"s": 1953,
"text": "Output :"
},
{
"code": null,
"e": 1973,
"s": 1962,
"text": "Python-gui"
},
{
"code": null,
"e": 1985,
"s": 1973,
"text": "Python-PyQt"
},
{
"code": null,
"e": 1992,
"s": 1985,
"text": "Python"
}
] |
Python | Pandas dataframe.subtract()
|
22 Sep, 2021
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.subtract() function is used for finding the subtraction of dataframe and other, element-wise. This function is essentially same as doing dataframe – other but with a support to substitute for missing data in one of the inputs.
Syntax: DataFrame.subtract(other, axis=’columns’, level=None, fill_value=None)Parameters : other : Series, DataFrame, or constant axis : For Series input, axis to match Series index on level : Broadcast across a level, matching Index values on the passed MultiIndex levelfill_value : Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing.Returns : result : DataFrame
Example #1: Use subtract() function to subtract each element of a dataframe with a corresponding element in a series.
Python3
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
default, selected
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
# importing pandas as pdimport pandas as pd # Creating the dataframedf = pd.DataFrame({"A":[1, 5, 3, 4, 2], "B":[3, 2, 4, 3, 4], "C":[2, 2, 7, 3, 4], "D":[4, 3, 6, 12, 7]}, index =["A1", "A2", "A3", "A4", "A5"]) # Print the dataframedf
Let’s create the series
Python3
# importing pandas as pdimport pandas as pd # Create the seriessr = pd.Series([12, 25, 64, 18], index =["A", "B", "C", "D"]) # Print the seriessr
Let’s use the dataframe.subtract() function for subtraction.
Python3
# equivalent to df - srdf.subtract(sr, axis = 1)
Output :
Example #2: Use subtract() function to subtract each element in a dataframe with the corresponding element in other dataframe
Python3
# importing pandas as pdimport pandas as pd # Creating the first dataframedf1 = pd.DataFrame({"A":[1, 5, 3, 4, 2], "B":[3, 2, 4, 3, 4], "C":[2, 2, 7, 3, 4], "D":[4, 3, 6, 12, 7]}, index =["A1", "A2", "A3", "A4", "A5"]) # Creating the second dataframedf2 = pd.DataFrame({"A":[10, 11, 7, 8, 5], "B":[21, 5, 32, 4, 6], "C":[11, 21, 23, 7, 9], "D":[1, 5, 3, 8, 6]}, index =["A1", "A2", "A3", "A4", "A5"]) # subtract df2 from df1df1.subtract(df2)
Output :
Notice, each element of the dataframe df1 has been subtracted with the corresponding element in the df2.
Python | Pandas dataframe.subtract() | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersPython | Pandas dataframe.subtract() | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:01•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=yHR-ZUmmrQQ" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
sweetyty
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.
Different ways to create Pandas Dataframe
Enumerate() in Python
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
Create a Pandas DataFrame from Lists
How to drop one or multiple columns in Pandas Dataframe
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Sep, 2021"
},
{
"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": 487,
"s": 242,
"text": "Pandas dataframe.subtract() function is used for finding the subtraction of dataframe and other, element-wise. This function is essentially same as doing dataframe – other but with a support to substitute for missing data in one of the inputs. "
},
{
"code": null,
"e": 1024,
"s": 487,
"text": "Syntax: DataFrame.subtract(other, axis=’columns’, level=None, fill_value=None)Parameters : other : Series, DataFrame, or constant axis : For Series input, axis to match Series index on level : Broadcast across a level, matching Index values on the passed MultiIndex levelfill_value : Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing.Returns : result : DataFrame "
},
{
"code": null,
"e": 1143,
"s": 1024,
"text": "Example #1: Use subtract() function to subtract each element of a dataframe with a corresponding element in a series. "
},
{
"code": null,
"e": 1151,
"s": 1143,
"text": "Python3"
},
{
"code": null,
"e": 1160,
"s": 1151,
"text": "Chapters"
},
{
"code": null,
"e": 1187,
"s": 1160,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 1237,
"s": 1187,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 1260,
"s": 1237,
"text": "captions off, selected"
},
{
"code": null,
"e": 1268,
"s": 1260,
"text": "English"
},
{
"code": null,
"e": 1286,
"s": 1268,
"text": "default, selected"
},
{
"code": null,
"e": 1310,
"s": 1286,
"text": "This is a modal window."
},
{
"code": null,
"e": 1379,
"s": 1310,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 1401,
"s": 1379,
"text": "End of dialog window."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the dataframedf = pd.DataFrame({\"A\":[1, 5, 3, 4, 2], \"B\":[3, 2, 4, 3, 4], \"C\":[2, 2, 7, 3, 4], \"D\":[4, 3, 6, 12, 7]}, index =[\"A1\", \"A2\", \"A3\", \"A4\", \"A5\"]) # Print the dataframedf",
"e": 1709,
"s": 1401,
"text": null
},
{
"code": null,
"e": 1734,
"s": 1709,
"text": "Let’s create the series "
},
{
"code": null,
"e": 1742,
"s": 1734,
"text": "Python3"
},
{
"code": "# importing pandas as pdimport pandas as pd # Create the seriessr = pd.Series([12, 25, 64, 18], index =[\"A\", \"B\", \"C\", \"D\"]) # Print the seriessr",
"e": 1888,
"s": 1742,
"text": null
},
{
"code": null,
"e": 1949,
"s": 1888,
"text": "Let’s use the dataframe.subtract() function for subtraction."
},
{
"code": null,
"e": 1957,
"s": 1949,
"text": "Python3"
},
{
"code": "# equivalent to df - srdf.subtract(sr, axis = 1)",
"e": 2006,
"s": 1957,
"text": null
},
{
"code": null,
"e": 2016,
"s": 2006,
"text": "Output : "
},
{
"code": null,
"e": 2144,
"s": 2016,
"text": " Example #2: Use subtract() function to subtract each element in a dataframe with the corresponding element in other dataframe"
},
{
"code": null,
"e": 2152,
"s": 2144,
"text": "Python3"
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the first dataframedf1 = pd.DataFrame({\"A\":[1, 5, 3, 4, 2], \"B\":[3, 2, 4, 3, 4], \"C\":[2, 2, 7, 3, 4], \"D\":[4, 3, 6, 12, 7]}, index =[\"A1\", \"A2\", \"A3\", \"A4\", \"A5\"]) # Creating the second dataframedf2 = pd.DataFrame({\"A\":[10, 11, 7, 8, 5], \"B\":[21, 5, 32, 4, 6], \"C\":[11, 21, 23, 7, 9], \"D\":[1, 5, 3, 8, 6]}, index =[\"A1\", \"A2\", \"A3\", \"A4\", \"A5\"]) # subtract df2 from df1df1.subtract(df2)",
"e": 2746,
"s": 2152,
"text": null
},
{
"code": null,
"e": 2756,
"s": 2746,
"text": "Output : "
},
{
"code": null,
"e": 2862,
"s": 2756,
"text": "Notice, each element of the dataframe df1 has been subtracted with the corresponding element in the df2. "
},
{
"code": null,
"e": 3752,
"s": 2862,
"text": "Python | Pandas dataframe.subtract() | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersPython | Pandas dataframe.subtract() | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:01•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=yHR-ZUmmrQQ\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 3763,
"s": 3754,
"text": "sweetyty"
},
{
"code": null,
"e": 3787,
"s": 3763,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 3819,
"s": 3787,
"text": "Python pandas-dataFrame-methods"
},
{
"code": null,
"e": 3833,
"s": 3819,
"text": "Python-pandas"
},
{
"code": null,
"e": 3840,
"s": 3833,
"text": "Python"
},
{
"code": null,
"e": 3938,
"s": 3840,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3980,
"s": 3938,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 4002,
"s": 3980,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 4034,
"s": 4002,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 4063,
"s": 4034,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 4090,
"s": 4063,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 4111,
"s": 4090,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 4147,
"s": 4111,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 4170,
"s": 4147,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 4207,
"s": 4170,
"text": "Create a Pandas DataFrame from Lists"
}
] |
Identifiers in Go Language
|
18 Nov, 2019
In programming languages, identifiers are used for identification purposes. Or in other words, identifiers are the user-defined name of the program components. In Go language, an identifier can be a variable name, function name, constant, statement labels, package name, or types.
Example:
package main
import "fmt"
func main() {
var name = "GeeksforGeeks"
}
There is total of three identifiers available in the above example:
main: Name of the package
main: Name of the function
name: Name of the variable
Rules for Defining Identifiers: There are certain valid rules for defining a valid Go identifier. These rules should be followed, otherwise, we will get a compile-time error.
The name of the identifier must begin with a letter or an underscore(_). And the names may contain the letters ‘a-z’ or ’A-Z’ or digits 0-9 as well as the character ‘_’.
The name of the identifier should not start with a digit.
The name of the identifier is case sensitive.
Keywords is not allowed to use as an identifier name.
There is no limit on the length of the name of the identifier, but it is advisable to use an optimum length of 4 – 15 letters only.
Example:
// Valid identifiers:
_geeks23
geeks
gek23sd
Geeks
geeKs
geeks_geeks
// Invalid identifiers:
212geeks
if
default
Note:
In Go language, there are some predeclared identifiers are available for constants, types, and functions. These names are not reserved, you are allowed to use them in the declaration. Following is the list of predeclared identifiers:For Constants:
true, false, iota, nil
For Types:
int, int8, int16, int32, int64, uint,
uint8, uint16, uint32, uint64, uintptr,
float32, float64, complex128, complex64,
bool, byte, rune, string, error
For Functions:
make, len, cap, new, append, copy, close,
delete, complex, real, imag, panic, recover
For Constants:
true, false, iota, nil
For Types:
int, int8, int16, int32, int64, uint,
uint8, uint16, uint32, uint64, uintptr,
float32, float64, complex128, complex64,
bool, byte, rune, string, error
For Functions:
make, len, cap, new, append, copy, close,
delete, complex, real, imag, panic, recover
The identifier represented by the underscore character(_) is known as a blank identifier. It is used as an anonymous placeholder instead of a regular identifier, and it has a special meaning in declarations, as an operand, and in assignments.
The identifier which is allowed to access it from another package is known as the exported identifier. The exported identifiers are those identifiers which obey the following conditions:The first character of the exported identifier’s name should be in the Unicode upper case letter.The identifier should be declared in the package block, or it is a variable name, or it is a method name.
The first character of the exported identifier’s name should be in the Unicode upper case letter.
The identifier should be declared in the package block, or it is a variable name, or it is a method name.
The uniqueness of the identifiers means the identifier is unique from the other set of the identifiers available in your program, or in the package and they are not exported.
Go-Basics
Golang
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to concatenate two strings in Golang
time.Sleep() Function in Golang With Examples
strings.Contains Function in Golang with Examples
strings.Replace() Function in Golang With Examples
fmt.Sprintf() Function in Golang With Examples
Golang Maps
Time Formatting in Golang
Interfaces in Golang
Different Ways to Find the Type of Variable in Golang
How to Parse JSON in Golang?
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n18 Nov, 2019"
},
{
"code": null,
"e": 334,
"s": 53,
"text": "In programming languages, identifiers are used for identification purposes. Or in other words, identifiers are the user-defined name of the program components. In Go language, an identifier can be a variable name, function name, constant, statement labels, package name, or types."
},
{
"code": null,
"e": 343,
"s": 334,
"text": "Example:"
},
{
"code": null,
"e": 419,
"s": 343,
"text": "package main\nimport \"fmt\"\n\nfunc main() {\n\n var name = \"GeeksforGeeks\"\n \n}\n"
},
{
"code": null,
"e": 487,
"s": 419,
"text": "There is total of three identifiers available in the above example:"
},
{
"code": null,
"e": 513,
"s": 487,
"text": "main: Name of the package"
},
{
"code": null,
"e": 540,
"s": 513,
"text": "main: Name of the function"
},
{
"code": null,
"e": 567,
"s": 540,
"text": "name: Name of the variable"
},
{
"code": null,
"e": 742,
"s": 567,
"text": "Rules for Defining Identifiers: There are certain valid rules for defining a valid Go identifier. These rules should be followed, otherwise, we will get a compile-time error."
},
{
"code": null,
"e": 912,
"s": 742,
"text": "The name of the identifier must begin with a letter or an underscore(_). And the names may contain the letters ‘a-z’ or ’A-Z’ or digits 0-9 as well as the character ‘_’."
},
{
"code": null,
"e": 970,
"s": 912,
"text": "The name of the identifier should not start with a digit."
},
{
"code": null,
"e": 1016,
"s": 970,
"text": "The name of the identifier is case sensitive."
},
{
"code": null,
"e": 1070,
"s": 1016,
"text": "Keywords is not allowed to use as an identifier name."
},
{
"code": null,
"e": 1202,
"s": 1070,
"text": "There is no limit on the length of the name of the identifier, but it is advisable to use an optimum length of 4 – 15 letters only."
},
{
"code": null,
"e": 1211,
"s": 1202,
"text": "Example:"
},
{
"code": null,
"e": 1326,
"s": 1211,
"text": "// Valid identifiers:\n_geeks23\ngeeks\ngek23sd\nGeeks\ngeeKs\ngeeks_geeks\n\n// Invalid identifiers:\n212geeks\nif\ndefault\n"
},
{
"code": null,
"e": 1332,
"s": 1326,
"text": "Note:"
},
{
"code": null,
"e": 1870,
"s": 1332,
"text": "In Go language, there are some predeclared identifiers are available for constants, types, and functions. These names are not reserved, you are allowed to use them in the declaration. Following is the list of predeclared identifiers:For Constants:\ntrue, false, iota, nil\n\nFor Types:\nint, int8, int16, int32, int64, uint,\nuint8, uint16, uint32, uint64, uintptr,\nfloat32, float64, complex128, complex64,\nbool, byte, rune, string, error\n\nFor Functions:\nmake, len, cap, new, append, copy, close, \ndelete, complex, real, imag, panic, recover\n"
},
{
"code": null,
"e": 2175,
"s": 1870,
"text": "For Constants:\ntrue, false, iota, nil\n\nFor Types:\nint, int8, int16, int32, int64, uint,\nuint8, uint16, uint32, uint64, uintptr,\nfloat32, float64, complex128, complex64,\nbool, byte, rune, string, error\n\nFor Functions:\nmake, len, cap, new, append, copy, close, \ndelete, complex, real, imag, panic, recover\n"
},
{
"code": null,
"e": 2418,
"s": 2175,
"text": "The identifier represented by the underscore character(_) is known as a blank identifier. It is used as an anonymous placeholder instead of a regular identifier, and it has a special meaning in declarations, as an operand, and in assignments."
},
{
"code": null,
"e": 2807,
"s": 2418,
"text": "The identifier which is allowed to access it from another package is known as the exported identifier. The exported identifiers are those identifiers which obey the following conditions:The first character of the exported identifier’s name should be in the Unicode upper case letter.The identifier should be declared in the package block, or it is a variable name, or it is a method name."
},
{
"code": null,
"e": 2905,
"s": 2807,
"text": "The first character of the exported identifier’s name should be in the Unicode upper case letter."
},
{
"code": null,
"e": 3011,
"s": 2905,
"text": "The identifier should be declared in the package block, or it is a variable name, or it is a method name."
},
{
"code": null,
"e": 3186,
"s": 3011,
"text": "The uniqueness of the identifiers means the identifier is unique from the other set of the identifiers available in your program, or in the package and they are not exported."
},
{
"code": null,
"e": 3196,
"s": 3186,
"text": "Go-Basics"
},
{
"code": null,
"e": 3203,
"s": 3196,
"text": "Golang"
},
{
"code": null,
"e": 3215,
"s": 3203,
"text": "Go Language"
},
{
"code": null,
"e": 3313,
"s": 3215,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3365,
"s": 3313,
"text": "Different ways to concatenate two strings in Golang"
},
{
"code": null,
"e": 3411,
"s": 3365,
"text": "time.Sleep() Function in Golang With Examples"
},
{
"code": null,
"e": 3461,
"s": 3411,
"text": "strings.Contains Function in Golang with Examples"
},
{
"code": null,
"e": 3512,
"s": 3461,
"text": "strings.Replace() Function in Golang With Examples"
},
{
"code": null,
"e": 3559,
"s": 3512,
"text": "fmt.Sprintf() Function in Golang With Examples"
},
{
"code": null,
"e": 3571,
"s": 3559,
"text": "Golang Maps"
},
{
"code": null,
"e": 3597,
"s": 3571,
"text": "Time Formatting in Golang"
},
{
"code": null,
"e": 3618,
"s": 3597,
"text": "Interfaces in Golang"
},
{
"code": null,
"e": 3672,
"s": 3618,
"text": "Different Ways to Find the Type of Variable in Golang"
}
] |
Mongoose | exists() Function
|
21 May, 2020
The exists() function returns true if at least one document exists in the database that matches the given filter, and false otherwise.
Installation of mongoose module:
You can visit the link to Install mongoose module. You can install this package by using this command.npm install mongooseAfter installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongooseAfter that, you can create a folder and add a file, for example index.js. To run this file you need to run the following command.node index.js
You can visit the link to Install mongoose module. You can install this package by using this command.npm install mongoose
npm install mongoose
After installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongoose
npm version mongoose
After that, you can create a folder and add a file, for example index.js. To run this file you need to run the following command.node index.js
node index.js
Filename: index.js
const mongoose = require('mongoose'); // Database Connectionmongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true}); // User modelconst User = mongoose.model('User', { name: { type: String }, age: { type: Number }}); User.exists({name:'Gourav'}, function (err, doc) { if (err){ console.log(err) }else{ console.log("Result :", doc) // false }}); User.exists({name:'Amit'}, function (err, doc) { if (err){ console.log(err) }else{ console.log("Result :", doc) // true }});
Steps to run the program:
The project structure will look like this:Make sure you have install mongoose module using following command:npm install mongooseBelow is the sample data in the database before the function is executed, You can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below:Run index.js file using below command:node index.js
The project structure will look like this:
Make sure you have install mongoose module using following command:npm install mongoose
npm install mongoose
Below is the sample data in the database before the function is executed, You can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below:
Run index.js file using below command:node index.js
node index.js
So this is how you can use the mongoose exists() function which returns true if at least one document exists in the database that matches the given filter, and false otherwise.
Mongoose
MongoDB
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Spring Boot JpaRepository with Example
Mongoose Populate() Method
MongoDB - db.collection.Find() Method
Aggregation in MongoDB
Upsert in MongoDB
How to update Node.js and NPM to next version ?
Installation of Node.js on Linux
Node.js fs.readFileSync() Method
How to install the previous version of node.js and npm ?
Node.js fs.writeFile() Method
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 May, 2020"
},
{
"code": null,
"e": 163,
"s": 28,
"text": "The exists() function returns true if at least one document exists in the database that matches the given filter, and false otherwise."
},
{
"code": null,
"e": 196,
"s": 163,
"text": "Installation of mongoose module:"
},
{
"code": null,
"e": 587,
"s": 196,
"text": "You can visit the link to Install mongoose module. You can install this package by using this command.npm install mongooseAfter installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongooseAfter that, you can create a folder and add a file, for example index.js. To run this file you need to run the following command.node index.js"
},
{
"code": null,
"e": 710,
"s": 587,
"text": "You can visit the link to Install mongoose module. You can install this package by using this command.npm install mongoose"
},
{
"code": null,
"e": 731,
"s": 710,
"text": "npm install mongoose"
},
{
"code": null,
"e": 858,
"s": 731,
"text": "After installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongoose"
},
{
"code": null,
"e": 879,
"s": 858,
"text": "npm version mongoose"
},
{
"code": null,
"e": 1022,
"s": 879,
"text": "After that, you can create a folder and add a file, for example index.js. To run this file you need to run the following command.node index.js"
},
{
"code": null,
"e": 1036,
"s": 1022,
"text": "node index.js"
},
{
"code": null,
"e": 1055,
"s": 1036,
"text": "Filename: index.js"
},
{
"code": "const mongoose = require('mongoose'); // Database Connectionmongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true}); // User modelconst User = mongoose.model('User', { name: { type: String }, age: { type: Number }}); User.exists({name:'Gourav'}, function (err, doc) { if (err){ console.log(err) }else{ console.log(\"Result :\", doc) // false }}); User.exists({name:'Amit'}, function (err, doc) { if (err){ console.log(err) }else{ console.log(\"Result :\", doc) // true }});",
"e": 1668,
"s": 1055,
"text": null
},
{
"code": null,
"e": 1694,
"s": 1668,
"text": "Steps to run the program:"
},
{
"code": null,
"e": 2056,
"s": 1694,
"text": "The project structure will look like this:Make sure you have install mongoose module using following command:npm install mongooseBelow is the sample data in the database before the function is executed, You can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below:Run index.js file using below command:node index.js"
},
{
"code": null,
"e": 2099,
"s": 2056,
"text": "The project structure will look like this:"
},
{
"code": null,
"e": 2187,
"s": 2099,
"text": "Make sure you have install mongoose module using following command:npm install mongoose"
},
{
"code": null,
"e": 2208,
"s": 2187,
"text": "npm install mongoose"
},
{
"code": null,
"e": 2390,
"s": 2208,
"text": "Below is the sample data in the database before the function is executed, You can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below:"
},
{
"code": null,
"e": 2442,
"s": 2390,
"text": "Run index.js file using below command:node index.js"
},
{
"code": null,
"e": 2456,
"s": 2442,
"text": "node index.js"
},
{
"code": null,
"e": 2633,
"s": 2456,
"text": "So this is how you can use the mongoose exists() function which returns true if at least one document exists in the database that matches the given filter, and false otherwise."
},
{
"code": null,
"e": 2642,
"s": 2633,
"text": "Mongoose"
},
{
"code": null,
"e": 2650,
"s": 2642,
"text": "MongoDB"
},
{
"code": null,
"e": 2658,
"s": 2650,
"text": "Node.js"
},
{
"code": null,
"e": 2675,
"s": 2658,
"text": "Web Technologies"
},
{
"code": null,
"e": 2773,
"s": 2675,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2812,
"s": 2773,
"text": "Spring Boot JpaRepository with Example"
},
{
"code": null,
"e": 2839,
"s": 2812,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 2877,
"s": 2839,
"text": "MongoDB - db.collection.Find() Method"
},
{
"code": null,
"e": 2900,
"s": 2877,
"text": "Aggregation in MongoDB"
},
{
"code": null,
"e": 2918,
"s": 2900,
"text": "Upsert in MongoDB"
},
{
"code": null,
"e": 2966,
"s": 2918,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 2999,
"s": 2966,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3032,
"s": 2999,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 3089,
"s": 3032,
"text": "How to install the previous version of node.js and npm ?"
}
] |
Recover in Golang
|
17 Sep, 2019
Just like try/catch block in exception in languages like Java, C#, etc. are used to catch exception similarly in Go language, recover function is used to handle panic. It is an inbuilt function which is defined under the builtin package of the Go language. The main use of this function is to regain control of a panicking Goroutine. Or in other words, it handles the panicking behavior of the Goroutine.
Syntax:
func recover() interface{}
Important Points:
Recover function is always called inside the deferred function, not in the normal function. If you call recover function inside the normal function or outside the deferred function, then the recover function does not stop the panicking sequence as shown in Example 1. So, always called recover function inside the deferred function because the deferred function does not stop its execution if the program panic, so the recover function stops the panicking sequence by simply restoring the normal execution of the goroutine and retrieves the error value passed to the call of panic as shown in the Example 2.
Recover function only work if you call in the same goroutine in which panic occurs. If you call it in a different goroutine, then it will not work as shown in Example 3.
If you want to find the stack trace, then use the PrintStack function which is defined under Debug package.
Example 1:
// Go program which illustrates// the concept of recoverpackage main import "fmt" // This function is created to handle// the panic occurs in entry function// but it does not handle the panic // occurred in the entry function// because it called in the normal// functionfunc handlepanic() { if a := recover(); a != nil { fmt.Println("RECOVER", a) }} // Functionfunc entry(lang *string, aname *string) { // Normal function handlepanic() // When the value of lang // is nil it will panic if lang == nil { panic("Error: Language cannot be nil") } // When the value of aname // is nil it will panic if aname == nil { panic("Error: Author name cannot be nil") } fmt.Printf("Author Language: %s \n Author Name: %s\n", *lang, *aname) fmt.Printf("Return successfully from the entry function")} // Main functionfunc main() { A_lang := "GO Language" entry(&A_lang, nil) fmt.Printf("Return successfully from the main function")}
Output:
panic: Error: Author name cannot be nil
goroutine 1 [running]:
main.entry(0x41a788, 0x0)
/tmp/sandbox777592252/prog.go:35 +0x180
main.main()
/tmp/sandbox777592252/prog.go:46 +0x40
Example 2:
// Go program which illustrates// the concept of recoverpackage main import ( "fmt") // This function handles the panic// occur in entry function// with the help of the recover functionfunc handlepanic() { if a := recover(); a != nil { fmt.Println("RECOVER", a) }} // Functionfunc entry(lang *string, aname *string) { // Deferred function defer handlepanic() // When the value of lang // is nil it will panic if lang == nil { panic("Error: Language cannot be nil") } // When the value of aname // is nil it will panic if aname == nil { panic("Error: Author name cannot be nil") } fmt.Printf("Author Language: %s \n Author Name: %s\n", *lang, *aname) fmt.Printf("Return successfully from the entry function")} // Main functionfunc main() { A_lang := "GO Language" entry(&A_lang, nil) fmt.Printf("Return successfully from the main function")}
Output:
RECOVER Error: Author name cannot be nil
Return successfully from the main function
Example 3:
// Go program which illustrates// recover in a goroutinepackage main import ( "fmt" "time") // For recoveryfunc handlepanic() { if a := recover(); a != nil { fmt.Println("RECOVER", a) }} /* Here, this panic is not handled by the recover function because of the recover function is not called in the same goroutine in which the panic occurs */ // Function 1func myfun1() { defer handlepanic() fmt.Println("Welcome to Function 1") go myfun2() time.Sleep(10 * time.Second)} // Function 2func myfun2() { fmt.Println("Welcome to Function 2") panic("Panicked!!")} // Main functionfunc main() { myfun1() fmt.Println("Return successfully from the main function")}
Output:
Welcome to Function 1
Welcome to Function 2
panic: Panicked!!
goroutine 6 [running]:
main.myfun2()
/tmp/sandbox157568972/prog.go:31 +0xa0
created by main.myfun1
/tmp/sandbox157568972/prog.go:24 +0xc0
Golang
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
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 Trim a String in Golang?
How to convert a string in lower case in Golang?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Sep, 2019"
},
{
"code": null,
"e": 433,
"s": 28,
"text": "Just like try/catch block in exception in languages like Java, C#, etc. are used to catch exception similarly in Go language, recover function is used to handle panic. It is an inbuilt function which is defined under the builtin package of the Go language. The main use of this function is to regain control of a panicking Goroutine. Or in other words, it handles the panicking behavior of the Goroutine."
},
{
"code": null,
"e": 441,
"s": 433,
"text": "Syntax:"
},
{
"code": null,
"e": 468,
"s": 441,
"text": "func recover() interface{}"
},
{
"code": null,
"e": 486,
"s": 468,
"text": "Important Points:"
},
{
"code": null,
"e": 1094,
"s": 486,
"text": "Recover function is always called inside the deferred function, not in the normal function. If you call recover function inside the normal function or outside the deferred function, then the recover function does not stop the panicking sequence as shown in Example 1. So, always called recover function inside the deferred function because the deferred function does not stop its execution if the program panic, so the recover function stops the panicking sequence by simply restoring the normal execution of the goroutine and retrieves the error value passed to the call of panic as shown in the Example 2."
},
{
"code": null,
"e": 1264,
"s": 1094,
"text": "Recover function only work if you call in the same goroutine in which panic occurs. If you call it in a different goroutine, then it will not work as shown in Example 3."
},
{
"code": null,
"e": 1372,
"s": 1264,
"text": "If you want to find the stack trace, then use the PrintStack function which is defined under Debug package."
},
{
"code": null,
"e": 1383,
"s": 1372,
"text": "Example 1:"
},
{
"code": "// Go program which illustrates// the concept of recoverpackage main import \"fmt\" // This function is created to handle// the panic occurs in entry function// but it does not handle the panic // occurred in the entry function// because it called in the normal// functionfunc handlepanic() { if a := recover(); a != nil { fmt.Println(\"RECOVER\", a) }} // Functionfunc entry(lang *string, aname *string) { // Normal function handlepanic() // When the value of lang // is nil it will panic if lang == nil { panic(\"Error: Language cannot be nil\") } // When the value of aname // is nil it will panic if aname == nil { panic(\"Error: Author name cannot be nil\") } fmt.Printf(\"Author Language: %s \\n Author Name: %s\\n\", *lang, *aname) fmt.Printf(\"Return successfully from the entry function\")} // Main functionfunc main() { A_lang := \"GO Language\" entry(&A_lang, nil) fmt.Printf(\"Return successfully from the main function\")}",
"e": 2397,
"s": 1383,
"text": null
},
{
"code": null,
"e": 2405,
"s": 2397,
"text": "Output:"
},
{
"code": null,
"e": 2595,
"s": 2405,
"text": "panic: Error: Author name cannot be nil\n\ngoroutine 1 [running]:\nmain.entry(0x41a788, 0x0)\n /tmp/sandbox777592252/prog.go:35 +0x180\nmain.main()\n /tmp/sandbox777592252/prog.go:46 +0x40\n"
},
{
"code": null,
"e": 2606,
"s": 2595,
"text": "Example 2:"
},
{
"code": "// Go program which illustrates// the concept of recoverpackage main import ( \"fmt\") // This function handles the panic// occur in entry function// with the help of the recover functionfunc handlepanic() { if a := recover(); a != nil { fmt.Println(\"RECOVER\", a) }} // Functionfunc entry(lang *string, aname *string) { // Deferred function defer handlepanic() // When the value of lang // is nil it will panic if lang == nil { panic(\"Error: Language cannot be nil\") } // When the value of aname // is nil it will panic if aname == nil { panic(\"Error: Author name cannot be nil\") } fmt.Printf(\"Author Language: %s \\n Author Name: %s\\n\", *lang, *aname) fmt.Printf(\"Return successfully from the entry function\")} // Main functionfunc main() { A_lang := \"GO Language\" entry(&A_lang, nil) fmt.Printf(\"Return successfully from the main function\")}",
"e": 3552,
"s": 2606,
"text": null
},
{
"code": null,
"e": 3560,
"s": 3552,
"text": "Output:"
},
{
"code": null,
"e": 3645,
"s": 3560,
"text": "RECOVER Error: Author name cannot be nil\nReturn successfully from the main function\n"
},
{
"code": null,
"e": 3656,
"s": 3645,
"text": "Example 3:"
},
{
"code": "// Go program which illustrates// recover in a goroutinepackage main import ( \"fmt\" \"time\") // For recoveryfunc handlepanic() { if a := recover(); a != nil { fmt.Println(\"RECOVER\", a) }} /* Here, this panic is not handled by the recover function because of the recover function is not called in the same goroutine in which the panic occurs */ // Function 1func myfun1() { defer handlepanic() fmt.Println(\"Welcome to Function 1\") go myfun2() time.Sleep(10 * time.Second)} // Function 2func myfun2() { fmt.Println(\"Welcome to Function 2\") panic(\"Panicked!!\")} // Main functionfunc main() { myfun1() fmt.Println(\"Return successfully from the main function\")}",
"e": 4385,
"s": 3656,
"text": null
},
{
"code": null,
"e": 4393,
"s": 4385,
"text": "Output:"
},
{
"code": null,
"e": 4603,
"s": 4393,
"text": "Welcome to Function 1\nWelcome to Function 2\npanic: Panicked!!\n\ngoroutine 6 [running]:\nmain.myfun2()\n /tmp/sandbox157568972/prog.go:31 +0xa0\ncreated by main.myfun1\n /tmp/sandbox157568972/prog.go:24 +0xc0\n"
},
{
"code": null,
"e": 4610,
"s": 4603,
"text": "Golang"
},
{
"code": null,
"e": 4622,
"s": 4610,
"text": "Go Language"
},
{
"code": null,
"e": 4720,
"s": 4622,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4771,
"s": 4720,
"text": "strings.Replace() Function in Golang With Examples"
},
{
"code": null,
"e": 4784,
"s": 4771,
"text": "Arrays in Go"
},
{
"code": null,
"e": 4796,
"s": 4784,
"text": "Golang Maps"
},
{
"code": null,
"e": 4829,
"s": 4796,
"text": "How to Split a String in Golang?"
},
{
"code": null,
"e": 4850,
"s": 4829,
"text": "Interfaces in Golang"
},
{
"code": null,
"e": 4867,
"s": 4850,
"text": "Slices in Golang"
},
{
"code": null,
"e": 4921,
"s": 4867,
"text": "Different Ways to Find the Type of Variable in Golang"
},
{
"code": null,
"e": 4950,
"s": 4921,
"text": "How to Parse JSON in Golang?"
},
{
"code": null,
"e": 4982,
"s": 4950,
"text": "How to Trim a String in Golang?"
}
] |
Docker - Toolbox
|
In the introductory chapters, we have seen the installation of Docker toolbox on Windows. The Docker toolbox is developed so that Docker containers can be run on Windows and MacOS. The site for toolbox on Windows is https://docs.docker.com/docker-for-windows/
For Windows, you need to have Windows 10 or Windows Server 2016 with Hyper-V enabled.
The toolbox consists of the following components −
Docker Engine − This is used as the base engine or Docker daemon that is used to run Docker containers.
Docker Engine − This is used as the base engine or Docker daemon that is used to run Docker containers.
Docker Machine − for running Docker machine commands.
Docker Machine − for running Docker machine commands.
Docker Compose for running Docker compose commands.
Docker Compose for running Docker compose commands.
Kinematic − This is the Docker GUI built for Windows and Mac OS.
Kinematic − This is the Docker GUI built for Windows and Mac OS.
Oracle virtualbox
Oracle virtualbox
Let’s now discuss the different types of activities that are possible with Docker toolbox.
With Docker toolbox on Windows 10, you can now run Docker commands off powershell. If you open powershell on Windows and type in the command of Docker version, you will get all the required details about the Docker version installed.
You can also now pull Images from Docker Hub and run containers in powershell as you would do in Linux. The following example will show in brief the downloading of the Ubuntu image and running of the container off the image.
The first step is to use the Docker pull command to pull the Ubuntu image from Docker Hub.
The next step is to run the Docker image using the following run command −
docker run –it ubuntu /bin/bash
You will notice that the command is the same as it was in Linux.
This is the GUI equivalent of Docker on Windows. To open this GUI, go to the taskbar and on the Docker icon, right-click and choose to open Kitematic.
It will prompt you to download Kitematic GUI. Once downloaded, just unzip the contents. There will be a file called Kitematic.exe. Double-click this exe file to open the GUI interface.
You will then be requested to log into Docker Hub, enter through the GUI. Just enter the required username and password and then click the Login button.
Once logged in, you will be able to see all the images downloaded on the system on the left-hand side of the interface.
On the right-hand side, you will find all the images available on Docker Hub.
Let’s take an example to understand how to download the Node image from Docker Hub using Kitematic.
Step 1 − Enter the keyword of node in the search criteria.
Step 2 − Click the create button on official Node image. You will then see the image being downloaded.
Once the image has been downloaded, it will then start running the Node container.
Step 3 − If you go to the settings tab, you can drill-down to further settings options, as shown below.
General settings − In this tab, you can name the container, change the path settings, and delete the container.
General settings − In this tab, you can name the container, change the path settings, and delete the container.
Ports − Here you can see the different port mappings. If you want, you can create your own port mappings.
Ports − Here you can see the different port mappings. If you want, you can create your own port mappings.
Volumes − Here you can see the different volume mappings.
Volumes − Here you can see the different volume mappings.
Advanced − It contains the advanced settings for the container.
Advanced − It contains the advanced settings for the container.
|
[
{
"code": null,
"e": 2734,
"s": 2474,
"text": "In the introductory chapters, we have seen the installation of Docker toolbox on Windows. The Docker toolbox is developed so that Docker containers can be run on Windows and MacOS. The site for toolbox on Windows is https://docs.docker.com/docker-for-windows/"
},
{
"code": null,
"e": 2820,
"s": 2734,
"text": "For Windows, you need to have Windows 10 or Windows Server 2016 with Hyper-V enabled."
},
{
"code": null,
"e": 2871,
"s": 2820,
"text": "The toolbox consists of the following components −"
},
{
"code": null,
"e": 2975,
"s": 2871,
"text": "Docker Engine − This is used as the base engine or Docker daemon that is used to run Docker containers."
},
{
"code": null,
"e": 3079,
"s": 2975,
"text": "Docker Engine − This is used as the base engine or Docker daemon that is used to run Docker containers."
},
{
"code": null,
"e": 3133,
"s": 3079,
"text": "Docker Machine − for running Docker machine commands."
},
{
"code": null,
"e": 3187,
"s": 3133,
"text": "Docker Machine − for running Docker machine commands."
},
{
"code": null,
"e": 3239,
"s": 3187,
"text": "Docker Compose for running Docker compose commands."
},
{
"code": null,
"e": 3291,
"s": 3239,
"text": "Docker Compose for running Docker compose commands."
},
{
"code": null,
"e": 3356,
"s": 3291,
"text": "Kinematic − This is the Docker GUI built for Windows and Mac OS."
},
{
"code": null,
"e": 3421,
"s": 3356,
"text": "Kinematic − This is the Docker GUI built for Windows and Mac OS."
},
{
"code": null,
"e": 3439,
"s": 3421,
"text": "Oracle virtualbox"
},
{
"code": null,
"e": 3457,
"s": 3439,
"text": "Oracle virtualbox"
},
{
"code": null,
"e": 3548,
"s": 3457,
"text": "Let’s now discuss the different types of activities that are possible with Docker toolbox."
},
{
"code": null,
"e": 3782,
"s": 3548,
"text": "With Docker toolbox on Windows 10, you can now run Docker commands off powershell. If you open powershell on Windows and type in the command of Docker version, you will get all the required details about the Docker version installed."
},
{
"code": null,
"e": 4007,
"s": 3782,
"text": "You can also now pull Images from Docker Hub and run containers in powershell as you would do in Linux. The following example will show in brief the downloading of the Ubuntu image and running of the container off the image."
},
{
"code": null,
"e": 4098,
"s": 4007,
"text": "The first step is to use the Docker pull command to pull the Ubuntu image from Docker Hub."
},
{
"code": null,
"e": 4173,
"s": 4098,
"text": "The next step is to run the Docker image using the following run command −"
},
{
"code": null,
"e": 4207,
"s": 4173,
"text": "docker run –it ubuntu /bin/bash \n"
},
{
"code": null,
"e": 4272,
"s": 4207,
"text": "You will notice that the command is the same as it was in Linux."
},
{
"code": null,
"e": 4423,
"s": 4272,
"text": "This is the GUI equivalent of Docker on Windows. To open this GUI, go to the taskbar and on the Docker icon, right-click and choose to open Kitematic."
},
{
"code": null,
"e": 4608,
"s": 4423,
"text": "It will prompt you to download Kitematic GUI. Once downloaded, just unzip the contents. There will be a file called Kitematic.exe. Double-click this exe file to open the GUI interface."
},
{
"code": null,
"e": 4761,
"s": 4608,
"text": "You will then be requested to log into Docker Hub, enter through the GUI. Just enter the required username and password and then click the Login button."
},
{
"code": null,
"e": 4881,
"s": 4761,
"text": "Once logged in, you will be able to see all the images downloaded on the system on the left-hand side of the interface."
},
{
"code": null,
"e": 4959,
"s": 4881,
"text": "On the right-hand side, you will find all the images available on Docker Hub."
},
{
"code": null,
"e": 5059,
"s": 4959,
"text": "Let’s take an example to understand how to download the Node image from Docker Hub using Kitematic."
},
{
"code": null,
"e": 5118,
"s": 5059,
"text": "Step 1 − Enter the keyword of node in the search criteria."
},
{
"code": null,
"e": 5221,
"s": 5118,
"text": "Step 2 − Click the create button on official Node image. You will then see the image being downloaded."
},
{
"code": null,
"e": 5304,
"s": 5221,
"text": "Once the image has been downloaded, it will then start running the Node container."
},
{
"code": null,
"e": 5408,
"s": 5304,
"text": "Step 3 − If you go to the settings tab, you can drill-down to further settings options, as shown below."
},
{
"code": null,
"e": 5520,
"s": 5408,
"text": "General settings − In this tab, you can name the container, change the path settings, and delete the container."
},
{
"code": null,
"e": 5632,
"s": 5520,
"text": "General settings − In this tab, you can name the container, change the path settings, and delete the container."
},
{
"code": null,
"e": 5738,
"s": 5632,
"text": "Ports − Here you can see the different port mappings. If you want, you can create your own port mappings."
},
{
"code": null,
"e": 5844,
"s": 5738,
"text": "Ports − Here you can see the different port mappings. If you want, you can create your own port mappings."
},
{
"code": null,
"e": 5902,
"s": 5844,
"text": "Volumes − Here you can see the different volume mappings."
},
{
"code": null,
"e": 5960,
"s": 5902,
"text": "Volumes − Here you can see the different volume mappings."
},
{
"code": null,
"e": 6024,
"s": 5960,
"text": "Advanced − It contains the advanced settings for the container."
}
] |
How to Remove the First Characters of a Specific Column in a Table in SQL?
|
08 Oct, 2021
Here we will see, how to remove the first characters of a specific column in a table in SQL. We can do this task using the String function.
String functions are used to perform an operation on an input string and return an output string. There are various string functions like LEN(for SQL server), SUBSTR, LTRIM, TRIM, etc. To perform the required function we need the SUBSTRING() functions
SUBSTRING():
This function is used to find a sub-string from the string from the given position. It takes three parameters:
String: It is a required parameter. It provides information about the string on which function is applied.
Start: It gives the starting position of the string. It is also the required parameter.
Length: It is an optional parameter. By default, it takes the length of the whole string.
Query:
SELECT SUBSTRING('geeksforgeeks', 1, 5);
Output:
To delete the first characters from the field we will use the following query:
Syntax:
SELECT SUBSTRING(string, 2, length(string));
Here, string denotes the field, 2 denotes the starting position of string i.e second character, and length(string) denotes the length of the string.
Query:
SELECT SUBSTRING('geeksforgeeks', 2, len('geeksforgeeks'));
Output:
For the purpose of the demonstration, we will be creating geeks for geeks table in a database called “geeks“.
Step 1: Creating the Database
Use the below SQL statement to create a database called geeks.
Query:
CREATE DATABASE geeks;
Step 2: Using the Database
Use the below SQL statement to switch the database context to geeks.
Query:
USE geeks;
Step 3: Table definition
We have the following geeks for geeks in our geek’s database.
Query:
CREATE TABLE geeksforgeeks
(FIRSTNAME VARCHAR(20),
LASTNAME VARCHAR(20),
AGE INT,GENDER VARCHAR(20));
Step 4: Insert data into the table
INSERT INTO geeksforgeeks VALUES
('Romy', 'Kumari', 22, 'female'),
('Pushkar', 'Jha', 23, 'male'),
('Meenakshi', 'Jha', 20, 'female'),
('Shalini', 'Jha', 22, 'female'),
('Nikhil', 'Kalra', 23, 'male'),
('Akanksha', 'Gupta', 23, 'female');
Step 5: See the content of the table
Use the below command to see the content of the geeks for geeks table:
Query:
SELECT * FROM geeksforgeeks;
Output:
Step 6: Now to delete the first character from the field we will use the geeks for geeks table. Below is the syntax for the SUBSTRING() function to delete the first character from the field.
Syntax:
SELECT SUBSTRING(column_name,2,length(column_name))
FROM table_name;
To delete the first character from the FIRSTNAME column from the geeks for geeks table. We use the given below query:
Query:
SELECT SUBSTRING(FIRSTNAME,2,len(FIRSTNAME))
FROM geeksforgeeks;
Output:
Now to delete the first character from the LASTNAME column.
Query:
SELECT SUBSTRING(LASTNAME,2,len(LASTNAME))AS
LASTNAME FROM geeksforgeeks;
Output:
Picked
SQL-Query
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
SQL Trigger | Student Database
SQL | Views
Difference between DELETE, DROP and TRUNCATE
Difference between SQL and NoSQL
MySQL | Group_CONCAT() Function
Window functions in SQL
SQL | GROUP BY
Difference between DDL and DML in DBMS
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Oct, 2021"
},
{
"code": null,
"e": 169,
"s": 28,
"text": "Here we will see, how to remove the first characters of a specific column in a table in SQL. We can do this task using the String function. "
},
{
"code": null,
"e": 421,
"s": 169,
"text": "String functions are used to perform an operation on an input string and return an output string. There are various string functions like LEN(for SQL server), SUBSTR, LTRIM, TRIM, etc. To perform the required function we need the SUBSTRING() functions"
},
{
"code": null,
"e": 435,
"s": 421,
"text": "SUBSTRING(): "
},
{
"code": null,
"e": 548,
"s": 435,
"text": "This function is used to find a sub-string from the string from the given position. It takes three parameters: "
},
{
"code": null,
"e": 655,
"s": 548,
"text": "String: It is a required parameter. It provides information about the string on which function is applied."
},
{
"code": null,
"e": 743,
"s": 655,
"text": "Start: It gives the starting position of the string. It is also the required parameter."
},
{
"code": null,
"e": 833,
"s": 743,
"text": "Length: It is an optional parameter. By default, it takes the length of the whole string."
},
{
"code": null,
"e": 840,
"s": 833,
"text": "Query:"
},
{
"code": null,
"e": 881,
"s": 840,
"text": "SELECT SUBSTRING('geeksforgeeks', 1, 5);"
},
{
"code": null,
"e": 889,
"s": 881,
"text": "Output:"
},
{
"code": null,
"e": 968,
"s": 889,
"text": "To delete the first characters from the field we will use the following query:"
},
{
"code": null,
"e": 976,
"s": 968,
"text": "Syntax:"
},
{
"code": null,
"e": 1021,
"s": 976,
"text": "SELECT SUBSTRING(string, 2, length(string));"
},
{
"code": null,
"e": 1171,
"s": 1021,
"text": "Here, string denotes the field, 2 denotes the starting position of string i.e second character, and length(string) denotes the length of the string. "
},
{
"code": null,
"e": 1178,
"s": 1171,
"text": "Query:"
},
{
"code": null,
"e": 1238,
"s": 1178,
"text": "SELECT SUBSTRING('geeksforgeeks', 2, len('geeksforgeeks'));"
},
{
"code": null,
"e": 1246,
"s": 1238,
"text": "Output:"
},
{
"code": null,
"e": 1356,
"s": 1246,
"text": "For the purpose of the demonstration, we will be creating geeks for geeks table in a database called “geeks“."
},
{
"code": null,
"e": 1386,
"s": 1356,
"text": "Step 1: Creating the Database"
},
{
"code": null,
"e": 1449,
"s": 1386,
"text": "Use the below SQL statement to create a database called geeks."
},
{
"code": null,
"e": 1456,
"s": 1449,
"text": "Query:"
},
{
"code": null,
"e": 1479,
"s": 1456,
"text": "CREATE DATABASE geeks;"
},
{
"code": null,
"e": 1506,
"s": 1479,
"text": "Step 2: Using the Database"
},
{
"code": null,
"e": 1575,
"s": 1506,
"text": "Use the below SQL statement to switch the database context to geeks."
},
{
"code": null,
"e": 1582,
"s": 1575,
"text": "Query:"
},
{
"code": null,
"e": 1593,
"s": 1582,
"text": "USE geeks;"
},
{
"code": null,
"e": 1618,
"s": 1593,
"text": "Step 3: Table definition"
},
{
"code": null,
"e": 1681,
"s": 1618,
"text": " We have the following geeks for geeks in our geek’s database."
},
{
"code": null,
"e": 1688,
"s": 1681,
"text": "Query:"
},
{
"code": null,
"e": 1794,
"s": 1688,
"text": " CREATE TABLE geeksforgeeks\n (FIRSTNAME VARCHAR(20),\n LASTNAME VARCHAR(20),\n AGE INT,GENDER VARCHAR(20));"
},
{
"code": null,
"e": 1829,
"s": 1794,
"text": "Step 4: Insert data into the table"
},
{
"code": null,
"e": 2070,
"s": 1829,
"text": "INSERT INTO geeksforgeeks VALUES\n('Romy', 'Kumari', 22, 'female'),\n('Pushkar', 'Jha', 23, 'male'), \n('Meenakshi', 'Jha', 20, 'female'),\n('Shalini', 'Jha', 22, 'female'),\n('Nikhil', 'Kalra', 23, 'male'),\n('Akanksha', 'Gupta', 23, 'female');"
},
{
"code": null,
"e": 2107,
"s": 2070,
"text": "Step 5: See the content of the table"
},
{
"code": null,
"e": 2179,
"s": 2107,
"text": " Use the below command to see the content of the geeks for geeks table:"
},
{
"code": null,
"e": 2186,
"s": 2179,
"text": "Query:"
},
{
"code": null,
"e": 2215,
"s": 2186,
"text": "SELECT * FROM geeksforgeeks;"
},
{
"code": null,
"e": 2223,
"s": 2215,
"text": "Output:"
},
{
"code": null,
"e": 2414,
"s": 2223,
"text": "Step 6: Now to delete the first character from the field we will use the geeks for geeks table. Below is the syntax for the SUBSTRING() function to delete the first character from the field."
},
{
"code": null,
"e": 2422,
"s": 2414,
"text": "Syntax:"
},
{
"code": null,
"e": 2491,
"s": 2422,
"text": "SELECT SUBSTRING(column_name,2,length(column_name))\nFROM table_name;"
},
{
"code": null,
"e": 2609,
"s": 2491,
"text": "To delete the first character from the FIRSTNAME column from the geeks for geeks table. We use the given below query:"
},
{
"code": null,
"e": 2616,
"s": 2609,
"text": "Query:"
},
{
"code": null,
"e": 2681,
"s": 2616,
"text": "SELECT SUBSTRING(FIRSTNAME,2,len(FIRSTNAME))\nFROM geeksforgeeks;"
},
{
"code": null,
"e": 2689,
"s": 2681,
"text": "Output:"
},
{
"code": null,
"e": 2751,
"s": 2691,
"text": "Now to delete the first character from the LASTNAME column."
},
{
"code": null,
"e": 2758,
"s": 2751,
"text": "Query:"
},
{
"code": null,
"e": 2832,
"s": 2758,
"text": "SELECT SUBSTRING(LASTNAME,2,len(LASTNAME))AS\nLASTNAME FROM geeksforgeeks;"
},
{
"code": null,
"e": 2840,
"s": 2832,
"text": "Output:"
},
{
"code": null,
"e": 2847,
"s": 2840,
"text": "Picked"
},
{
"code": null,
"e": 2857,
"s": 2847,
"text": "SQL-Query"
},
{
"code": null,
"e": 2868,
"s": 2857,
"text": "SQL-Server"
},
{
"code": null,
"e": 2872,
"s": 2868,
"text": "SQL"
},
{
"code": null,
"e": 2876,
"s": 2872,
"text": "SQL"
},
{
"code": null,
"e": 2974,
"s": 2876,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2985,
"s": 2974,
"text": "CTE in SQL"
},
{
"code": null,
"e": 3051,
"s": 2985,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 3082,
"s": 3051,
"text": "SQL Trigger | Student Database"
},
{
"code": null,
"e": 3094,
"s": 3082,
"text": "SQL | Views"
},
{
"code": null,
"e": 3139,
"s": 3094,
"text": "Difference between DELETE, DROP and TRUNCATE"
},
{
"code": null,
"e": 3172,
"s": 3139,
"text": "Difference between SQL and NoSQL"
},
{
"code": null,
"e": 3204,
"s": 3172,
"text": "MySQL | Group_CONCAT() Function"
},
{
"code": null,
"e": 3228,
"s": 3204,
"text": "Window functions in SQL"
},
{
"code": null,
"e": 3243,
"s": 3228,
"text": "SQL | GROUP BY"
}
] |
Ulimit, Soft Limits and Hard Limits in Linux
|
26 Nov, 2020
ulimit is admin access required Linux shell command which is used to see, set, or limit the resource usage of the current user. It is used to return the number of open file descriptors for each process. It is also used to set restrictions on the resources used by a process.
Syntax:
To check the ulimit value use the following command:
ulimit -a
Working with ulimit commands:
1. To display maximum users process or for showing maximum user process limit for the logged-in user.
ulimit -u
2. For showing the maximum file size a user can have.
ulimit -f
3. For showing maximum memory size for the current user.
ulimit -m
4. For showing maximum memory size limit.
ulimit -v
What are Soft limits and Hard limits in Linux?
The soft limits are the limits which are allocated for actual processing of application or users while the Hard limits are nothing but an upper bound to the values of soft limits. Hence,
(soft limits <= hard limit)
Working with Hard and Soft limit values:
1. For displaying the Hard limit. Hard limits are a restriction to the maximum value of soft limits
ulimit -Hn
2. For displaying Soft Limit. The soft limits are the limits that are there for processing.
ulimit -Sn
3. To change Soft Limit values:
sysctl -w fs.file-max=<value>
Note: Replace <value> with the value you want to set for the soft limit and also remember size can not exceed the Hard Limit!
4. Displaying current Values for opened files
cat /proc/sys/fs/file-max
Technical Scripter 2020
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
tar command in Linux with examples
Conditional Statements | Shell Script
Tail command in Linux with examples
Docker - COPY Instruction
scp command in Linux with Examples
UDP Server-Client implementation in C
Cat command in Linux with examples
echo command in Linux with Examples
chown command in Linux with Examples
touch command in Linux with Examples
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n26 Nov, 2020"
},
{
"code": null,
"e": 328,
"s": 53,
"text": "ulimit is admin access required Linux shell command which is used to see, set, or limit the resource usage of the current user. It is used to return the number of open file descriptors for each process. It is also used to set restrictions on the resources used by a process."
},
{
"code": null,
"e": 336,
"s": 328,
"text": "Syntax:"
},
{
"code": null,
"e": 389,
"s": 336,
"text": "To check the ulimit value use the following command:"
},
{
"code": null,
"e": 399,
"s": 389,
"text": "ulimit -a"
},
{
"code": null,
"e": 429,
"s": 399,
"text": "Working with ulimit commands:"
},
{
"code": null,
"e": 531,
"s": 429,
"text": "1. To display maximum users process or for showing maximum user process limit for the logged-in user."
},
{
"code": null,
"e": 541,
"s": 531,
"text": "ulimit -u"
},
{
"code": null,
"e": 595,
"s": 541,
"text": "2. For showing the maximum file size a user can have."
},
{
"code": null,
"e": 605,
"s": 595,
"text": "ulimit -f"
},
{
"code": null,
"e": 662,
"s": 605,
"text": "3. For showing maximum memory size for the current user."
},
{
"code": null,
"e": 672,
"s": 662,
"text": "ulimit -m"
},
{
"code": null,
"e": 714,
"s": 672,
"text": "4. For showing maximum memory size limit."
},
{
"code": null,
"e": 724,
"s": 714,
"text": "ulimit -v"
},
{
"code": null,
"e": 772,
"s": 724,
"text": "What are Soft limits and Hard limits in Linux? "
},
{
"code": null,
"e": 961,
"s": 772,
"text": "The soft limits are the limits which are allocated for actual processing of application or users while the Hard limits are nothing but an upper bound to the values of soft limits. Hence, "
},
{
"code": null,
"e": 989,
"s": 961,
"text": "(soft limits <= hard limit)"
},
{
"code": null,
"e": 1030,
"s": 989,
"text": "Working with Hard and Soft limit values:"
},
{
"code": null,
"e": 1130,
"s": 1030,
"text": "1. For displaying the Hard limit. Hard limits are a restriction to the maximum value of soft limits"
},
{
"code": null,
"e": 1141,
"s": 1130,
"text": "ulimit -Hn"
},
{
"code": null,
"e": 1233,
"s": 1141,
"text": "2. For displaying Soft Limit. The soft limits are the limits that are there for processing."
},
{
"code": null,
"e": 1244,
"s": 1233,
"text": "ulimit -Sn"
},
{
"code": null,
"e": 1276,
"s": 1244,
"text": "3. To change Soft Limit values:"
},
{
"code": null,
"e": 1306,
"s": 1276,
"text": "sysctl -w fs.file-max=<value>"
},
{
"code": null,
"e": 1432,
"s": 1306,
"text": "Note: Replace <value> with the value you want to set for the soft limit and also remember size can not exceed the Hard Limit!"
},
{
"code": null,
"e": 1478,
"s": 1432,
"text": "4. Displaying current Values for opened files"
},
{
"code": null,
"e": 1504,
"s": 1478,
"text": "cat /proc/sys/fs/file-max"
},
{
"code": null,
"e": 1528,
"s": 1504,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 1539,
"s": 1528,
"text": "Linux-Unix"
},
{
"code": null,
"e": 1558,
"s": 1539,
"text": "Technical Scripter"
},
{
"code": null,
"e": 1656,
"s": 1558,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1691,
"s": 1656,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 1729,
"s": 1691,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 1765,
"s": 1729,
"text": "Tail command in Linux with examples"
},
{
"code": null,
"e": 1791,
"s": 1765,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 1826,
"s": 1791,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 1864,
"s": 1826,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 1899,
"s": 1864,
"text": "Cat command in Linux with examples"
},
{
"code": null,
"e": 1935,
"s": 1899,
"text": "echo command in Linux with Examples"
},
{
"code": null,
"e": 1972,
"s": 1935,
"text": "chown command in Linux with Examples"
}
] |
Program to implement Singly Linked List in C++ using class
|
03 Jul, 2022
The linked list stores data in sequential storage, like arrays. Though the data are stored sequentially, the memory locations are not contiguous.Unlike an array, the linked list can store data of different data types.The below diagram represents the linked-list structure.
In C++ the linked list can be represented with a class and a Node class separately, which has two members, namely data and a next pointer which points to the next node.
InsertNode: In this article, insertion is done at the end of the list. Follow the steps to insert a node in the linked list.
Let’s say, 4 is to be inserted on the existing linked list, i.e., 1 -> 2 -> 3.The resultant linked list will be 1 -> 2 -> 3 -> 4.
To insert a new node traverse till the end of the list until NULL node is found.
Create a new Node, and link the new node to the last node of the linked list.
DeleteNode: In this article, deletion is done using the index of the node. Follow the steps to delete a node:
If the node to be deleted is the head node, store the head in temp variable. Then update head as head->next. Delete temp.
If the index of the node to be deleted is greater than the length of the list then return from the function.
Traverse till the node to be deleted. Delete the node, and link the previous node to the next node of the deleted node.
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include <iostream>using namespace std; // Node class to represent// a node of the linked list.class Node {public: int data; Node* next; // Default constructor Node() { data = 0; next = NULL; } // Parameterised Constructor Node(int data) { this->data = data; this->next = NULL; }}; // Linked list class to// implement a linked list.class Linkedlist { Node* head; public: // Default constructor Linkedlist() { head = NULL; } // Function to insert a // node at the end of the // linked list. void insertNode(int); // Function to print the // linked list. void printList(); // Function to delete the // node at given position void deleteNode(int);}; // Function to delete the// node at given positionvoid Linkedlist::deleteNode(int nodeOffset){ Node *temp1 = head, *temp2 = NULL; int ListLen = 0; if (head == NULL) { cout << "List empty." << endl; return; } // Find length of the linked-list. while (temp1 != NULL) { temp1 = temp1->next; ListLen++; } // Check if the position to be // deleted is less than the length // of the linked list. if (ListLen < nodeOffset) { cout << "Index out of range" << endl; return; } // Declare temp1 temp1 = head; // Deleting the head. if (nodeOffset == 1) { // Update head head = head->next; delete temp1; return; } // Traverse the list to // find the node to be deleted. while (nodeOffset-- > 1) { // Update temp2 temp2 = temp1; // Update temp1 temp1 = temp1->next; } // Change the next pointer // of the previous node. temp2->next = temp1->next; // Delete the node delete temp1;} // Function to insert a new node.void Linkedlist::insertNode(int data){ // Create the new Node. Node* newNode = new Node(data); // Assign to head if (head == NULL) { head = newNode; return; } // Traverse till end of list Node* temp = head; while (temp->next != NULL) { // Update temp temp = temp->next; } // Insert at the last. temp->next = newNode;} // Function to print the// nodes of the linked list.void Linkedlist::printList(){ Node* temp = head; // Check for empty list. if (head == NULL) { cout << "List empty" << endl; return; } // Traverse the list. while (temp != NULL) { cout << temp->data << " "; temp = temp->next; }} // Driver Codeint main(){ Linkedlist list; // Inserting nodes list.insertNode(1); list.insertNode(2); list.insertNode(3); list.insertNode(4); cout << "Elements of the list are: "; // Print the list list.printList(); cout << endl; // Delete node at position 2. list.deleteNode(2); cout << "Elements of the list are: "; list.printList(); cout << endl; return 0;}
Elements of the list are: 1 2 3 4
Elements of the list are: 1 3 4
Time Complexity: O(N)Auxiliary Space: O(N)
C++ Programs
Data Structures
Linked List
Data Structures
Linked List
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Passing a function as a parameter in C++
Const keyword in C++
cout in C++
Different ways to print elements of vector
Dynamic _Cast in C++
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": 52,
"s": 24,
"text": "\n03 Jul, 2022"
},
{
"code": null,
"e": 326,
"s": 52,
"text": "The linked list stores data in sequential storage, like arrays. Though the data are stored sequentially, the memory locations are not contiguous.Unlike an array, the linked list can store data of different data types.The below diagram represents the linked-list structure. "
},
{
"code": null,
"e": 496,
"s": 326,
"text": "In C++ the linked list can be represented with a class and a Node class separately, which has two members, namely data and a next pointer which points to the next node. "
},
{
"code": null,
"e": 621,
"s": 496,
"text": "InsertNode: In this article, insertion is done at the end of the list. Follow the steps to insert a node in the linked list."
},
{
"code": null,
"e": 751,
"s": 621,
"text": "Let’s say, 4 is to be inserted on the existing linked list, i.e., 1 -> 2 -> 3.The resultant linked list will be 1 -> 2 -> 3 -> 4."
},
{
"code": null,
"e": 832,
"s": 751,
"text": "To insert a new node traverse till the end of the list until NULL node is found."
},
{
"code": null,
"e": 910,
"s": 832,
"text": "Create a new Node, and link the new node to the last node of the linked list."
},
{
"code": null,
"e": 1021,
"s": 910,
"text": "DeleteNode: In this article, deletion is done using the index of the node. Follow the steps to delete a node: "
},
{
"code": null,
"e": 1143,
"s": 1021,
"text": "If the node to be deleted is the head node, store the head in temp variable. Then update head as head->next. Delete temp."
},
{
"code": null,
"e": 1252,
"s": 1143,
"text": "If the index of the node to be deleted is greater than the length of the list then return from the function."
},
{
"code": null,
"e": 1372,
"s": 1252,
"text": "Traverse till the node to be deleted. Delete the node, and link the previous node to the next node of the deleted node."
},
{
"code": null,
"e": 1423,
"s": 1372,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1427,
"s": 1423,
"text": "C++"
},
{
"code": "// C++ program for the above approach#include <iostream>using namespace std; // Node class to represent// a node of the linked list.class Node {public: int data; Node* next; // Default constructor Node() { data = 0; next = NULL; } // Parameterised Constructor Node(int data) { this->data = data; this->next = NULL; }}; // Linked list class to// implement a linked list.class Linkedlist { Node* head; public: // Default constructor Linkedlist() { head = NULL; } // Function to insert a // node at the end of the // linked list. void insertNode(int); // Function to print the // linked list. void printList(); // Function to delete the // node at given position void deleteNode(int);}; // Function to delete the// node at given positionvoid Linkedlist::deleteNode(int nodeOffset){ Node *temp1 = head, *temp2 = NULL; int ListLen = 0; if (head == NULL) { cout << \"List empty.\" << endl; return; } // Find length of the linked-list. while (temp1 != NULL) { temp1 = temp1->next; ListLen++; } // Check if the position to be // deleted is less than the length // of the linked list. if (ListLen < nodeOffset) { cout << \"Index out of range\" << endl; return; } // Declare temp1 temp1 = head; // Deleting the head. if (nodeOffset == 1) { // Update head head = head->next; delete temp1; return; } // Traverse the list to // find the node to be deleted. while (nodeOffset-- > 1) { // Update temp2 temp2 = temp1; // Update temp1 temp1 = temp1->next; } // Change the next pointer // of the previous node. temp2->next = temp1->next; // Delete the node delete temp1;} // Function to insert a new node.void Linkedlist::insertNode(int data){ // Create the new Node. Node* newNode = new Node(data); // Assign to head if (head == NULL) { head = newNode; return; } // Traverse till end of list Node* temp = head; while (temp->next != NULL) { // Update temp temp = temp->next; } // Insert at the last. temp->next = newNode;} // Function to print the// nodes of the linked list.void Linkedlist::printList(){ Node* temp = head; // Check for empty list. if (head == NULL) { cout << \"List empty\" << endl; return; } // Traverse the list. while (temp != NULL) { cout << temp->data << \" \"; temp = temp->next; }} // Driver Codeint main(){ Linkedlist list; // Inserting nodes list.insertNode(1); list.insertNode(2); list.insertNode(3); list.insertNode(4); cout << \"Elements of the list are: \"; // Print the list list.printList(); cout << endl; // Delete node at position 2. list.deleteNode(2); cout << \"Elements of the list are: \"; list.printList(); cout << endl; return 0;}",
"e": 4473,
"s": 1427,
"text": null
},
{
"code": null,
"e": 4542,
"s": 4473,
"text": "Elements of the list are: 1 2 3 4 \nElements of the list are: 1 3 4 \n"
},
{
"code": null,
"e": 4585,
"s": 4542,
"text": "Time Complexity: O(N)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 4598,
"s": 4585,
"text": "C++ Programs"
},
{
"code": null,
"e": 4614,
"s": 4598,
"text": "Data Structures"
},
{
"code": null,
"e": 4626,
"s": 4614,
"text": "Linked List"
},
{
"code": null,
"e": 4642,
"s": 4626,
"text": "Data Structures"
},
{
"code": null,
"e": 4654,
"s": 4642,
"text": "Linked List"
},
{
"code": null,
"e": 4752,
"s": 4654,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4793,
"s": 4752,
"text": "Passing a function as a parameter in C++"
},
{
"code": null,
"e": 4814,
"s": 4793,
"text": "Const keyword in C++"
},
{
"code": null,
"e": 4826,
"s": 4814,
"text": "cout in C++"
},
{
"code": null,
"e": 4869,
"s": 4826,
"text": "Different ways to print elements of vector"
},
{
"code": null,
"e": 4890,
"s": 4869,
"text": "Dynamic _Cast in C++"
},
{
"code": null,
"e": 4915,
"s": 4890,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 4964,
"s": 4915,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 5008,
"s": 4964,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 5040,
"s": 5008,
"text": "Introduction to Data Structures"
}
] |
Difference between Tuple Relational Calculus (TRC) and Domain Relational Calculus (DRC)
|
07 Jun, 2022
1. Tuple Relational Calculus (TRC) : A tuple relational calculus is a non-procedural query language that specifies to select of the tuples in a relation. It can select the tuples with a range of values or tuples for certain attribute values etc. The resulting relation can have one or more tuples.
Notation :
{T | P (T)} or {T | Condition (T)}
where T is the resulting tuples and P(T) is a condition used to fetch T.
Example :
{T | EMPLOYEE (T) AND T.DEPT_ID = 10}
This selects all the tuples of employee names who work for Department 10.
2. Domain Relational Calculus (DRC) : A domain relational calculus uses the list of attributes to be selected from the relation based on the condition. It is the same as TRC but differs by selecting the attributes rather than selecting whole tuples.
Notation :
{ a1, a2, a3, ..., an | P (a1, a2, a3, ..., an) }
Where a1, a2, a3, ... an are attributes of the relation and P is the condition.
Example :
{ | < EMPLOYEE > DEPT_ID = 10 }
select EMP_ID and EMP_NAME of employees who work for department 10.
itskawal2000
annieahujaweb2020
Picked
DBMS
Difference Between
GATE CS
Write From Home
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of Functional dependencies in DBMS
MySQL | Regular expressions (Regexp)
What is Temporary Table in SQL?
Difference between OLAP and OLTP in DBMS
Difference between Where and Having Clause in SQL
Class method vs Static method in Python
Difference between BFS and DFS
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Differences between JDK, JRE and JVM
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n07 Jun, 2022"
},
{
"code": null,
"e": 352,
"s": 53,
"text": "1. Tuple Relational Calculus (TRC) : A tuple relational calculus is a non-procedural query language that specifies to select of the tuples in a relation. It can select the tuples with a range of values or tuples for certain attribute values etc. The resulting relation can have one or more tuples. "
},
{
"code": null,
"e": 402,
"s": 352,
"text": "Notation :\n{T | P (T)} or {T | Condition (T)} "
},
{
"code": null,
"e": 476,
"s": 402,
"text": "where T is the resulting tuples and P(T) is a condition used to fetch T. "
},
{
"code": null,
"e": 487,
"s": 476,
"text": "Example : "
},
{
"code": null,
"e": 526,
"s": 487,
"text": "{T | EMPLOYEE (T) AND T.DEPT_ID = 10} "
},
{
"code": null,
"e": 601,
"s": 526,
"text": "This selects all the tuples of employee names who work for Department 10. "
},
{
"code": null,
"e": 853,
"s": 601,
"text": "2. Domain Relational Calculus (DRC) : A domain relational calculus uses the list of attributes to be selected from the relation based on the condition. It is the same as TRC but differs by selecting the attributes rather than selecting whole tuples. "
},
{
"code": null,
"e": 915,
"s": 853,
"text": "Notation :\n{ a1, a2, a3, ..., an | P (a1, a2, a3, ..., an) } "
},
{
"code": null,
"e": 996,
"s": 915,
"text": "Where a1, a2, a3, ... an are attributes of the relation and P is the condition. "
},
{
"code": null,
"e": 1007,
"s": 996,
"text": "Example : "
},
{
"code": null,
"e": 1041,
"s": 1007,
"text": "{ | < EMPLOYEE > DEPT_ID = 10 } "
},
{
"code": null,
"e": 1110,
"s": 1041,
"text": "select EMP_ID and EMP_NAME of employees who work for department 10. "
},
{
"code": null,
"e": 1123,
"s": 1110,
"text": "itskawal2000"
},
{
"code": null,
"e": 1141,
"s": 1123,
"text": "annieahujaweb2020"
},
{
"code": null,
"e": 1148,
"s": 1141,
"text": "Picked"
},
{
"code": null,
"e": 1153,
"s": 1148,
"text": "DBMS"
},
{
"code": null,
"e": 1172,
"s": 1153,
"text": "Difference Between"
},
{
"code": null,
"e": 1180,
"s": 1172,
"text": "GATE CS"
},
{
"code": null,
"e": 1196,
"s": 1180,
"text": "Write From Home"
},
{
"code": null,
"e": 1201,
"s": 1196,
"text": "DBMS"
},
{
"code": null,
"e": 1299,
"s": 1201,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1340,
"s": 1299,
"text": "Types of Functional dependencies in DBMS"
},
{
"code": null,
"e": 1377,
"s": 1340,
"text": "MySQL | Regular expressions (Regexp)"
},
{
"code": null,
"e": 1409,
"s": 1377,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 1450,
"s": 1409,
"text": "Difference between OLAP and OLTP in DBMS"
},
{
"code": null,
"e": 1500,
"s": 1450,
"text": "Difference between Where and Having Clause in SQL"
},
{
"code": null,
"e": 1540,
"s": 1500,
"text": "Class method vs Static method in Python"
},
{
"code": null,
"e": 1571,
"s": 1540,
"text": "Difference between BFS and DFS"
},
{
"code": null,
"e": 1632,
"s": 1571,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1700,
"s": 1632,
"text": "Difference Between Method Overloading and Method Overriding in Java"
}
] |
Introduction to NSE Tools Module in Python
|
03 Aug, 2021
NSE National Stock Exchange of India Limited is the leading stock exchange of India, located in Mumbai, Maharashtra. NSE was established in 1992 as the first dematerialized electronic exchange in the country.nsetools is a library for collecting real time data from National Stock Exchange of India. It can be used in various types of projects which requires fetching live quotes for a given stock or index or building large data sets for further data analytics. We can also build command line interface applications which can provide us live market details at a blazing fast speeds, much faster than any browser. The accuracy of data is only as correct as provided on http://www.nseindia.comIn order to install nse tools we have to use the command given below
pip install nsetools
Creating a Nse object
Python3
# importing nse from nse toolsfrom nsetools import Nse # creating a Nse objectnse = Nse() # printing Nse objectprint(nse)
Output :
Driver Class for National Stock Exchange (NSE)
Getting Information
Python3
# importing nse from nse toolsfrom nsetools import Nse # creating a Nse objectnse = Nse() # getting quote of the sbinquote = nse.get_quote('sbin') # printing company nameprint(quote['companyName']) # printing buy priceprint("Buy Price : " + str(quote['buyPrice1']))
Output :
State Bank of India
Buy Price : 191.45
Python3
# importing nse from nse toolsfrom nsetools import Nse # creating a Nse objectnse = Nse() # getting quote of the sbinquote = nse.get_quote('sbin') # printing company nameprint(quote['companyName']) # printing average priceprint("Average Price : " + str(quote['averagePrice']))
Output :
State Bank of India
Average Price : 193.9
kapoorsagar226
Python NseTools-library
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Convert integer to string in Python
Python OOPs Concepts
Python | os.path.join() method
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n03 Aug, 2021"
},
{
"code": null,
"e": 815,
"s": 53,
"text": "NSE National Stock Exchange of India Limited is the leading stock exchange of India, located in Mumbai, Maharashtra. NSE was established in 1992 as the first dematerialized electronic exchange in the country.nsetools is a library for collecting real time data from National Stock Exchange of India. It can be used in various types of projects which requires fetching live quotes for a given stock or index or building large data sets for further data analytics. We can also build command line interface applications which can provide us live market details at a blazing fast speeds, much faster than any browser. The accuracy of data is only as correct as provided on http://www.nseindia.comIn order to install nse tools we have to use the command given below "
},
{
"code": null,
"e": 836,
"s": 815,
"text": "pip install nsetools"
},
{
"code": null,
"e": 860,
"s": 836,
"text": "Creating a Nse object "
},
{
"code": null,
"e": 868,
"s": 860,
"text": "Python3"
},
{
"code": "# importing nse from nse toolsfrom nsetools import Nse # creating a Nse objectnse = Nse() # printing Nse objectprint(nse)",
"e": 990,
"s": 868,
"text": null
},
{
"code": null,
"e": 1001,
"s": 990,
"text": "Output : "
},
{
"code": null,
"e": 1048,
"s": 1001,
"text": "Driver Class for National Stock Exchange (NSE)"
},
{
"code": null,
"e": 1070,
"s": 1048,
"text": "Getting Information "
},
{
"code": null,
"e": 1078,
"s": 1070,
"text": "Python3"
},
{
"code": "# importing nse from nse toolsfrom nsetools import Nse # creating a Nse objectnse = Nse() # getting quote of the sbinquote = nse.get_quote('sbin') # printing company nameprint(quote['companyName']) # printing buy priceprint(\"Buy Price : \" + str(quote['buyPrice1']))",
"e": 1344,
"s": 1078,
"text": null
},
{
"code": null,
"e": 1355,
"s": 1344,
"text": "Output : "
},
{
"code": null,
"e": 1394,
"s": 1355,
"text": "State Bank of India\nBuy Price : 191.45"
},
{
"code": null,
"e": 1404,
"s": 1396,
"text": "Python3"
},
{
"code": "# importing nse from nse toolsfrom nsetools import Nse # creating a Nse objectnse = Nse() # getting quote of the sbinquote = nse.get_quote('sbin') # printing company nameprint(quote['companyName']) # printing average priceprint(\"Average Price : \" + str(quote['averagePrice']))",
"e": 1681,
"s": 1404,
"text": null
},
{
"code": null,
"e": 1692,
"s": 1681,
"text": "Output : "
},
{
"code": null,
"e": 1734,
"s": 1692,
"text": "State Bank of India\nAverage Price : 193.9"
},
{
"code": null,
"e": 1751,
"s": 1736,
"text": "kapoorsagar226"
},
{
"code": null,
"e": 1775,
"s": 1751,
"text": "Python NseTools-library"
},
{
"code": null,
"e": 1782,
"s": 1775,
"text": "Python"
},
{
"code": null,
"e": 1880,
"s": 1782,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1898,
"s": 1880,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1940,
"s": 1898,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1962,
"s": 1940,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1988,
"s": 1962,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2020,
"s": 1988,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2049,
"s": 2020,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2076,
"s": 2049,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2112,
"s": 2076,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 2133,
"s": 2112,
"text": "Python OOPs Concepts"
}
] |
Square root of an integer
|
23 Jun, 2022
Given an integer x, find it’s square root. If x is not a perfect square, then return floor(√x).
Examples :
Input: x = 4
Output: 2
Explanation: The square root of 4 is 2.
Input: x = 11
Output: 3
Explanation: The square root of 11 lies in between
3 and 4 so floor of the square root is 3.
There can be many ways to solve this problem. For example, the Babylonian Method is one way.Simple Approach: To find the floor of the square root, try with all-natural numbers starting from 1. Continue incrementing the number until the square of that number is greater than the given number.
Algorithm: Create a variable (counter) i and take care of some base cases, i.e when the given number is 0 or 1.Run a loop until i*i <= n , where n is the given number. Increment i by 1.The floor of the square root of the number is i – 1
Create a variable (counter) i and take care of some base cases, i.e when the given number is 0 or 1.Run a loop until i*i <= n , where n is the given number. Increment i by 1.The floor of the square root of the number is i – 1
Create a variable (counter) i and take care of some base cases, i.e when the given number is 0 or 1.
Run a loop until i*i <= n , where n is the given number. Increment i by 1.
The floor of the square root of the number is i – 1
Implementation:
C++
C
Java
Python3
C#
PHP
Javascript
// A C++ program to find floor(sqrt(x)#include<bits/stdc++.h>using namespace std; // Returns floor of square root of xint floorSqrt(int x){ // Base cases if (x == 0 || x == 1) return x; // Starting from 1, try all numbers until // i*i is greater than or equal to x. int i = 1, result = 1; while (result <= x) { i++; result = i * i; } return i - 1;} // Driver programint main(){ int x = 11; cout << floorSqrt(x) << endl; return 0;}
#include <stdio.h> // Returns floor of square root of xint floorSqrt(int x){ // Base cases if (x == 0 || x == 1) return x; // Starting from 1, try all numbers until // i*i is greater than or equal to x. int i = 1, result = 1; while (result <= x) { i++; result = i * i; } return i - 1;} // Driver programint main(){ int x = 11; printf("%d\n",floorSqrt(x)); return 0;}//code is contributed by lalith kumar.g
// A Java program to find floor(sqrt(x)) class GFG { // Returns floor of square root of x static int floorSqrt(int x) { // Base cases if (x == 0 || x == 1) return x; // Starting from 1, try all numbers until // i*i is greater than or equal to x. int i = 1, result = 1; while (result <= x) { i++; result = i * i; } return i - 1; } // Driver program public static void main(String[] args) { int x = 11; System.out.print(floorSqrt(x)); }} // This code is contributed by Smitha Dinesh Semwal.
# Python3 program to find floor(sqrt(x) # Returns floor of square root of xdef floorSqrt(x): # Base cases if (x == 0 or x == 1): return x # Starting from 1, try all numbers until # i*i is greater than or equal to x. i = 1; result = 1 while (result <= x): i += 1 result = i * i return i - 1 # Driver Codex = 11print(floorSqrt(x)) # This code is contributed by Smitha Dinesh Semwal.
// A C# program to// find floor(sqrt(x))using System; class GFG{ // Returns floor of // square root of x static int floorSqrt(int x) { // Base cases if (x == 0 || x == 1) return x; // Starting from 1, try all // numbers until i*i is // greater than or equal to x. int i = 1, result = 1; while (result <= x) { i++; result = i * i; } return i - 1; } // Driver Code static public void Main () { int x = 11; Console.WriteLine(floorSqrt(x)); }} // This code is contributed by ajit
<?php// A PHP program to find floor(sqrt(x) // Returns floor of square root of xfunction floorSqrt($x){ // Base cases if ($x == 0 || $x == 1) return $x; // Starting from 1, try all // numbers until i*i is // greater than or equal to x. $i = 1; $result = 1; while ($result <= $x) { $i++; $result = $i * $i; } return $i - 1;} // Driver Code$x = 11;echo floorSqrt($x), "\n"; // This code is contributed by ajit?>
<script> // A Javascript program to find floor(sqrt(x) // Returns floor of square root of xfunction floorSqrt(x){ // Base cases if (x == 0 || x == 1) return x; // Starting from 1, try all // numbers until i*i is // greater than or equal to x. let i = 1; let result = 1; while (result <= x) { i++; result = i * i; } return i - 1;} // Driver Codelet x = 11;document.write(floorSqrt(x)); // This code is contributed by mohan </script>
Output :
3
Complexity Analysis: Time Complexity: O(√ n). Only one traversal of the solution is needed, so the time complexity is O(√ n).Space Complexity: O(1). Constant extra space is needed.
Time Complexity: O(√ n). Only one traversal of the solution is needed, so the time complexity is O(√ n).
Space Complexity: O(1). Constant extra space is needed.
Thanks Fattepur Mahesh for suggesting this solution. Better Approach: The idea is to find the largest integer i whose square is less than or equal to the given number. The idea is to use Binary Search to solve the problem. The values of i * i is monotonically increasing, so the problem can be solved using binary search.
Algorithm: Take care of some base cases, i.e when the given number is 0 or 1.Create some variables, lowerbound l = 0, upperbound r = n, where n is the given number, mid and ans to store the answer.Run a loop until l <= r , the search space vanishesCheck if the square of mid (mid = (l + r)/2 ) is less than or equal to n, If yes then search for a larger value in second half of search space, i.e l = mid + 1, update ans = midElse if the square of mid is more than n then search for a smaller value in first half of search space, i.e r = mid – 1Print the value of answer ( ans)
Take care of some base cases, i.e when the given number is 0 or 1.Create some variables, lowerbound l = 0, upperbound r = n, where n is the given number, mid and ans to store the answer.Run a loop until l <= r , the search space vanishesCheck if the square of mid (mid = (l + r)/2 ) is less than or equal to n, If yes then search for a larger value in second half of search space, i.e l = mid + 1, update ans = midElse if the square of mid is more than n then search for a smaller value in first half of search space, i.e r = mid – 1Print the value of answer ( ans)
Take care of some base cases, i.e when the given number is 0 or 1.
Create some variables, lowerbound l = 0, upperbound r = n, where n is the given number, mid and ans to store the answer.
Run a loop until l <= r , the search space vanishes
Check if the square of mid (mid = (l + r)/2 ) is less than or equal to n, If yes then search for a larger value in second half of search space, i.e l = mid + 1, update ans = mid
Else if the square of mid is more than n then search for a smaller value in first half of search space, i.e r = mid – 1
Print the value of answer ( ans)
Implementation:
C++
C
Java
Python3
C#
PHP
Javascript
#include <iostream> using namespace std;int floorSqrt(int x){ // Base cases if (x == 0 || x == 1) return x; // Do Binary Search for floor(sqrt(x)) int start = 1, end = x/2, ans; while (start <= end) { int mid = (start + end) / 2; // If x is a perfect square int sqr = mid * mid; if (sqr == x) return mid; // Since we need floor, we update answer when // mid*mid is smaller than x, and move closer to // sqrt(x) /* if(mid*mid<=x) { start = mid+1; ans = mid; } Here basically if we multiply mid with itself so there will be integer overflow which will throw tle for larger input so to overcome this situation we can use long or we can just divide the number by mid which is same as checking mid*mid < x */ if (sqr <= x) { start = mid + 1; ans = mid; } else // If mid*mid is greater than x end = mid - 1; } return ans;} // Driver programint main(){ int x = 20221; cout << floorSqrt(x) << endl; return 0;}
#include <stdio.h>#include <math.h> int floorSqrt(int x) { // Base Cases if (x == 0 || x == 1) return x; // Do Binary Search for floor(sqrt(x)) long start = 1, end = x, ans=0; while (start <= end) { int mid = (start + end) / 2; // If x is a perfect square if (mid*mid == x) return (int)mid; // Since we need floor, we update answer when mid*mid is // smaller than x, and move closer to sqrt(x) if (mid*mid < x) { start = mid + 1; ans = mid; } else // If mid*mid is greater than x end = mid-1; } return (int)ans; } // Driver Method int main() { int x = 11; printf("%d\n",floorSqrt(x)); } //Contributed by lalith kumar.g
// A Java program to find floor(sqrt(x)public class Test{ public static int floorSqrt(int x) { // Base Cases if (x == 0 || x == 1) return x; // Do Binary Search for floor(sqrt(x)) long start = 1, end = x, ans=0; while (start <= end) { long mid = (start + end) / 2; // If x is a perfect square if (mid*mid == x) return (int)mid; // Since we need floor, we update answer when mid*mid is // smaller than x, and move closer to sqrt(x) if (mid*mid < x) { start = mid + 1; ans = mid; } else // If mid*mid is greater than x end = mid-1; } return (int)ans; } // Driver Method public static void main(String args[]) { int x = 11; System.out.println(floorSqrt(x)); }}// Contributed by InnerPeace
# Python 3 program to find floor(sqrt(x) # Returns floor of square root of x def floorSqrt(x) : # Base cases if (x == 0 or x == 1) : return x # Do Binary Search for floor(sqrt(x)) start = 1 end = x while (start <= end) : mid = (start + end) // 2 # If x is a perfect square if (mid*mid == x) : return mid # Since we need floor, we update # answer when mid*mid is smaller # than x, and move closer to sqrt(x) if (mid * mid < x) : start = mid + 1 ans = mid else : # If mid*mid is greater than x end = mid-1 return ans # driver code x = 11print(floorSqrt(x)) # This code is contributed by Nikita Tiwari.
// A C# program to// find floor(sqrt(x)using System; class GFG{ public static int floorSqrt(int x) { // Base Cases if (x == 0 || x == 1) return x; // Do Binary Search // for floor(sqrt(x)) int start = 1, end = x, ans = 0; while (start <= end) { int mid = (start + end) / 2; // If x is a // perfect square if (mid * mid == x) return mid; // Since we need floor, we // update answer when mid * // mid is smaller than x, // and move closer to sqrt(x) if (mid * mid < x) { start = mid + 1; ans = mid; } // If mid*mid is // greater than x else end = mid-1; } return ans; } // Driver Code static public void Main () { int x = 11; Console.WriteLine(floorSqrt(x)); }} // This code is Contributed by m_kit
<?php// A PHP program to find floor(sqrt(x) // Returns floor of// square root of x function floorSqrt($x){ // Base cases if ($x == 0 || $x == 1) return $x; // Do Binary Search // for floor(sqrt(x)) $start = 1; $end = $x; $ans; while ($start <= $end) { $mid = ($start + $end) / 2; // If x is a perfect square if ($mid * $mid == $x) return $mid; // Since we need floor, we update // answer when mid*mid is smaller // than x, and move closer to sqrt(x) if ($mid * $mid < $x) { $start = $mid + 1; $ans = $mid; } // If mid*mid is // greater than x else $end = $mid-1; } return $ans;} // Driver Code$x = 11;echo floorSqrt($x), "\n"; // This code is contributed by ajit?>
<script> // A Javascript program to find floor(sqrt(x) // Returns floor of// square root of x function floorSqrt(x){ // Base cases if (x == 0 || x == 1) return x; // Do Binary Search // for floor(sqrt(x)) let start = 1; let end = x; let ans; while (start <= end) { let mid = (start + end) / 2; // If x is a perfect square if (mid * mid == x) return mid; // Since we need floor, we update // answer when mid*mid is smaller // than x, and move closer to sqrt(x) if (mid * mid < x) { start = mid + 1; ans = mid; } // If mid*mid is // greater than x else end = mid-1; } return ans;} // Driver Codelet x = 11;document.write(floorSqrt(x) + "<br>"); // This code is contributed by _saurabh_jaiswal</script>
Output :
142
Complexity Analysis: Time complexity: O(log n). The time complexity of the binary search is O(log n).Space Complexity: O(1). Constant extra space is needed.
Time complexity: O(log n). The time complexity of the binary search is O(log n).
Space Complexity: O(1). Constant extra space is needed.
Thanks to Gaurav Ahirwar for suggesting above method.Note: The Binary Search can be further optimized to start with ‘start’ = 0 and ‘end’ = x/2. The floor of the square root of x cannot be more than x/2 when x > 1.Thanks to visit for suggesting the above optimization.
Better Approach: The logic is simple as we can observe that for a perfect square number it’s square root represent the total no of the perfect square from 1 to x.
for ex:- sqrt(1)=1, sqrt(4)=2, sqrt(9)=3 ........ so on.
Algorithm:
1. find the square root of x and store in a variable sqrt.
2. Use the floor value of sqrt and store in variable result, because for non-perfect square number. it’s floor value gives the result.
3. return the result.
Implementation:
C++
C
Java
Python3
C#
Javascript
#include <bits/stdc++.h>using namespace std;int countSquares(int x){ int sqr = sqrt(x); int result = (int)(sqr); return result;}int main(){ int x = 9; cout << (countSquares(x)); return 0;} // This code is contributed by Rajput-Ji
#include <stdio.h>#include <math.h> static int countSquares(int x) { int sqr = (int) sqrt(x); int result = (int) (sqr); return result; } int main() { int x = 9; printf("%d\n",countSquares(x)); }// This code is contributed by lalith kumar.g
import java.util.*; class GFG { static int countSquares(int x) { int sqr = (int) Math.sqrt(x); int result = (int) (sqr); return result; } public static void main(String[] args) { int x = 9; System.out.print(countSquares(x)); }} // This code is contributed by Rajput-Ji
def countSquares(x): sqrt = x**0.5 result = int(sqrt) return resultx = 9print(countSquares(x))
using System;public class GFG { static int countSquares(int x) { int sqr = (int) Math.Sqrt(x); int result = (int) (sqr); return result; } public static void Main(String[] args) { int x = 9; Console.Write(countSquares(x)); }} // This code is contributed by Rajput-Ji
<script> function countSquares(x) { var sqr = parseInt( Math.sqrt(x)); var result = parseInt(sqr); return result; } var x = 9; document.write(countSquares(x)); // This code is contributed by Rajput-Ji</script>
Output:
3
Method: Finding square root of an integer by using sqrt() function of math module.
Python3
# Python3 program to find (sqrt(x))from math import*n=4# using the sqrt functon of math# module finding the square root integerprint(round(sqrt(n))) # This code is contributed by gangarajula laxmi
2
Complexity AnalysisTime complexity:- O(log n)Auxiliary Space :- O(1)
Time complexity:- O(log n)
Auxiliary Space :- O(1)
jit_t
FarhanSheik
yhgupta
andrew1234
pulamolusaimohan
swamipatil158
_saurabh_jaiswal
amit aggrawal
surajrawat307
arorakashish0911
saurabh1990aror
ibrezm1
aakashpanda2000
Rajput-Ji
movshov
nitish705702
lalithkumarg20
dsoumi125
laxmigangarajula03
Accolite
Amazon
Binary Search
Microsoft
Ola Cabs
Snapdeal
Divide and Conquer
Mathematical
Accolite
Amazon
Microsoft
Snapdeal
Ola Cabs
Mathematical
Divide and Conquer
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Find a peak element
Median of two sorted arrays of same size
Allocate minimum number of pages
Quick Sort vs Merge Sort
Closest Pair of Points using Divide and Conquer algorithm
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": "\n23 Jun, 2022"
},
{
"code": null,
"e": 148,
"s": 52,
"text": "Given an integer x, find it’s square root. If x is not a perfect square, then return floor(√x)."
},
{
"code": null,
"e": 160,
"s": 148,
"text": "Examples : "
},
{
"code": null,
"e": 343,
"s": 160,
"text": "Input: x = 4\nOutput: 2\nExplanation: The square root of 4 is 2.\n\nInput: x = 11\nOutput: 3\nExplanation: The square root of 11 lies in between\n3 and 4 so floor of the square root is 3."
},
{
"code": null,
"e": 635,
"s": 343,
"text": "There can be many ways to solve this problem. For example, the Babylonian Method is one way.Simple Approach: To find the floor of the square root, try with all-natural numbers starting from 1. Continue incrementing the number until the square of that number is greater than the given number."
},
{
"code": null,
"e": 872,
"s": 635,
"text": "Algorithm: Create a variable (counter) i and take care of some base cases, i.e when the given number is 0 or 1.Run a loop until i*i <= n , where n is the given number. Increment i by 1.The floor of the square root of the number is i – 1"
},
{
"code": null,
"e": 1098,
"s": 872,
"text": "Create a variable (counter) i and take care of some base cases, i.e when the given number is 0 or 1.Run a loop until i*i <= n , where n is the given number. Increment i by 1.The floor of the square root of the number is i – 1"
},
{
"code": null,
"e": 1199,
"s": 1098,
"text": "Create a variable (counter) i and take care of some base cases, i.e when the given number is 0 or 1."
},
{
"code": null,
"e": 1274,
"s": 1199,
"text": "Run a loop until i*i <= n , where n is the given number. Increment i by 1."
},
{
"code": null,
"e": 1326,
"s": 1274,
"text": "The floor of the square root of the number is i – 1"
},
{
"code": null,
"e": 1342,
"s": 1326,
"text": "Implementation:"
},
{
"code": null,
"e": 1346,
"s": 1342,
"text": "C++"
},
{
"code": null,
"e": 1348,
"s": 1346,
"text": "C"
},
{
"code": null,
"e": 1353,
"s": 1348,
"text": "Java"
},
{
"code": null,
"e": 1361,
"s": 1353,
"text": "Python3"
},
{
"code": null,
"e": 1364,
"s": 1361,
"text": "C#"
},
{
"code": null,
"e": 1368,
"s": 1364,
"text": "PHP"
},
{
"code": null,
"e": 1379,
"s": 1368,
"text": "Javascript"
},
{
"code": "// A C++ program to find floor(sqrt(x)#include<bits/stdc++.h>using namespace std; // Returns floor of square root of xint floorSqrt(int x){ // Base cases if (x == 0 || x == 1) return x; // Starting from 1, try all numbers until // i*i is greater than or equal to x. int i = 1, result = 1; while (result <= x) { i++; result = i * i; } return i - 1;} // Driver programint main(){ int x = 11; cout << floorSqrt(x) << endl; return 0;}",
"e": 1860,
"s": 1379,
"text": null
},
{
"code": "#include <stdio.h> // Returns floor of square root of xint floorSqrt(int x){ // Base cases if (x == 0 || x == 1) return x; // Starting from 1, try all numbers until // i*i is greater than or equal to x. int i = 1, result = 1; while (result <= x) { i++; result = i * i; } return i - 1;} // Driver programint main(){ int x = 11; printf(\"%d\\n\",floorSqrt(x)); return 0;}//code is contributed by lalith kumar.g",
"e": 2310,
"s": 1860,
"text": null
},
{
"code": "// A Java program to find floor(sqrt(x)) class GFG { // Returns floor of square root of x static int floorSqrt(int x) { // Base cases if (x == 0 || x == 1) return x; // Starting from 1, try all numbers until // i*i is greater than or equal to x. int i = 1, result = 1; while (result <= x) { i++; result = i * i; } return i - 1; } // Driver program public static void main(String[] args) { int x = 11; System.out.print(floorSqrt(x)); }} // This code is contributed by Smitha Dinesh Semwal.",
"e": 2942,
"s": 2310,
"text": null
},
{
"code": "# Python3 program to find floor(sqrt(x) # Returns floor of square root of xdef floorSqrt(x): # Base cases if (x == 0 or x == 1): return x # Starting from 1, try all numbers until # i*i is greater than or equal to x. i = 1; result = 1 while (result <= x): i += 1 result = i * i return i - 1 # Driver Codex = 11print(floorSqrt(x)) # This code is contributed by Smitha Dinesh Semwal.",
"e": 3377,
"s": 2942,
"text": null
},
{
"code": "// A C# program to// find floor(sqrt(x))using System; class GFG{ // Returns floor of // square root of x static int floorSqrt(int x) { // Base cases if (x == 0 || x == 1) return x; // Starting from 1, try all // numbers until i*i is // greater than or equal to x. int i = 1, result = 1; while (result <= x) { i++; result = i * i; } return i - 1; } // Driver Code static public void Main () { int x = 11; Console.WriteLine(floorSqrt(x)); }} // This code is contributed by ajit",
"e": 4008,
"s": 3377,
"text": null
},
{
"code": "<?php// A PHP program to find floor(sqrt(x) // Returns floor of square root of xfunction floorSqrt($x){ // Base cases if ($x == 0 || $x == 1) return $x; // Starting from 1, try all // numbers until i*i is // greater than or equal to x. $i = 1; $result = 1; while ($result <= $x) { $i++; $result = $i * $i; } return $i - 1;} // Driver Code$x = 11;echo floorSqrt($x), \"\\n\"; // This code is contributed by ajit?>",
"e": 4469,
"s": 4008,
"text": null
},
{
"code": "<script> // A Javascript program to find floor(sqrt(x) // Returns floor of square root of xfunction floorSqrt(x){ // Base cases if (x == 0 || x == 1) return x; // Starting from 1, try all // numbers until i*i is // greater than or equal to x. let i = 1; let result = 1; while (result <= x) { i++; result = i * i; } return i - 1;} // Driver Codelet x = 11;document.write(floorSqrt(x)); // This code is contributed by mohan </script>",
"e": 4966,
"s": 4469,
"text": null
},
{
"code": null,
"e": 4975,
"s": 4966,
"text": "Output :"
},
{
"code": null,
"e": 4977,
"s": 4975,
"text": "3"
},
{
"code": null,
"e": 5158,
"s": 4977,
"text": "Complexity Analysis: Time Complexity: O(√ n). Only one traversal of the solution is needed, so the time complexity is O(√ n).Space Complexity: O(1). Constant extra space is needed."
},
{
"code": null,
"e": 5263,
"s": 5158,
"text": "Time Complexity: O(√ n). Only one traversal of the solution is needed, so the time complexity is O(√ n)."
},
{
"code": null,
"e": 5319,
"s": 5263,
"text": "Space Complexity: O(1). Constant extra space is needed."
},
{
"code": null,
"e": 5642,
"s": 5319,
"text": "Thanks Fattepur Mahesh for suggesting this solution. Better Approach: The idea is to find the largest integer i whose square is less than or equal to the given number. The idea is to use Binary Search to solve the problem. The values of i * i is monotonically increasing, so the problem can be solved using binary search. "
},
{
"code": null,
"e": 6219,
"s": 5642,
"text": "Algorithm: Take care of some base cases, i.e when the given number is 0 or 1.Create some variables, lowerbound l = 0, upperbound r = n, where n is the given number, mid and ans to store the answer.Run a loop until l <= r , the search space vanishesCheck if the square of mid (mid = (l + r)/2 ) is less than or equal to n, If yes then search for a larger value in second half of search space, i.e l = mid + 1, update ans = midElse if the square of mid is more than n then search for a smaller value in first half of search space, i.e r = mid – 1Print the value of answer ( ans)"
},
{
"code": null,
"e": 6785,
"s": 6219,
"text": "Take care of some base cases, i.e when the given number is 0 or 1.Create some variables, lowerbound l = 0, upperbound r = n, where n is the given number, mid and ans to store the answer.Run a loop until l <= r , the search space vanishesCheck if the square of mid (mid = (l + r)/2 ) is less than or equal to n, If yes then search for a larger value in second half of search space, i.e l = mid + 1, update ans = midElse if the square of mid is more than n then search for a smaller value in first half of search space, i.e r = mid – 1Print the value of answer ( ans)"
},
{
"code": null,
"e": 6852,
"s": 6785,
"text": "Take care of some base cases, i.e when the given number is 0 or 1."
},
{
"code": null,
"e": 6973,
"s": 6852,
"text": "Create some variables, lowerbound l = 0, upperbound r = n, where n is the given number, mid and ans to store the answer."
},
{
"code": null,
"e": 7025,
"s": 6973,
"text": "Run a loop until l <= r , the search space vanishes"
},
{
"code": null,
"e": 7203,
"s": 7025,
"text": "Check if the square of mid (mid = (l + r)/2 ) is less than or equal to n, If yes then search for a larger value in second half of search space, i.e l = mid + 1, update ans = mid"
},
{
"code": null,
"e": 7323,
"s": 7203,
"text": "Else if the square of mid is more than n then search for a smaller value in first half of search space, i.e r = mid – 1"
},
{
"code": null,
"e": 7356,
"s": 7323,
"text": "Print the value of answer ( ans)"
},
{
"code": null,
"e": 7372,
"s": 7356,
"text": "Implementation:"
},
{
"code": null,
"e": 7376,
"s": 7372,
"text": "C++"
},
{
"code": null,
"e": 7378,
"s": 7376,
"text": "C"
},
{
"code": null,
"e": 7383,
"s": 7378,
"text": "Java"
},
{
"code": null,
"e": 7391,
"s": 7383,
"text": "Python3"
},
{
"code": null,
"e": 7394,
"s": 7391,
"text": "C#"
},
{
"code": null,
"e": 7398,
"s": 7394,
"text": "PHP"
},
{
"code": null,
"e": 7409,
"s": 7398,
"text": "Javascript"
},
{
"code": "#include <iostream> using namespace std;int floorSqrt(int x){ // Base cases if (x == 0 || x == 1) return x; // Do Binary Search for floor(sqrt(x)) int start = 1, end = x/2, ans; while (start <= end) { int mid = (start + end) / 2; // If x is a perfect square int sqr = mid * mid; if (sqr == x) return mid; // Since we need floor, we update answer when // mid*mid is smaller than x, and move closer to // sqrt(x) /* if(mid*mid<=x) { start = mid+1; ans = mid; } Here basically if we multiply mid with itself so there will be integer overflow which will throw tle for larger input so to overcome this situation we can use long or we can just divide the number by mid which is same as checking mid*mid < x */ if (sqr <= x) { start = mid + 1; ans = mid; } else // If mid*mid is greater than x end = mid - 1; } return ans;} // Driver programint main(){ int x = 20221; cout << floorSqrt(x) << endl; return 0;}",
"e": 8644,
"s": 7409,
"text": null
},
{
"code": "#include <stdio.h>#include <math.h> int floorSqrt(int x) { // Base Cases if (x == 0 || x == 1) return x; // Do Binary Search for floor(sqrt(x)) long start = 1, end = x, ans=0; while (start <= end) { int mid = (start + end) / 2; // If x is a perfect square if (mid*mid == x) return (int)mid; // Since we need floor, we update answer when mid*mid is // smaller than x, and move closer to sqrt(x) if (mid*mid < x) { start = mid + 1; ans = mid; } else // If mid*mid is greater than x end = mid-1; } return (int)ans; } // Driver Method int main() { int x = 11; printf(\"%d\\n\",floorSqrt(x)); } //Contributed by lalith kumar.g",
"e": 9527,
"s": 8644,
"text": null
},
{
"code": "// A Java program to find floor(sqrt(x)public class Test{ public static int floorSqrt(int x) { // Base Cases if (x == 0 || x == 1) return x; // Do Binary Search for floor(sqrt(x)) long start = 1, end = x, ans=0; while (start <= end) { long mid = (start + end) / 2; // If x is a perfect square if (mid*mid == x) return (int)mid; // Since we need floor, we update answer when mid*mid is // smaller than x, and move closer to sqrt(x) if (mid*mid < x) { start = mid + 1; ans = mid; } else // If mid*mid is greater than x end = mid-1; } return (int)ans; } // Driver Method public static void main(String args[]) { int x = 11; System.out.println(floorSqrt(x)); }}// Contributed by InnerPeace",
"e": 10481,
"s": 9527,
"text": null
},
{
"code": "# Python 3 program to find floor(sqrt(x) # Returns floor of square root of x def floorSqrt(x) : # Base cases if (x == 0 or x == 1) : return x # Do Binary Search for floor(sqrt(x)) start = 1 end = x while (start <= end) : mid = (start + end) // 2 # If x is a perfect square if (mid*mid == x) : return mid # Since we need floor, we update # answer when mid*mid is smaller # than x, and move closer to sqrt(x) if (mid * mid < x) : start = mid + 1 ans = mid else : # If mid*mid is greater than x end = mid-1 return ans # driver code x = 11print(floorSqrt(x)) # This code is contributed by Nikita Tiwari.",
"e": 11299,
"s": 10481,
"text": null
},
{
"code": "// A C# program to// find floor(sqrt(x)using System; class GFG{ public static int floorSqrt(int x) { // Base Cases if (x == 0 || x == 1) return x; // Do Binary Search // for floor(sqrt(x)) int start = 1, end = x, ans = 0; while (start <= end) { int mid = (start + end) / 2; // If x is a // perfect square if (mid * mid == x) return mid; // Since we need floor, we // update answer when mid * // mid is smaller than x, // and move closer to sqrt(x) if (mid * mid < x) { start = mid + 1; ans = mid; } // If mid*mid is // greater than x else end = mid-1; } return ans; } // Driver Code static public void Main () { int x = 11; Console.WriteLine(floorSqrt(x)); }} // This code is Contributed by m_kit",
"e": 12336,
"s": 11299,
"text": null
},
{
"code": "<?php// A PHP program to find floor(sqrt(x) // Returns floor of// square root of x function floorSqrt($x){ // Base cases if ($x == 0 || $x == 1) return $x; // Do Binary Search // for floor(sqrt(x)) $start = 1; $end = $x; $ans; while ($start <= $end) { $mid = ($start + $end) / 2; // If x is a perfect square if ($mid * $mid == $x) return $mid; // Since we need floor, we update // answer when mid*mid is smaller // than x, and move closer to sqrt(x) if ($mid * $mid < $x) { $start = $mid + 1; $ans = $mid; } // If mid*mid is // greater than x else $end = $mid-1; } return $ans;} // Driver Code$x = 11;echo floorSqrt($x), \"\\n\"; // This code is contributed by ajit?>",
"e": 13183,
"s": 12336,
"text": null
},
{
"code": "<script> // A Javascript program to find floor(sqrt(x) // Returns floor of// square root of x function floorSqrt(x){ // Base cases if (x == 0 || x == 1) return x; // Do Binary Search // for floor(sqrt(x)) let start = 1; let end = x; let ans; while (start <= end) { let mid = (start + end) / 2; // If x is a perfect square if (mid * mid == x) return mid; // Since we need floor, we update // answer when mid*mid is smaller // than x, and move closer to sqrt(x) if (mid * mid < x) { start = mid + 1; ans = mid; } // If mid*mid is // greater than x else end = mid-1; } return ans;} // Driver Codelet x = 11;document.write(floorSqrt(x) + \"<br>\"); // This code is contributed by _saurabh_jaiswal</script>",
"e": 14075,
"s": 13183,
"text": null
},
{
"code": null,
"e": 14084,
"s": 14075,
"text": "Output :"
},
{
"code": null,
"e": 14088,
"s": 14084,
"text": "142"
},
{
"code": null,
"e": 14245,
"s": 14088,
"text": "Complexity Analysis: Time complexity: O(log n). The time complexity of the binary search is O(log n).Space Complexity: O(1). Constant extra space is needed."
},
{
"code": null,
"e": 14326,
"s": 14245,
"text": "Time complexity: O(log n). The time complexity of the binary search is O(log n)."
},
{
"code": null,
"e": 14382,
"s": 14326,
"text": "Space Complexity: O(1). Constant extra space is needed."
},
{
"code": null,
"e": 14651,
"s": 14382,
"text": "Thanks to Gaurav Ahirwar for suggesting above method.Note: The Binary Search can be further optimized to start with ‘start’ = 0 and ‘end’ = x/2. The floor of the square root of x cannot be more than x/2 when x > 1.Thanks to visit for suggesting the above optimization."
},
{
"code": null,
"e": 14814,
"s": 14651,
"text": "Better Approach: The logic is simple as we can observe that for a perfect square number it’s square root represent the total no of the perfect square from 1 to x."
},
{
"code": null,
"e": 14871,
"s": 14814,
"text": "for ex:- sqrt(1)=1, sqrt(4)=2, sqrt(9)=3 ........ so on."
},
{
"code": null,
"e": 14882,
"s": 14871,
"text": "Algorithm:"
},
{
"code": null,
"e": 14969,
"s": 14882,
"text": " 1. find the square root of x and store in a variable sqrt."
},
{
"code": null,
"e": 15132,
"s": 14969,
"text": " 2. Use the floor value of sqrt and store in variable result, because for non-perfect square number. it’s floor value gives the result."
},
{
"code": null,
"e": 15182,
"s": 15132,
"text": " 3. return the result."
},
{
"code": null,
"e": 15198,
"s": 15182,
"text": "Implementation:"
},
{
"code": null,
"e": 15202,
"s": 15198,
"text": "C++"
},
{
"code": null,
"e": 15204,
"s": 15202,
"text": "C"
},
{
"code": null,
"e": 15209,
"s": 15204,
"text": "Java"
},
{
"code": null,
"e": 15217,
"s": 15209,
"text": "Python3"
},
{
"code": null,
"e": 15220,
"s": 15217,
"text": "C#"
},
{
"code": null,
"e": 15231,
"s": 15220,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std;int countSquares(int x){ int sqr = sqrt(x); int result = (int)(sqr); return result;}int main(){ int x = 9; cout << (countSquares(x)); return 0;} // This code is contributed by Rajput-Ji",
"e": 15481,
"s": 15231,
"text": null
},
{
"code": "#include <stdio.h>#include <math.h> static int countSquares(int x) { int sqr = (int) sqrt(x); int result = (int) (sqr); return result; } int main() { int x = 9; printf(\"%d\\n\",countSquares(x)); }// This code is contributed by lalith kumar.g",
"e": 15769,
"s": 15481,
"text": null
},
{
"code": "import java.util.*; class GFG { static int countSquares(int x) { int sqr = (int) Math.sqrt(x); int result = (int) (sqr); return result; } public static void main(String[] args) { int x = 9; System.out.print(countSquares(x)); }} // This code is contributed by Rajput-Ji",
"e": 16089,
"s": 15769,
"text": null
},
{
"code": "def countSquares(x): sqrt = x**0.5 result = int(sqrt) return resultx = 9print(countSquares(x))",
"e": 16187,
"s": 16089,
"text": null
},
{
"code": "using System;public class GFG { static int countSquares(int x) { int sqr = (int) Math.Sqrt(x); int result = (int) (sqr); return result; } public static void Main(String[] args) { int x = 9; Console.Write(countSquares(x)); }} // This code is contributed by Rajput-Ji",
"e": 16473,
"s": 16187,
"text": null
},
{
"code": "<script> function countSquares(x) { var sqr = parseInt( Math.sqrt(x)); var result = parseInt(sqr); return result; } var x = 9; document.write(countSquares(x)); // This code is contributed by Rajput-Ji</script>",
"e": 16725,
"s": 16473,
"text": null
},
{
"code": null,
"e": 16733,
"s": 16725,
"text": "Output:"
},
{
"code": null,
"e": 16735,
"s": 16733,
"text": "3"
},
{
"code": null,
"e": 16819,
"s": 16735,
"text": "Method: Finding square root of an integer by using sqrt() function of math module."
},
{
"code": null,
"e": 16827,
"s": 16819,
"text": "Python3"
},
{
"code": "# Python3 program to find (sqrt(x))from math import*n=4# using the sqrt functon of math# module finding the square root integerprint(round(sqrt(n))) # This code is contributed by gangarajula laxmi",
"e": 17024,
"s": 16827,
"text": null
},
{
"code": null,
"e": 17026,
"s": 17024,
"text": "2"
},
{
"code": null,
"e": 17097,
"s": 17026,
"text": "Complexity AnalysisTime complexity:- O(log n)Auxiliary Space :- O(1) "
},
{
"code": null,
"e": 17124,
"s": 17097,
"text": "Time complexity:- O(log n)"
},
{
"code": null,
"e": 17150,
"s": 17124,
"text": "Auxiliary Space :- O(1) "
},
{
"code": null,
"e": 17156,
"s": 17150,
"text": "jit_t"
},
{
"code": null,
"e": 17168,
"s": 17156,
"text": "FarhanSheik"
},
{
"code": null,
"e": 17176,
"s": 17168,
"text": "yhgupta"
},
{
"code": null,
"e": 17187,
"s": 17176,
"text": "andrew1234"
},
{
"code": null,
"e": 17204,
"s": 17187,
"text": "pulamolusaimohan"
},
{
"code": null,
"e": 17218,
"s": 17204,
"text": "swamipatil158"
},
{
"code": null,
"e": 17235,
"s": 17218,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 17249,
"s": 17235,
"text": "amit aggrawal"
},
{
"code": null,
"e": 17263,
"s": 17249,
"text": "surajrawat307"
},
{
"code": null,
"e": 17280,
"s": 17263,
"text": "arorakashish0911"
},
{
"code": null,
"e": 17296,
"s": 17280,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 17304,
"s": 17296,
"text": "ibrezm1"
},
{
"code": null,
"e": 17320,
"s": 17304,
"text": "aakashpanda2000"
},
{
"code": null,
"e": 17330,
"s": 17320,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 17338,
"s": 17330,
"text": "movshov"
},
{
"code": null,
"e": 17351,
"s": 17338,
"text": "nitish705702"
},
{
"code": null,
"e": 17366,
"s": 17351,
"text": "lalithkumarg20"
},
{
"code": null,
"e": 17376,
"s": 17366,
"text": "dsoumi125"
},
{
"code": null,
"e": 17395,
"s": 17376,
"text": "laxmigangarajula03"
},
{
"code": null,
"e": 17404,
"s": 17395,
"text": "Accolite"
},
{
"code": null,
"e": 17411,
"s": 17404,
"text": "Amazon"
},
{
"code": null,
"e": 17425,
"s": 17411,
"text": "Binary Search"
},
{
"code": null,
"e": 17435,
"s": 17425,
"text": "Microsoft"
},
{
"code": null,
"e": 17444,
"s": 17435,
"text": "Ola Cabs"
},
{
"code": null,
"e": 17453,
"s": 17444,
"text": "Snapdeal"
},
{
"code": null,
"e": 17472,
"s": 17453,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 17485,
"s": 17472,
"text": "Mathematical"
},
{
"code": null,
"e": 17494,
"s": 17485,
"text": "Accolite"
},
{
"code": null,
"e": 17501,
"s": 17494,
"text": "Amazon"
},
{
"code": null,
"e": 17511,
"s": 17501,
"text": "Microsoft"
},
{
"code": null,
"e": 17520,
"s": 17511,
"text": "Snapdeal"
},
{
"code": null,
"e": 17529,
"s": 17520,
"text": "Ola Cabs"
},
{
"code": null,
"e": 17542,
"s": 17529,
"text": "Mathematical"
},
{
"code": null,
"e": 17561,
"s": 17542,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 17575,
"s": 17561,
"text": "Binary Search"
},
{
"code": null,
"e": 17673,
"s": 17575,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 17693,
"s": 17673,
"text": "Find a peak element"
},
{
"code": null,
"e": 17734,
"s": 17693,
"text": "Median of two sorted arrays of same size"
},
{
"code": null,
"e": 17767,
"s": 17734,
"text": "Allocate minimum number of pages"
},
{
"code": null,
"e": 17792,
"s": 17767,
"text": "Quick Sort vs Merge Sort"
},
{
"code": null,
"e": 17850,
"s": 17792,
"text": "Closest Pair of Points using Divide and Conquer algorithm"
},
{
"code": null,
"e": 17880,
"s": 17850,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 17923,
"s": 17880,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 17983,
"s": 17923,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 17998,
"s": 17983,
"text": "C++ Data Types"
}
] |
Static Function in PHP
|
31 Jul, 2021
In certain cases, it is very handy to access methods and properties in terms of a class rather than an object. This can be done with the help of static keyword. Any method declared as static is accessible without the creation of an object. Static functions are associated with the class, not an instance of the class. They are permitted to access only static methods and static variables. To add a static method to the class, static keyword is used.
public static function test()
{
// Method implementation
}
They can be invoked directly outside the class by using scope resolution operator (::) as follows:
MyClass::test();
Example: This example illustrates static function as counter.
<?php/* Use static function as a counter */ class solution { static $count; public static function getCount() { return self::$count++; }} solution::$count = 1; for($i = 0; $i < 5; ++$i) { echo 'The next value is: '. solution::getCount() . "\n";} ?>
The next value is: 1
The next value is: 2
The next value is: 3
The next value is: 4
The next value is: 5
When to define static methods ?The static keyword is used in the context of variables and methods that are common to all the objects of the class. Therefore, any logic which can be shared among multiple instances of a class should be extracted and put inside the static method. PHP static methods are most typically used in classes containing static methods only often called utility classes of PHP frameworks like Laravel and CakePHP.
Below is the PHP code which shows the use of static methods.
Example: This example illustrates the static method in PHP.
<?php/* Use of static method in PHP */ class A { public function test($var = "Hello World") { $this->var = $var; return $this->var; }} class B { public static function test($var) { $var = "This is static"; return $var; }} // Creating Object of class A$obj = new A(); echo $obj->test('This is non-static'); echo "\n";echo B::test('This is non-static'); ?>
This is non-static
This is static
However, a static method doesn’t let you define explicit dependencies and includes global variables in the code that can be accessed from anywhere. This can affect the scalability of an application. Moreover, you will have a tough time performing automated testing on classes containing static methods. Therefore, they should be used for utilities and not for convenience reasons.
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.
PHP-function
Picked
PHP
PHP Programs
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to convert array to string in PHP ?
PHP | Converting string to Date and DateTime
How to get parameters from a URL string in PHP?
Split a comma delimited string into an array in PHP
Download file from URL using PHP
How to convert array to string in PHP ?
How to call PHP function on the click of a Button ?
How to get parameters from a URL string in PHP?
Split a comma delimited string into an array in PHP
How to pass JavaScript variables to PHP ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 Jul, 2021"
},
{
"code": null,
"e": 478,
"s": 28,
"text": "In certain cases, it is very handy to access methods and properties in terms of a class rather than an object. This can be done with the help of static keyword. Any method declared as static is accessible without the creation of an object. Static functions are associated with the class, not an instance of the class. They are permitted to access only static methods and static variables. To add a static method to the class, static keyword is used."
},
{
"code": null,
"e": 542,
"s": 478,
"text": "public static function test()\n{\n // Method implementation\n}\n"
},
{
"code": null,
"e": 641,
"s": 542,
"text": "They can be invoked directly outside the class by using scope resolution operator (::) as follows:"
},
{
"code": null,
"e": 659,
"s": 641,
"text": "MyClass::test();\n"
},
{
"code": null,
"e": 721,
"s": 659,
"text": "Example: This example illustrates static function as counter."
},
{
"code": "<?php/* Use static function as a counter */ class solution { static $count; public static function getCount() { return self::$count++; }} solution::$count = 1; for($i = 0; $i < 5; ++$i) { echo 'The next value is: '. solution::getCount() . \"\\n\";} ?>",
"e": 1009,
"s": 721,
"text": null
},
{
"code": null,
"e": 1115,
"s": 1009,
"text": "The next value is: 1\nThe next value is: 2\nThe next value is: 3\nThe next value is: 4\nThe next value is: 5\n"
},
{
"code": null,
"e": 1551,
"s": 1115,
"text": "When to define static methods ?The static keyword is used in the context of variables and methods that are common to all the objects of the class. Therefore, any logic which can be shared among multiple instances of a class should be extracted and put inside the static method. PHP static methods are most typically used in classes containing static methods only often called utility classes of PHP frameworks like Laravel and CakePHP."
},
{
"code": null,
"e": 1612,
"s": 1551,
"text": "Below is the PHP code which shows the use of static methods."
},
{
"code": null,
"e": 1672,
"s": 1612,
"text": "Example: This example illustrates the static method in PHP."
},
{
"code": "<?php/* Use of static method in PHP */ class A { public function test($var = \"Hello World\") { $this->var = $var; return $this->var; }} class B { public static function test($var) { $var = \"This is static\"; return $var; }} // Creating Object of class A$obj = new A(); echo $obj->test('This is non-static'); echo \"\\n\";echo B::test('This is non-static'); ?>",
"e": 2079,
"s": 1672,
"text": null
},
{
"code": null,
"e": 2114,
"s": 2079,
"text": "This is non-static\nThis is static\n"
},
{
"code": null,
"e": 2495,
"s": 2114,
"text": "However, a static method doesn’t let you define explicit dependencies and includes global variables in the code that can be accessed from anywhere. This can affect the scalability of an application. Moreover, you will have a tough time performing automated testing on classes containing static methods. Therefore, they should be used for utilities and not for convenience reasons."
},
{
"code": null,
"e": 2664,
"s": 2495,
"text": "PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples."
},
{
"code": null,
"e": 2677,
"s": 2664,
"text": "PHP-function"
},
{
"code": null,
"e": 2684,
"s": 2677,
"text": "Picked"
},
{
"code": null,
"e": 2688,
"s": 2684,
"text": "PHP"
},
{
"code": null,
"e": 2701,
"s": 2688,
"text": "PHP Programs"
},
{
"code": null,
"e": 2718,
"s": 2701,
"text": "Web Technologies"
},
{
"code": null,
"e": 2722,
"s": 2718,
"text": "PHP"
},
{
"code": null,
"e": 2820,
"s": 2722,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2860,
"s": 2820,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 2905,
"s": 2860,
"text": "PHP | Converting string to Date and DateTime"
},
{
"code": null,
"e": 2953,
"s": 2905,
"text": "How to get parameters from a URL string in PHP?"
},
{
"code": null,
"e": 3005,
"s": 2953,
"text": "Split a comma delimited string into an array in PHP"
},
{
"code": null,
"e": 3038,
"s": 3005,
"text": "Download file from URL using PHP"
},
{
"code": null,
"e": 3078,
"s": 3038,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 3130,
"s": 3078,
"text": "How to call PHP function on the click of a Button ?"
},
{
"code": null,
"e": 3178,
"s": 3130,
"text": "How to get parameters from a URL string in PHP?"
},
{
"code": null,
"e": 3230,
"s": 3178,
"text": "Split a comma delimited string into an array in PHP"
}
] |
WPF - WrapPanel
|
In WrapPanel, child elements are positioned in sequential order, from left to right or from top to bottom based on the orientation property. The only difference between StackPanel and WrapPanel is that it doesn’t stack all the child elements in a single line; it wraps the remaining elements to another line if there is no space left.
WrapPanel is mostly used for tabs or menu items. The hierarchical inheritance of WrapPanel class is as follows −
Background
Gets or sets a Brush that fills the panel content area. (Inherited from Panel)
Children
Gets a UIElementCollection of child elements of this Panel. (Inherited from Panel.)
Height
Gets or sets the suggested height of the element. (Inherited from FrameworkElement.)
ItemHeight
Gets or sets a value that specifies the height of all items that are contained within a WrapPanel.
ItemWidth
Gets or sets a value that specifies the width of all items that are contained within a WrapPanel.
LogicalChildren
Gets an enumerator that can iterate the logical child elements of this Panel element. (Inherited from Panel.)
LogicalOrientation
The Orientation of the panel, if the panel supports layout in only a single dimension. (Inherited from Panel.)
Margin
Gets or sets the outer margin of an element. (Inherited from FrameworkElement.)
Name
Gets or sets the identifying name of the element. The name provides a reference so that code-behind, such as event handler code, can refer to a markup element after it is constructed during processing by a XAML processor. (Inherited from FrameworkElement.)
Orientation
Gets or sets a value that specifies the dimension in which child content is arranged.
Parent
Gets the logical parent element of this element. (Inherited from FrameworkElement.)
Resources
Gets or sets the locally-defined resource dictionary. (Inherited from FrameworkElement.)
Style
Gets or sets the style used by this element when it is rendered. (Inherited from FrameworkElement.)
Width
Gets or sets the width of the element. (Inherited from FrameworkElement.)
The following example shows how to add child elements into a WrapPanel. Here is the XAML implementation in which Text Blocks and Text Boxes are created inside a WrapPanel in horizontal direction.
<Window x:Class = "WPFWrapPanel.MainWindow"
xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d = "http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local = "clr-namespace:WPFWrapPanel"
mc:Ignorable = "d" Title = "MainWindow" Height = "350" Width = "604">
<Grid>
<WrapPanel Orientation = "Vertical">
<TextBlock Text = "Fist Name" Width = "60" Height = "20" Margin = "5" />
<TextBox Width = "200" Height = "20" Margin = "5" />
<TextBlock Text = "Last Name" Width = "60" Height = "20" Margin = "5" />
<TextBox Width = "200" Height = "20" Margin = "5"/>
<TextBlock Text = "Age" Width = "60" Height = "20" Margin = "5" />
<TextBox Width = "60" Height = "20" Margin = "5" />
<TextBlock Text = "Title" Width = "60" Height = "20" Margin = "5" />
<TextBox Width = "200" Height = "20" Margin = "5" />
</WrapPanel>
</Grid>
</Window>
When you compile and execute the above code, it will produce the following window. You can change the arrangement from top to bottom by changing the orientation property to Vertical.
We recommend that you execute the above example code and try the other properties of this class as well.
|
[
{
"code": null,
"e": 2489,
"s": 2154,
"text": "In WrapPanel, child elements are positioned in sequential order, from left to right or from top to bottom based on the orientation property. The only difference between StackPanel and WrapPanel is that it doesn’t stack all the child elements in a single line; it wraps the remaining elements to another line if there is no space left."
},
{
"code": null,
"e": 2602,
"s": 2489,
"text": "WrapPanel is mostly used for tabs or menu items. The hierarchical inheritance of WrapPanel class is as follows −"
},
{
"code": null,
"e": 2613,
"s": 2602,
"text": "Background"
},
{
"code": null,
"e": 2692,
"s": 2613,
"text": "Gets or sets a Brush that fills the panel content area. (Inherited from Panel)"
},
{
"code": null,
"e": 2701,
"s": 2692,
"text": "Children"
},
{
"code": null,
"e": 2785,
"s": 2701,
"text": "Gets a UIElementCollection of child elements of this Panel. (Inherited from Panel.)"
},
{
"code": null,
"e": 2792,
"s": 2785,
"text": "Height"
},
{
"code": null,
"e": 2877,
"s": 2792,
"text": "Gets or sets the suggested height of the element. (Inherited from FrameworkElement.)"
},
{
"code": null,
"e": 2888,
"s": 2877,
"text": "ItemHeight"
},
{
"code": null,
"e": 2987,
"s": 2888,
"text": "Gets or sets a value that specifies the height of all items that are contained within a WrapPanel."
},
{
"code": null,
"e": 2997,
"s": 2987,
"text": "ItemWidth"
},
{
"code": null,
"e": 3095,
"s": 2997,
"text": "Gets or sets a value that specifies the width of all items that are contained within a WrapPanel."
},
{
"code": null,
"e": 3111,
"s": 3095,
"text": "LogicalChildren"
},
{
"code": null,
"e": 3221,
"s": 3111,
"text": "Gets an enumerator that can iterate the logical child elements of this Panel element. (Inherited from Panel.)"
},
{
"code": null,
"e": 3240,
"s": 3221,
"text": "LogicalOrientation"
},
{
"code": null,
"e": 3351,
"s": 3240,
"text": "The Orientation of the panel, if the panel supports layout in only a single dimension. (Inherited from Panel.)"
},
{
"code": null,
"e": 3358,
"s": 3351,
"text": "Margin"
},
{
"code": null,
"e": 3438,
"s": 3358,
"text": "Gets or sets the outer margin of an element. (Inherited from FrameworkElement.)"
},
{
"code": null,
"e": 3443,
"s": 3438,
"text": "Name"
},
{
"code": null,
"e": 3700,
"s": 3443,
"text": "Gets or sets the identifying name of the element. The name provides a reference so that code-behind, such as event handler code, can refer to a markup element after it is constructed during processing by a XAML processor. (Inherited from FrameworkElement.)"
},
{
"code": null,
"e": 3712,
"s": 3700,
"text": "Orientation"
},
{
"code": null,
"e": 3798,
"s": 3712,
"text": "Gets or sets a value that specifies the dimension in which child content is arranged."
},
{
"code": null,
"e": 3805,
"s": 3798,
"text": "Parent"
},
{
"code": null,
"e": 3889,
"s": 3805,
"text": "Gets the logical parent element of this element. (Inherited from FrameworkElement.)"
},
{
"code": null,
"e": 3899,
"s": 3889,
"text": "Resources"
},
{
"code": null,
"e": 3988,
"s": 3899,
"text": "Gets or sets the locally-defined resource dictionary. (Inherited from FrameworkElement.)"
},
{
"code": null,
"e": 3994,
"s": 3988,
"text": "Style"
},
{
"code": null,
"e": 4094,
"s": 3994,
"text": "Gets or sets the style used by this element when it is rendered. (Inherited from FrameworkElement.)"
},
{
"code": null,
"e": 4100,
"s": 4094,
"text": "Width"
},
{
"code": null,
"e": 4174,
"s": 4100,
"text": "Gets or sets the width of the element. (Inherited from FrameworkElement.)"
},
{
"code": null,
"e": 4370,
"s": 4174,
"text": "The following example shows how to add child elements into a WrapPanel. Here is the XAML implementation in which Text Blocks and Text Boxes are created inside a WrapPanel in horizontal direction."
},
{
"code": null,
"e": 5490,
"s": 4370,
"text": "<Window x:Class = \"WPFWrapPanel.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n xmlns:d = \"http://schemas.microsoft.com/expression/blend/2008\" \n xmlns:mc = \"http://schemas.openxmlformats.org/markup-compatibility/2006\" \n xmlns:local = \"clr-namespace:WPFWrapPanel\" \n mc:Ignorable = \"d\" Title = \"MainWindow\" Height = \"350\" Width = \"604\"> \n\t\n <Grid> \n <WrapPanel Orientation = \"Vertical\"> \n <TextBlock Text = \"Fist Name\" Width = \"60\" Height = \"20\" Margin = \"5\" /> \n <TextBox Width = \"200\" Height = \"20\" Margin = \"5\" /> \n <TextBlock Text = \"Last Name\" Width = \"60\" Height = \"20\" Margin = \"5\" /> \n <TextBox Width = \"200\" Height = \"20\" Margin = \"5\"/> \n <TextBlock Text = \"Age\" Width = \"60\" Height = \"20\" Margin = \"5\" /> \n <TextBox Width = \"60\" Height = \"20\" Margin = \"5\" /> \n <TextBlock Text = \"Title\" Width = \"60\" Height = \"20\" Margin = \"5\" /> \n <TextBox Width = \"200\" Height = \"20\" Margin = \"5\" /> \n </WrapPanel> \n </Grid> \n\t\n</Window>"
},
{
"code": null,
"e": 5673,
"s": 5490,
"text": "When you compile and execute the above code, it will produce the following window. You can change the arrangement from top to bottom by changing the orientation property to Vertical."
}
] |
Principal Component Analysis with R Programming
|
16 Dec, 2021
Principal component analysis(PCA) in R programming is an analysis of the linear components of all existing attributes. Principal components are linear combinations (orthogonal transformation) of the original predictor in the dataset. It is a useful technique for EDA(Exploratory data analysis) and allows you to better visualize the variations present in a dataset with many variables.
First principal component captures the maximum variance in dataset. It determines the direction of higher variability. Second principal component captures the remaining variance in data and is uncorrelated with PC1. The correlation between PC1 and PC2 should be zero. So, all succeeding principal components follow the same concept. They capture the remaining variance without being correlated to the previous principal component.
The dataset mtcars(motor trend car road test) comprises fuel consumption and 10 aspects of automobile design and performance for 32 automobiles. It comes pre-installed with dplyr package in R.
R
# Installing required packageinstall.packages("dplyr") # Loading the packagelibrary(dplyr) # Importing excel filestr(mtcars)
Output:
We perform Principal component analysis on mtcars which consists of 32 car brands and 10 variables.
R
# Loading Datadata(mtcars) # Apply PCA using prcomp function# Need to scale / Normalize as# PCA depends on distance measuremy_pca <- prcomp(mtcars, scale = TRUE, center = TRUE, retx = T)names(my_pca) # Summarysummary(my_pca)my_pca # View the principal component loading# my_pca$rotation[1:5, 1:4]my_pca$rotation # See the principal componentsdim(my_pca$x)my_pca$x # Plotting the resultant principal components# The parameter scale = 0 ensures that arrows# are scaled to represent the loadingsbiplot(my_pca, main = "Biplot", scale = 0) # Compute standard deviationmy_pca$sdev # Compute variancemy_pca.var <- my_pca$sdev ^ 2my_pca.var # Proportion of variance for a scree plotpropve <- my_pca.var / sum(my_pca.var)propve # Plot variance explained for each principal componentplot(propve, xlab = "principal component", ylab = "Proportion of Variance Explained", ylim = c(0, 1), type = "b", main = "Scree Plot") # Plot the cumulative proportion of variance explainedplot(cumsum(propve), xlab = "Principal Component", ylab = "Cumulative Proportion of Variance Explained", ylim = c(0, 1), type = "b") # Find Top n principal component# which will atleast cover 90 % variance of dimensionwhich(cumsum(propve) >= 0.9)[1] # Predict mpg using first 4 new Principal Components# Add a training set with principal componentstrain.data <- data.frame(disp = mtcars$disp, my_pca$x[, 1:4]) # Running a Decision tree algporithm## Installing and loading packagesinstall.packages("rpart")install.packages("rpart.plot")library(rpart)library(rpart.plot) rpart.model <- rpart(disp ~ ., data = train.data, method = "anova") rpart.plot(rpart.model)
Output:
Bi plot
The resultant principal components are plotted as Biplot. Scale value 0 represents that arrows are scaled representing loadings.
Variance explained for each principal component
Scree Plot represents the proportion of variance and a principal component. Below 2 principal components, there is a maximum proportion of variance as clearly seen in the plot.
Cumulative proportion of variance
Scree Plot represents the Cumulative proportion of variance and a principal component. Above 2 principal components, there is a maximum cumulative proportion of variance as clearly seen in the plot.
Decision tree model
Decision tree model was built to predict disp using other variables in the dataset and using ANOVA method. The decision tree plot is plotted and displays the information.
kumar_satyam
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
How to Replace specific values in column in R DataFrame ?
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Loops in R (for, while, repeat)
Group by function in R using Dplyr
How to change Row Names of DataFrame in R ?
R Programming Language - Introduction
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Dec, 2021"
},
{
"code": null,
"e": 414,
"s": 28,
"text": "Principal component analysis(PCA) in R programming is an analysis of the linear components of all existing attributes. Principal components are linear combinations (orthogonal transformation) of the original predictor in the dataset. It is a useful technique for EDA(Exploratory data analysis) and allows you to better visualize the variations present in a dataset with many variables."
},
{
"code": null,
"e": 845,
"s": 414,
"text": "First principal component captures the maximum variance in dataset. It determines the direction of higher variability. Second principal component captures the remaining variance in data and is uncorrelated with PC1. The correlation between PC1 and PC2 should be zero. So, all succeeding principal components follow the same concept. They capture the remaining variance without being correlated to the previous principal component."
},
{
"code": null,
"e": 1038,
"s": 845,
"text": "The dataset mtcars(motor trend car road test) comprises fuel consumption and 10 aspects of automobile design and performance for 32 automobiles. It comes pre-installed with dplyr package in R."
},
{
"code": null,
"e": 1040,
"s": 1038,
"text": "R"
},
{
"code": "# Installing required packageinstall.packages(\"dplyr\") # Loading the packagelibrary(dplyr) # Importing excel filestr(mtcars)",
"e": 1165,
"s": 1040,
"text": null
},
{
"code": null,
"e": 1173,
"s": 1165,
"text": "Output:"
},
{
"code": null,
"e": 1273,
"s": 1173,
"text": "We perform Principal component analysis on mtcars which consists of 32 car brands and 10 variables."
},
{
"code": null,
"e": 1275,
"s": 1273,
"text": "R"
},
{
"code": "# Loading Datadata(mtcars) # Apply PCA using prcomp function# Need to scale / Normalize as# PCA depends on distance measuremy_pca <- prcomp(mtcars, scale = TRUE, center = TRUE, retx = T)names(my_pca) # Summarysummary(my_pca)my_pca # View the principal component loading# my_pca$rotation[1:5, 1:4]my_pca$rotation # See the principal componentsdim(my_pca$x)my_pca$x # Plotting the resultant principal components# The parameter scale = 0 ensures that arrows# are scaled to represent the loadingsbiplot(my_pca, main = \"Biplot\", scale = 0) # Compute standard deviationmy_pca$sdev # Compute variancemy_pca.var <- my_pca$sdev ^ 2my_pca.var # Proportion of variance for a scree plotpropve <- my_pca.var / sum(my_pca.var)propve # Plot variance explained for each principal componentplot(propve, xlab = \"principal component\", ylab = \"Proportion of Variance Explained\", ylim = c(0, 1), type = \"b\", main = \"Scree Plot\") # Plot the cumulative proportion of variance explainedplot(cumsum(propve), xlab = \"Principal Component\", ylab = \"Cumulative Proportion of Variance Explained\", ylim = c(0, 1), type = \"b\") # Find Top n principal component# which will atleast cover 90 % variance of dimensionwhich(cumsum(propve) >= 0.9)[1] # Predict mpg using first 4 new Principal Components# Add a training set with principal componentstrain.data <- data.frame(disp = mtcars$disp, my_pca$x[, 1:4]) # Running a Decision tree algporithm## Installing and loading packagesinstall.packages(\"rpart\")install.packages(\"rpart.plot\")library(rpart)library(rpart.plot) rpart.model <- rpart(disp ~ ., data = train.data, method = \"anova\") rpart.plot(rpart.model)",
"e": 2974,
"s": 1275,
"text": null
},
{
"code": null,
"e": 2983,
"s": 2974,
"text": "Output: "
},
{
"code": null,
"e": 2991,
"s": 2983,
"text": "Bi plot"
},
{
"code": null,
"e": 3120,
"s": 2991,
"text": "The resultant principal components are plotted as Biplot. Scale value 0 represents that arrows are scaled representing loadings."
},
{
"code": null,
"e": 3168,
"s": 3120,
"text": "Variance explained for each principal component"
},
{
"code": null,
"e": 3345,
"s": 3168,
"text": "Scree Plot represents the proportion of variance and a principal component. Below 2 principal components, there is a maximum proportion of variance as clearly seen in the plot."
},
{
"code": null,
"e": 3379,
"s": 3345,
"text": "Cumulative proportion of variance"
},
{
"code": null,
"e": 3578,
"s": 3379,
"text": "Scree Plot represents the Cumulative proportion of variance and a principal component. Above 2 principal components, there is a maximum cumulative proportion of variance as clearly seen in the plot."
},
{
"code": null,
"e": 3598,
"s": 3578,
"text": "Decision tree model"
},
{
"code": null,
"e": 3769,
"s": 3598,
"text": "Decision tree model was built to predict disp using other variables in the dataset and using ANOVA method. The decision tree plot is plotted and displays the information."
},
{
"code": null,
"e": 3782,
"s": 3769,
"text": "kumar_satyam"
},
{
"code": null,
"e": 3793,
"s": 3782,
"text": "R Language"
},
{
"code": null,
"e": 3891,
"s": 3793,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3943,
"s": 3891,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 4001,
"s": 3943,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 4053,
"s": 4001,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 4111,
"s": 4053,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 4143,
"s": 4111,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 4178,
"s": 4143,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 4222,
"s": 4178,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 4260,
"s": 4222,
"text": "R Programming Language - Introduction"
},
{
"code": null,
"e": 4298,
"s": 4260,
"text": "How to Change Axis Scales in R Plots?"
}
] |
turtle.forward() method in Python-Turtle
|
16 Jul, 2020
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.
The turtle.forward() method is used to move the turtle forward by the value of the argument that it takes. It gives a line on moving to another position or direction.
turtle.forward(distance)
The argument it takes is distance { a number (integer or float) }. So, it moves the turtle forward by the specified distance, in the direction the turtle is headed.
Below is the implementation of above method with some examples :
Example 1:
Python3
# importing packagesimport turtle # move turtle forward with # distance = 100turtle.forward(100)
Output :
Example 2:
Python3
# importing packageimport turtle # move the turtle forward by 50turtle.forward(50) # change the directionturtle.right(90) # move the turtle forward by 50 againturtle.forward(50)
Output :
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 ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Defaultdict in Python
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n16 Jul, 2020"
},
{
"code": null,
"e": 270,
"s": 53,
"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": 438,
"s": 270,
"text": "The turtle.forward() method is used to move the turtle forward by the value of the argument that it takes. It gives a line on moving to another position or direction. "
},
{
"code": null,
"e": 464,
"s": 438,
"text": "turtle.forward(distance)\n"
},
{
"code": null,
"e": 629,
"s": 464,
"text": "The argument it takes is distance { a number (integer or float) }. So, it moves the turtle forward by the specified distance, in the direction the turtle is headed."
},
{
"code": null,
"e": 694,
"s": 629,
"text": "Below is the implementation of above method with some examples :"
},
{
"code": null,
"e": 705,
"s": 694,
"text": "Example 1:"
},
{
"code": null,
"e": 713,
"s": 705,
"text": "Python3"
},
{
"code": "# importing packagesimport turtle # move turtle forward with # distance = 100turtle.forward(100)",
"e": 811,
"s": 713,
"text": null
},
{
"code": null,
"e": 820,
"s": 811,
"text": "Output :"
},
{
"code": null,
"e": 831,
"s": 820,
"text": "Example 2:"
},
{
"code": null,
"e": 839,
"s": 831,
"text": "Python3"
},
{
"code": "# importing packageimport turtle # move the turtle forward by 50turtle.forward(50) # change the directionturtle.right(90) # move the turtle forward by 50 againturtle.forward(50)",
"e": 1022,
"s": 839,
"text": null
},
{
"code": null,
"e": 1031,
"s": 1022,
"text": "Output :"
},
{
"code": null,
"e": 1045,
"s": 1031,
"text": "Python-turtle"
},
{
"code": null,
"e": 1052,
"s": 1045,
"text": "Python"
},
{
"code": null,
"e": 1150,
"s": 1052,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1182,
"s": 1150,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1209,
"s": 1182,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1230,
"s": 1209,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1253,
"s": 1230,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1309,
"s": 1253,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1351,
"s": 1309,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1382,
"s": 1351,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1424,
"s": 1382,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1463,
"s": 1424,
"text": "Python | Get unique values from a list"
}
] |
Working with XML Files in R Programming
|
13 Sep, 2021
XML which stands for Extensible Markup Language is made up of markup tags, wherein each tag illustrates the information carried by the particular attribute in the XML file. We can work with the XML files using the XML package provided by R. The package has to be explicitly installed using the following command:
install.packages("XML")
XML files can be created by saving the data with the respective tags containing information about the content and saving it with ‘.xml’.We will use the following XML file ‘sample.xml’ to see the various operations that can be performed on the file:
HTML
<RECORDS> <STUDENT> <ID>1</ID> <NAME>Alia</NAME> <MARKS>620</MARKS> <BRANCH>IT</BRANCH> </STUDENT> <STUDENT> <ID>2</ID> <NAME>Brijesh</NAME> <MARKS>440</MARKS> <BRANCH>Commerce</BRANCH> </STUDENT> <STUDENT> <ID>3</ID> <NAME>Yash</NAME> <MARKS>600</MARKS> <BRANCH>Humanities</BRANCH> </STUDENT> <STUDENT> <ID>4</ID> <NAME>Mallika</NAME> <MARKS>660</MARKS> <BRANCH>IT</BRANCH> </STUDENT> <STUDENT> <ID>5</ID> <NAME>Zayn</NAME> <MARKS>560</MARKS> <BRANCH>IT</BRANCH> </STUDENT></RECORDS>
The XML file can be read after installing the package and then parsing it with xmlparse() function, which takes as input the XML file name and prints the content of the file in the form of a list. The file should be located in the current working directory. An additional package named ‘methods’ should also be installed. The following code can be used to read the contents of the file “sample.xml”.
Python3
# loading the library and other important packageslibrary("XML")library("methods") # the contents of sample.xml are parseddata <- xmlParse(file = "sample.xml") print(data)
Output:
1
Alia
620
IT
2
Brijesh
440
Commerce
3
Yash
600
Humanities
4
Mallika
660
IT
5
Zayn
560
IT
XML files can be parsed and operations can be performed on its various components. There are various in-built functions available in R, to extract the information of the nodes associated with the file, getting the number of nodes in the file, and also the specific attributes of some particular node in the file.
Python3
# loading the library and other important packageslibrary("XML")library("methods") # the contents of sample.xml are parsed# Load the packages required to read XML files.library("XML")library("methods") # Give the input file name to the function.res <- xmlParse(file = "sample.xml") # Extract the root node.rootnode <- xmlRoot(res) # number of nodes in the root.nodes <- xmlSize(rootnode) # get entire contents of a recordsecond_node <- rootnode[2] # get 3rd attribute of 4th recordattri <- rootnode[[3]][[4]] cat('number of nodes: ', nodes)print ('details of 2 record: ')print (second_node) # prints the marks of the fourth recordprint ('3rd attribute of 4th record: ', attr)
Output:
[1] number of nodes: 5
[2] details of 2 record:
$STUDENT
2
Brijesh
440
Commerce
[3] 3rd attribute of 4th record: 660
In order to enhance the readability of the data, the XML data can be converted into a data frame consisting of a data frame comprising of rows and columns. R contains an in-built function xmlToDataFrame() which contains as input the XML file and outputs the corresponding data in the form of a data frame. This simulates the easy handling and processing of large amounts of data.
Python3
# Load the required packages.library("XML")library("methods") # Convert the input xml file to a data frame.dataframe <- xmlToDataFrame("sample.xml")print(dataframe)
Output:
ID NAME MARKS BRANCH
1 1 Alia 620 IT
2 2 Brijesh 440 Commerce
3 3 Yash 600 Humanities
4 4 Mallika 660 IT
5 5 Zayn 560 IT
clintra
Picked
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change column name of a given DataFrame in R
Filter data by multiple conditions in R using Dplyr
How to Replace specific values in column in R DataFrame ?
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Loops in R (for, while, repeat)
Adding elements in a vector in R programming - append() method
Group by function in R using Dplyr
How to change Row Names of DataFrame in R ?
Convert Factor to Numeric and Numeric to Factor in R Programming
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Sep, 2021"
},
{
"code": null,
"e": 342,
"s": 28,
"text": "XML which stands for Extensible Markup Language is made up of markup tags, wherein each tag illustrates the information carried by the particular attribute in the XML file. We can work with the XML files using the XML package provided by R. The package has to be explicitly installed using the following command: "
},
{
"code": null,
"e": 366,
"s": 342,
"text": "install.packages(\"XML\")"
},
{
"code": null,
"e": 615,
"s": 366,
"text": "XML files can be created by saving the data with the respective tags containing information about the content and saving it with ‘.xml’.We will use the following XML file ‘sample.xml’ to see the various operations that can be performed on the file:"
},
{
"code": null,
"e": 620,
"s": 615,
"text": "HTML"
},
{
"code": "<RECORDS> <STUDENT> <ID>1</ID> <NAME>Alia</NAME> <MARKS>620</MARKS> <BRANCH>IT</BRANCH> </STUDENT> <STUDENT> <ID>2</ID> <NAME>Brijesh</NAME> <MARKS>440</MARKS> <BRANCH>Commerce</BRANCH> </STUDENT> <STUDENT> <ID>3</ID> <NAME>Yash</NAME> <MARKS>600</MARKS> <BRANCH>Humanities</BRANCH> </STUDENT> <STUDENT> <ID>4</ID> <NAME>Mallika</NAME> <MARKS>660</MARKS> <BRANCH>IT</BRANCH> </STUDENT> <STUDENT> <ID>5</ID> <NAME>Zayn</NAME> <MARKS>560</MARKS> <BRANCH>IT</BRANCH> </STUDENT></RECORDS>",
"e": 1219,
"s": 620,
"text": null
},
{
"code": null,
"e": 1620,
"s": 1219,
"text": "The XML file can be read after installing the package and then parsing it with xmlparse() function, which takes as input the XML file name and prints the content of the file in the form of a list. The file should be located in the current working directory. An additional package named ‘methods’ should also be installed. The following code can be used to read the contents of the file “sample.xml”. "
},
{
"code": null,
"e": 1628,
"s": 1620,
"text": "Python3"
},
{
"code": "# loading the library and other important packageslibrary(\"XML\")library(\"methods\") # the contents of sample.xml are parseddata <- xmlParse(file = \"sample.xml\") print(data)",
"e": 1800,
"s": 1628,
"text": null
},
{
"code": null,
"e": 1808,
"s": 1800,
"text": "Output:"
},
{
"code": null,
"e": 1898,
"s": 1808,
"text": "1\nAlia\n620\nIT\n2\nBrijesh\n440\nCommerce\n3\nYash\n600\nHumanities\n4\nMallika\n660\nIT\n5\nZayn\n560\nIT"
},
{
"code": null,
"e": 2212,
"s": 1898,
"text": "XML files can be parsed and operations can be performed on its various components. There are various in-built functions available in R, to extract the information of the nodes associated with the file, getting the number of nodes in the file, and also the specific attributes of some particular node in the file. "
},
{
"code": null,
"e": 2220,
"s": 2212,
"text": "Python3"
},
{
"code": "# loading the library and other important packageslibrary(\"XML\")library(\"methods\") # the contents of sample.xml are parsed# Load the packages required to read XML files.library(\"XML\")library(\"methods\") # Give the input file name to the function.res <- xmlParse(file = \"sample.xml\") # Extract the root node.rootnode <- xmlRoot(res) # number of nodes in the root.nodes <- xmlSize(rootnode) # get entire contents of a recordsecond_node <- rootnode[2] # get 3rd attribute of 4th recordattri <- rootnode[[3]][[4]] cat('number of nodes: ', nodes)print ('details of 2 record: ')print (second_node) # prints the marks of the fourth recordprint ('3rd attribute of 4th record: ', attr)",
"e": 2896,
"s": 2220,
"text": null
},
{
"code": null,
"e": 2904,
"s": 2896,
"text": "Output:"
},
{
"code": null,
"e": 3037,
"s": 2904,
"text": "[1] number of nodes: 5\n[2] details of 2 record:\n$STUDENT\n 2\n Brijesh\n 440\n Commerce\n[3] 3rd attribute of 4th record: 660"
},
{
"code": null,
"e": 3418,
"s": 3037,
"text": "In order to enhance the readability of the data, the XML data can be converted into a data frame consisting of a data frame comprising of rows and columns. R contains an in-built function xmlToDataFrame() which contains as input the XML file and outputs the corresponding data in the form of a data frame. This simulates the easy handling and processing of large amounts of data. "
},
{
"code": null,
"e": 3426,
"s": 3418,
"text": "Python3"
},
{
"code": "# Load the required packages.library(\"XML\")library(\"methods\") # Convert the input xml file to a data frame.dataframe <- xmlToDataFrame(\"sample.xml\")print(dataframe)",
"e": 3591,
"s": 3426,
"text": null
},
{
"code": null,
"e": 3599,
"s": 3591,
"text": "Output:"
},
{
"code": null,
"e": 3838,
"s": 3599,
"text": " ID NAME MARKS BRANCH \n1 1 Alia 620 IT\n2 2 Brijesh 440 Commerce\n3 3 Yash 600 Humanities\n4 4 Mallika 660 IT\n5 5 Zayn 560 IT"
},
{
"code": null,
"e": 3848,
"s": 3840,
"text": "clintra"
},
{
"code": null,
"e": 3855,
"s": 3848,
"text": "Picked"
},
{
"code": null,
"e": 3866,
"s": 3855,
"text": "R Language"
},
{
"code": null,
"e": 3964,
"s": 3866,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4009,
"s": 3964,
"text": "Change column name of a given DataFrame in R"
},
{
"code": null,
"e": 4061,
"s": 4009,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 4119,
"s": 4061,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 4171,
"s": 4119,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 4229,
"s": 4171,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 4261,
"s": 4229,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 4324,
"s": 4261,
"text": "Adding elements in a vector in R programming - append() method"
},
{
"code": null,
"e": 4359,
"s": 4324,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 4403,
"s": 4359,
"text": "How to change Row Names of DataFrame in R ?"
}
] |
Accessing Data in a MultiIndex DataFrame in Pandas | by B. Chen | Towards Data Science
|
A MultiIndex (also known as a hierarchical index) DataFrame allows you to have multiple columns acting as a row identifier and multiple rows acting as a header identifier. With MultiIndex, you can do some sophisticated data analysis, especially for working with higher dimensional data. Accessing data is the first step when working on a MultiIndex DataFrame.
In this article, you’ll learn how to access data in a MultiIndex DataFrame. This article is structured as follows:
Selecting data via the first level indexSelecting data via multi-level indexSelect a range of data using sliceSelecting all content using slice(None)Using cross-section xs()Using IndexSlice
Selecting data via the first level index
Selecting data via multi-level index
Select a range of data using slice
Selecting all content using slice(None)
Using cross-section xs()
Using IndexSlice
For demonstration, we create a dummy dataset and will load it with the first 2 columns as a row identifier and the first 2 rows as a header identifier.
df = pd.read_csv('dataset.csv', index_col=[0,1], header=[0,1]).sort_index()
Please check out Notebook for the source code.
When it comes to select data on a DataFrame, Pandas loc is one of the top favorites. In a previous article, we have introduced the loc and iloc for selecting data in a general (single-index) DataFrame. Accessing data in a MultiIndex DataFrame can be done in a similar way to a single index DataFrame.
We can pass the first-level label to loc to select data
# Retrieve London's Day weatherdf.loc['London', 'Day']
We can also use : to return all data.
# To get all rows - all Day weatherdf.loc[:, 'Day']
And to get all columns
# To get all columnsdf.loc['London' , :]
Above works as we would expect. However, you may be surprised to find df.loc['London', '2019-07-02'] also works
# This also works>>> df.loc['London' , '2019-07-02']Day Weather Shower Wind SW 16 mph Max Temperature 29Night Weather Heavy rain Wind SW 16 mph Max Temperature 17Name: (London, 2019-07-02), dtype: object
This result can lead to ambiguity in general. In fact, all the above statements are shorthand notations for retrieving data from a MultiIndex DataFrame. For MultiIndex DataFrame, it’s recommended to use a tuple to avoid ambiguity.
Here are equivalent statements using tuple
# Equivalent to df.loc['London', 'Day']df.loc[('London', ) , ('Day', )]# Equivalent to df.loc[:, 'Day']df.loc[:, ('Day',)]# Equivalent to df.loc['London' , :]df.loc[('London', ) , :]# Equivalent to df.loc['London' , '2019-07-02']df.loc[('London' , '2019-07-02')]
If you want to read London’s Day weather on 2019–07–01, you can simply do:
>>> df.loc['London', 'Day'].loc['2019-07-01']Weather ShowerWind SW 16 mphMax Temperature 28Name: 2019-07-01, dtype: object
Note that loc['London', 'Day'] return a DataFrame and loc['2019-07-01'] is called on it to extract the data again. This certainly works, but there is a more effective way using tuples.
>>> df.loc[('London', '2019-07-01'), 'Day']Weather ShowerWind SW 16 mphMax Temperature 28Name: (London, 2019-07-01), dtype: object
MultiIndex keys take the form of tuple. In this case, ('London', '2019-07-01') select the row label and 'Day' select the column.
We can also pass a list of labels to select multiple rows or columns:
# Select multiple rowsdf.loc[ ('London' , ['2019-07-01','2019-07-02'] ) , 'Day']# Select multiple columnsdf.loc[ 'London' , ('Day', ['Weather', 'Wind'])]
Slice (written as start:stop:step) is a powerful technique that allows selecting a range of data. It is very useful when we want to select everything in between two items.
Slicing the first-level index in MultiIndex DataFrame is similar to the way on a single index DataFrame. For example,
df.loc[ 'Cambridge':'Oxford', 'Day']
However, we will be getting a SyntaxError when slicing the multi-level index like below:
# We are getting a SyntaxErrordf.loc[ ('London', '2019-07-01': '2019-07-03'), 'Day']
The correct way to slice a multi-level index is to use tuple:
df.loc[ ('London','2019-07-01'):('London','2019-07-03'), 'Day']
The lower level indexes are not necessary to be the same. For example, we can select the data range from ('Cambridge', '2019-07-01') to ('London', '2019-07-02')
df.loc[ ('Cambridge', '2019-07-01'):('London','2019-07-02'), 'Day']
We can use : to select all content when retrieving data via the first-level index. However, we will be getting SyntaxError when using it with a multi-level index.
# Getting SyntaxErrordf.loc[ ('London', :), 'Day']# Getting SyntaxErrordf.loc[ (: , '2019-07-04'), 'Day']
The correct way to select all content on a specific index level is to use slice(None)
df.loc[ ('London', slice(None)), 'Day']df.loc[ (slice(None) , '2019-07-04'), 'Day']
The xs() method of DataFrame can take a level argument to make selecting data at a particular level of a MultiIndex easier.
df.xs('2019-07-04', level='Date')
xs() also allows selection with multiple keys
df.xs(('London', '2019-07-04'), level=['City','Date'])
You can also select on the columns with xs(), by providing the axis argument.
df.xs('Wind', level=1, axis=1)
Note that the selected column label 'Wind' is not included in the result. To retain the level that was selected, we can pass drop_level=False
df.xs('Wind', level=1, axis=1, drop_level=False)
You can use Pandas IndexSlice to facilitate a more natural syntax.
For example, use : instead of slice(None)
from pandas import IndexSlice as idxdf.loc[ idx[: , '2019-07-04'], 'Day']# Instead of slice(None)# df.loc[ # (slice(None) , '2019-07-04'), # 'Day'# ]
Use IndexSlice for both rows and columns
rows = idx[: , '2019-07-01']cols = idx['Day' , ['Max Temperature','Weather']]df.loc[rows, cols]
Use xs() with IndexSlice for selecting a range of data
rows= ( idx['2019-07-02':'2019-07-04'], 'London')df.xs( rows , level = ['Date','City'])
With MultiIndex, you can do some sophisticated data analysis, especially for working with higher dimensional data. Accessing data is the first step when working with MultiIndex DataFrame. I hope you found this tutorial to access MultiIndex DataFrame useful. I recommend you to check out the documentation to know about other things you can do.
Thanks for reading. Please check out the Notebook for the source code and stay tuned if you are interested in the practical aspect of machine learning.
Pandas cut() function for transforming numerical data into categorical data
Using Pandas method chaining to improve code readability
How to do a Custom Sort on Pandas DataFrame
All the Pandas shift() you should know for data analysis
When to use Pandas transform() function
Pandas concat() tricks you should know
Difference between apply() and transform() in Pandas
All the Pandas merge() you should know
Working with datetime in Pandas DataFrame
Pandas read_csv() tricks you should know
4 tricks you should know to parse date columns with Pandas read_csv()
More tutorials can be found on my Github
|
[
{
"code": null,
"e": 532,
"s": 172,
"text": "A MultiIndex (also known as a hierarchical index) DataFrame allows you to have multiple columns acting as a row identifier and multiple rows acting as a header identifier. With MultiIndex, you can do some sophisticated data analysis, especially for working with higher dimensional data. Accessing data is the first step when working on a MultiIndex DataFrame."
},
{
"code": null,
"e": 647,
"s": 532,
"text": "In this article, you’ll learn how to access data in a MultiIndex DataFrame. This article is structured as follows:"
},
{
"code": null,
"e": 837,
"s": 647,
"text": "Selecting data via the first level indexSelecting data via multi-level indexSelect a range of data using sliceSelecting all content using slice(None)Using cross-section xs()Using IndexSlice"
},
{
"code": null,
"e": 878,
"s": 837,
"text": "Selecting data via the first level index"
},
{
"code": null,
"e": 915,
"s": 878,
"text": "Selecting data via multi-level index"
},
{
"code": null,
"e": 950,
"s": 915,
"text": "Select a range of data using slice"
},
{
"code": null,
"e": 990,
"s": 950,
"text": "Selecting all content using slice(None)"
},
{
"code": null,
"e": 1015,
"s": 990,
"text": "Using cross-section xs()"
},
{
"code": null,
"e": 1032,
"s": 1015,
"text": "Using IndexSlice"
},
{
"code": null,
"e": 1184,
"s": 1032,
"text": "For demonstration, we create a dummy dataset and will load it with the first 2 columns as a row identifier and the first 2 rows as a header identifier."
},
{
"code": null,
"e": 1266,
"s": 1184,
"text": "df = pd.read_csv('dataset.csv', index_col=[0,1], header=[0,1]).sort_index()"
},
{
"code": null,
"e": 1313,
"s": 1266,
"text": "Please check out Notebook for the source code."
},
{
"code": null,
"e": 1614,
"s": 1313,
"text": "When it comes to select data on a DataFrame, Pandas loc is one of the top favorites. In a previous article, we have introduced the loc and iloc for selecting data in a general (single-index) DataFrame. Accessing data in a MultiIndex DataFrame can be done in a similar way to a single index DataFrame."
},
{
"code": null,
"e": 1670,
"s": 1614,
"text": "We can pass the first-level label to loc to select data"
},
{
"code": null,
"e": 1725,
"s": 1670,
"text": "# Retrieve London's Day weatherdf.loc['London', 'Day']"
},
{
"code": null,
"e": 1763,
"s": 1725,
"text": "We can also use : to return all data."
},
{
"code": null,
"e": 1815,
"s": 1763,
"text": "# To get all rows - all Day weatherdf.loc[:, 'Day']"
},
{
"code": null,
"e": 1838,
"s": 1815,
"text": "And to get all columns"
},
{
"code": null,
"e": 1879,
"s": 1838,
"text": "# To get all columnsdf.loc['London' , :]"
},
{
"code": null,
"e": 1991,
"s": 1879,
"text": "Above works as we would expect. However, you may be surprised to find df.loc['London', '2019-07-02'] also works"
},
{
"code": null,
"e": 2301,
"s": 1991,
"text": "# This also works>>> df.loc['London' , '2019-07-02']Day Weather Shower Wind SW 16 mph Max Temperature 29Night Weather Heavy rain Wind SW 16 mph Max Temperature 17Name: (London, 2019-07-02), dtype: object"
},
{
"code": null,
"e": 2532,
"s": 2301,
"text": "This result can lead to ambiguity in general. In fact, all the above statements are shorthand notations for retrieving data from a MultiIndex DataFrame. For MultiIndex DataFrame, it’s recommended to use a tuple to avoid ambiguity."
},
{
"code": null,
"e": 2575,
"s": 2532,
"text": "Here are equivalent statements using tuple"
},
{
"code": null,
"e": 2838,
"s": 2575,
"text": "# Equivalent to df.loc['London', 'Day']df.loc[('London', ) , ('Day', )]# Equivalent to df.loc[:, 'Day']df.loc[:, ('Day',)]# Equivalent to df.loc['London' , :]df.loc[('London', ) , :]# Equivalent to df.loc['London' , '2019-07-02']df.loc[('London' , '2019-07-02')]"
},
{
"code": null,
"e": 2913,
"s": 2838,
"text": "If you want to read London’s Day weather on 2019–07–01, you can simply do:"
},
{
"code": null,
"e": 3074,
"s": 2913,
"text": ">>> df.loc['London', 'Day'].loc['2019-07-01']Weather ShowerWind SW 16 mphMax Temperature 28Name: 2019-07-01, dtype: object"
},
{
"code": null,
"e": 3259,
"s": 3074,
"text": "Note that loc['London', 'Day'] return a DataFrame and loc['2019-07-01'] is called on it to extract the data again. This certainly works, but there is a more effective way using tuples."
},
{
"code": null,
"e": 3428,
"s": 3259,
"text": ">>> df.loc[('London', '2019-07-01'), 'Day']Weather ShowerWind SW 16 mphMax Temperature 28Name: (London, 2019-07-01), dtype: object"
},
{
"code": null,
"e": 3557,
"s": 3428,
"text": "MultiIndex keys take the form of tuple. In this case, ('London', '2019-07-01') select the row label and 'Day' select the column."
},
{
"code": null,
"e": 3627,
"s": 3557,
"text": "We can also pass a list of labels to select multiple rows or columns:"
},
{
"code": null,
"e": 3795,
"s": 3627,
"text": "# Select multiple rowsdf.loc[ ('London' , ['2019-07-01','2019-07-02'] ) , 'Day']# Select multiple columnsdf.loc[ 'London' , ('Day', ['Weather', 'Wind'])]"
},
{
"code": null,
"e": 3967,
"s": 3795,
"text": "Slice (written as start:stop:step) is a powerful technique that allows selecting a range of data. It is very useful when we want to select everything in between two items."
},
{
"code": null,
"e": 4085,
"s": 3967,
"text": "Slicing the first-level index in MultiIndex DataFrame is similar to the way on a single index DataFrame. For example,"
},
{
"code": null,
"e": 4128,
"s": 4085,
"text": "df.loc[ 'Cambridge':'Oxford', 'Day']"
},
{
"code": null,
"e": 4217,
"s": 4128,
"text": "However, we will be getting a SyntaxError when slicing the multi-level index like below:"
},
{
"code": null,
"e": 4308,
"s": 4217,
"text": "# We are getting a SyntaxErrordf.loc[ ('London', '2019-07-01': '2019-07-03'), 'Day']"
},
{
"code": null,
"e": 4370,
"s": 4308,
"text": "The correct way to slice a multi-level index is to use tuple:"
},
{
"code": null,
"e": 4440,
"s": 4370,
"text": "df.loc[ ('London','2019-07-01'):('London','2019-07-03'), 'Day']"
},
{
"code": null,
"e": 4601,
"s": 4440,
"text": "The lower level indexes are not necessary to be the same. For example, we can select the data range from ('Cambridge', '2019-07-01') to ('London', '2019-07-02')"
},
{
"code": null,
"e": 4675,
"s": 4601,
"text": "df.loc[ ('Cambridge', '2019-07-01'):('London','2019-07-02'), 'Day']"
},
{
"code": null,
"e": 4838,
"s": 4675,
"text": "We can use : to select all content when retrieving data via the first-level index. However, we will be getting SyntaxError when using it with a multi-level index."
},
{
"code": null,
"e": 4958,
"s": 4838,
"text": "# Getting SyntaxErrordf.loc[ ('London', :), 'Day']# Getting SyntaxErrordf.loc[ (: , '2019-07-04'), 'Day']"
},
{
"code": null,
"e": 5044,
"s": 4958,
"text": "The correct way to select all content on a specific index level is to use slice(None)"
},
{
"code": null,
"e": 5142,
"s": 5044,
"text": "df.loc[ ('London', slice(None)), 'Day']df.loc[ (slice(None) , '2019-07-04'), 'Day']"
},
{
"code": null,
"e": 5266,
"s": 5142,
"text": "The xs() method of DataFrame can take a level argument to make selecting data at a particular level of a MultiIndex easier."
},
{
"code": null,
"e": 5300,
"s": 5266,
"text": "df.xs('2019-07-04', level='Date')"
},
{
"code": null,
"e": 5346,
"s": 5300,
"text": "xs() also allows selection with multiple keys"
},
{
"code": null,
"e": 5401,
"s": 5346,
"text": "df.xs(('London', '2019-07-04'), level=['City','Date'])"
},
{
"code": null,
"e": 5479,
"s": 5401,
"text": "You can also select on the columns with xs(), by providing the axis argument."
},
{
"code": null,
"e": 5510,
"s": 5479,
"text": "df.xs('Wind', level=1, axis=1)"
},
{
"code": null,
"e": 5652,
"s": 5510,
"text": "Note that the selected column label 'Wind' is not included in the result. To retain the level that was selected, we can pass drop_level=False"
},
{
"code": null,
"e": 5701,
"s": 5652,
"text": "df.xs('Wind', level=1, axis=1, drop_level=False)"
},
{
"code": null,
"e": 5768,
"s": 5701,
"text": "You can use Pandas IndexSlice to facilitate a more natural syntax."
},
{
"code": null,
"e": 5810,
"s": 5768,
"text": "For example, use : instead of slice(None)"
},
{
"code": null,
"e": 5974,
"s": 5810,
"text": "from pandas import IndexSlice as idxdf.loc[ idx[: , '2019-07-04'], 'Day']# Instead of slice(None)# df.loc[ # (slice(None) , '2019-07-04'), # 'Day'# ]"
},
{
"code": null,
"e": 6015,
"s": 5974,
"text": "Use IndexSlice for both rows and columns"
},
{
"code": null,
"e": 6111,
"s": 6015,
"text": "rows = idx[: , '2019-07-01']cols = idx['Day' , ['Max Temperature','Weather']]df.loc[rows, cols]"
},
{
"code": null,
"e": 6166,
"s": 6111,
"text": "Use xs() with IndexSlice for selecting a range of data"
},
{
"code": null,
"e": 6268,
"s": 6166,
"text": "rows= ( idx['2019-07-02':'2019-07-04'], 'London')df.xs( rows , level = ['Date','City'])"
},
{
"code": null,
"e": 6612,
"s": 6268,
"text": "With MultiIndex, you can do some sophisticated data analysis, especially for working with higher dimensional data. Accessing data is the first step when working with MultiIndex DataFrame. I hope you found this tutorial to access MultiIndex DataFrame useful. I recommend you to check out the documentation to know about other things you can do."
},
{
"code": null,
"e": 6764,
"s": 6612,
"text": "Thanks for reading. Please check out the Notebook for the source code and stay tuned if you are interested in the practical aspect of machine learning."
},
{
"code": null,
"e": 6840,
"s": 6764,
"text": "Pandas cut() function for transforming numerical data into categorical data"
},
{
"code": null,
"e": 6897,
"s": 6840,
"text": "Using Pandas method chaining to improve code readability"
},
{
"code": null,
"e": 6941,
"s": 6897,
"text": "How to do a Custom Sort on Pandas DataFrame"
},
{
"code": null,
"e": 6998,
"s": 6941,
"text": "All the Pandas shift() you should know for data analysis"
},
{
"code": null,
"e": 7038,
"s": 6998,
"text": "When to use Pandas transform() function"
},
{
"code": null,
"e": 7077,
"s": 7038,
"text": "Pandas concat() tricks you should know"
},
{
"code": null,
"e": 7130,
"s": 7077,
"text": "Difference between apply() and transform() in Pandas"
},
{
"code": null,
"e": 7169,
"s": 7130,
"text": "All the Pandas merge() you should know"
},
{
"code": null,
"e": 7211,
"s": 7169,
"text": "Working with datetime in Pandas DataFrame"
},
{
"code": null,
"e": 7252,
"s": 7211,
"text": "Pandas read_csv() tricks you should know"
},
{
"code": null,
"e": 7322,
"s": 7252,
"text": "4 tricks you should know to parse date columns with Pandas read_csv()"
}
] |
Tryit Editor v3.7
|
Tryit: Using pseudo-element and HTML class
|
[] |
Java default Keyword
|
❮ Java Keywords
Specify some code to run if there is no case match in a switch block:
int day = 4;
switch (day) {
case 6:
System.out.println("Today is Saturday");
break;
case 7:
System.out.println("Today is Sunday");
break;
default:
System.out.println("Looking forward to the Weekend");
}
/ Outputs "Looking forward to the Weekend"
Try it Yourself »
The default keyword the default block of code in a switch statement.
The default keyword specifies some code to run if there is no case match in the switch.
Note: if the default keyword is used
as the last statement in a switch block, it does not need a break.
Read more about the switch statement in our Java Switch Tutorial.
❮ Java Keywords
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 18,
"s": 0,
"text": "\n❮ Java Keywords\n"
},
{
"code": null,
"e": 88,
"s": 18,
"text": "Specify some code to run if there is no case match in a switch block:"
},
{
"code": null,
"e": 361,
"s": 88,
"text": "int day = 4;\nswitch (day) {\n case 6:\n System.out.println(\"Today is Saturday\");\n break;\n case 7:\n System.out.println(\"Today is Sunday\");\n break;\n default:\n System.out.println(\"Looking forward to the Weekend\");\n}\n/ Outputs \"Looking forward to the Weekend\"\n"
},
{
"code": null,
"e": 381,
"s": 361,
"text": "\nTry it Yourself »\n"
},
{
"code": null,
"e": 450,
"s": 381,
"text": "The default keyword the default block of code in a switch statement."
},
{
"code": null,
"e": 538,
"s": 450,
"text": "The default keyword specifies some code to run if there is no case match in the switch."
},
{
"code": null,
"e": 643,
"s": 538,
"text": "Note: if the default keyword is used \nas the last statement in a switch block, it does not need a break."
},
{
"code": null,
"e": 709,
"s": 643,
"text": "Read more about the switch statement in our Java Switch Tutorial."
},
{
"code": null,
"e": 727,
"s": 709,
"text": "\n❮ Java Keywords\n"
},
{
"code": null,
"e": 760,
"s": 727,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 802,
"s": 760,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 909,
"s": 802,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 928,
"s": 909,
"text": "help@w3schools.com"
}
] |
C++ Program to print an Array using Recursion - GeeksforGeeks
|
11 Oct, 2019
Write a program in C++ to print an Array using Recursion
Using static variable: Static variables have a property of preserving their value even after they are out of their scope! Hence, static variables preserve their previous value in their previous scope and are not initialized again in the new scope.Syntax:static data_type var_name = var_value; // C++ Program to print// an Array using Recursion #include <bits/stdc++.h>using namespace std; // Recursive function to print the arrayvoid print_array(int arr[], int size){ // using the static variable static int i; // base case if (i == size) { i = 0; cout << endl; return; } // print the ith element cout << arr[i] << " "; i++; // recursive call print_array(arr, size);} // Driver codeint main(){ int arr[] = { 3, 5, 6, 8, 1 }; int n = sizeof(arr) / sizeof(arr[0]); print_array(arr, n); return 0;}Output:3 5 6 8 1
Without using Static variable:// C++ Program to print// an Array using Recursion #include <bits/stdc++.h>using namespace std; // Recursive function to print the arrayvoid print_array(int arr[], int size, int i){ // base case if (i == size) { cout << endl; return; } // print the ith element cout << arr[i] << " "; i++; // recursive call print_array(arr, size, i);} // Driver codeint main(){ int arr[] = { 3, 5, 6, 8, 1 }; int n = sizeof(arr) / sizeof(arr[0]); print_array(arr, n, 0); return 0;}Output:3 5 6 8 1
Using static variable: Static variables have a property of preserving their value even after they are out of their scope! Hence, static variables preserve their previous value in their previous scope and are not initialized again in the new scope.Syntax:static data_type var_name = var_value; // C++ Program to print// an Array using Recursion #include <bits/stdc++.h>using namespace std; // Recursive function to print the arrayvoid print_array(int arr[], int size){ // using the static variable static int i; // base case if (i == size) { i = 0; cout << endl; return; } // print the ith element cout << arr[i] << " "; i++; // recursive call print_array(arr, size);} // Driver codeint main(){ int arr[] = { 3, 5, 6, 8, 1 }; int n = sizeof(arr) / sizeof(arr[0]); print_array(arr, n); return 0;}Output:3 5 6 8 1
Syntax:
static data_type var_name = var_value;
// C++ Program to print// an Array using Recursion #include <bits/stdc++.h>using namespace std; // Recursive function to print the arrayvoid print_array(int arr[], int size){ // using the static variable static int i; // base case if (i == size) { i = 0; cout << endl; return; } // print the ith element cout << arr[i] << " "; i++; // recursive call print_array(arr, size);} // Driver codeint main(){ int arr[] = { 3, 5, 6, 8, 1 }; int n = sizeof(arr) / sizeof(arr[0]); print_array(arr, n); return 0;}
3 5 6 8 1
Without using Static variable:// C++ Program to print// an Array using Recursion #include <bits/stdc++.h>using namespace std; // Recursive function to print the arrayvoid print_array(int arr[], int size, int i){ // base case if (i == size) { cout << endl; return; } // print the ith element cout << arr[i] << " "; i++; // recursive call print_array(arr, size, i);} // Driver codeint main(){ int arr[] = { 3, 5, 6, 8, 1 }; int n = sizeof(arr) / sizeof(arr[0]); print_array(arr, n, 0); return 0;}Output:3 5 6 8 1
// C++ Program to print// an Array using Recursion #include <bits/stdc++.h>using namespace std; // Recursive function to print the arrayvoid print_array(int arr[], int size, int i){ // base case if (i == size) { cout << endl; return; } // print the ith element cout << arr[i] << " "; i++; // recursive call print_array(arr, size, i);} // Driver codeint main(){ int arr[] = { 3, 5, 6, 8, 1 }; int n = sizeof(arr) / sizeof(arr[0]); print_array(arr, n, 0); return 0;}
3 5 6 8 1
Arrays
C++
Recursion
Arrays
Recursion
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Next Greater Element
Window Sliding Technique
Count pairs with given sum
Program to find sum of elements in a given array
Reversal algorithm for array rotation
Vector in C++ STL
Initialize a vector in C++ (6 different ways)
Map in C++ Standard Template Library (STL)
Inheritance in C++
std::sort() in C++ STL
|
[
{
"code": null,
"e": 24429,
"s": 24401,
"text": "\n11 Oct, 2019"
},
{
"code": null,
"e": 24486,
"s": 24429,
"text": "Write a program in C++ to print an Array using Recursion"
},
{
"code": null,
"e": 25954,
"s": 24486,
"text": "Using static variable: Static variables have a property of preserving their value even after they are out of their scope! Hence, static variables preserve their previous value in their previous scope and are not initialized again in the new scope.Syntax:static data_type var_name = var_value; // C++ Program to print// an Array using Recursion #include <bits/stdc++.h>using namespace std; // Recursive function to print the arrayvoid print_array(int arr[], int size){ // using the static variable static int i; // base case if (i == size) { i = 0; cout << endl; return; } // print the ith element cout << arr[i] << \" \"; i++; // recursive call print_array(arr, size);} // Driver codeint main(){ int arr[] = { 3, 5, 6, 8, 1 }; int n = sizeof(arr) / sizeof(arr[0]); print_array(arr, n); return 0;}Output:3 5 6 8 1\nWithout using Static variable:// C++ Program to print// an Array using Recursion #include <bits/stdc++.h>using namespace std; // Recursive function to print the arrayvoid print_array(int arr[], int size, int i){ // base case if (i == size) { cout << endl; return; } // print the ith element cout << arr[i] << \" \"; i++; // recursive call print_array(arr, size, i);} // Driver codeint main(){ int arr[] = { 3, 5, 6, 8, 1 }; int n = sizeof(arr) / sizeof(arr[0]); print_array(arr, n, 0); return 0;}Output:3 5 6 8 1\n"
},
{
"code": null,
"e": 26846,
"s": 25954,
"text": "Using static variable: Static variables have a property of preserving their value even after they are out of their scope! Hence, static variables preserve their previous value in their previous scope and are not initialized again in the new scope.Syntax:static data_type var_name = var_value; // C++ Program to print// an Array using Recursion #include <bits/stdc++.h>using namespace std; // Recursive function to print the arrayvoid print_array(int arr[], int size){ // using the static variable static int i; // base case if (i == size) { i = 0; cout << endl; return; } // print the ith element cout << arr[i] << \" \"; i++; // recursive call print_array(arr, size);} // Driver codeint main(){ int arr[] = { 3, 5, 6, 8, 1 }; int n = sizeof(arr) / sizeof(arr[0]); print_array(arr, n); return 0;}Output:3 5 6 8 1\n"
},
{
"code": null,
"e": 26854,
"s": 26846,
"text": "Syntax:"
},
{
"code": null,
"e": 26894,
"s": 26854,
"text": "static data_type var_name = var_value; "
},
{
"code": "// C++ Program to print// an Array using Recursion #include <bits/stdc++.h>using namespace std; // Recursive function to print the arrayvoid print_array(int arr[], int size){ // using the static variable static int i; // base case if (i == size) { i = 0; cout << endl; return; } // print the ith element cout << arr[i] << \" \"; i++; // recursive call print_array(arr, size);} // Driver codeint main(){ int arr[] = { 3, 5, 6, 8, 1 }; int n = sizeof(arr) / sizeof(arr[0]); print_array(arr, n); return 0;}",
"e": 27476,
"s": 26894,
"text": null
},
{
"code": null,
"e": 27487,
"s": 27476,
"text": "3 5 6 8 1\n"
},
{
"code": null,
"e": 28064,
"s": 27487,
"text": "Without using Static variable:// C++ Program to print// an Array using Recursion #include <bits/stdc++.h>using namespace std; // Recursive function to print the arrayvoid print_array(int arr[], int size, int i){ // base case if (i == size) { cout << endl; return; } // print the ith element cout << arr[i] << \" \"; i++; // recursive call print_array(arr, size, i);} // Driver codeint main(){ int arr[] = { 3, 5, 6, 8, 1 }; int n = sizeof(arr) / sizeof(arr[0]); print_array(arr, n, 0); return 0;}Output:3 5 6 8 1\n"
},
{
"code": "// C++ Program to print// an Array using Recursion #include <bits/stdc++.h>using namespace std; // Recursive function to print the arrayvoid print_array(int arr[], int size, int i){ // base case if (i == size) { cout << endl; return; } // print the ith element cout << arr[i] << \" \"; i++; // recursive call print_array(arr, size, i);} // Driver codeint main(){ int arr[] = { 3, 5, 6, 8, 1 }; int n = sizeof(arr) / sizeof(arr[0]); print_array(arr, n, 0); return 0;}",
"e": 28594,
"s": 28064,
"text": null
},
{
"code": null,
"e": 28605,
"s": 28594,
"text": "3 5 6 8 1\n"
},
{
"code": null,
"e": 28612,
"s": 28605,
"text": "Arrays"
},
{
"code": null,
"e": 28616,
"s": 28612,
"text": "C++"
},
{
"code": null,
"e": 28626,
"s": 28616,
"text": "Recursion"
},
{
"code": null,
"e": 28633,
"s": 28626,
"text": "Arrays"
},
{
"code": null,
"e": 28643,
"s": 28633,
"text": "Recursion"
},
{
"code": null,
"e": 28647,
"s": 28643,
"text": "CPP"
},
{
"code": null,
"e": 28745,
"s": 28647,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28754,
"s": 28745,
"text": "Comments"
},
{
"code": null,
"e": 28767,
"s": 28754,
"text": "Old Comments"
},
{
"code": null,
"e": 28788,
"s": 28767,
"text": "Next Greater Element"
},
{
"code": null,
"e": 28813,
"s": 28788,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 28840,
"s": 28813,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 28889,
"s": 28840,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 28927,
"s": 28889,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 28945,
"s": 28927,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 28991,
"s": 28945,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 29034,
"s": 28991,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 29053,
"s": 29034,
"text": "Inheritance in C++"
}
] |
How to Set Up a Foreign Data Wrapper in PostgreSQL | by Eve Ben Ezra | Towards Data Science
|
A foreign data wrapper is an extension available in PostgreSQL that allows you to access a table or schema in one database from another. Foreign data wrappers can serve all sorts of purposes:
Completing a data flow cycle
Your data may be segregated across databases, but still related in ways that makes being able to combine or aggregate it desirable
Allows you to control the permissions on the foreign tables
Let’s go!
For this example, we’ll use the databases localdb and foreigndb. I want to access a table account_metrics in foreigndb from localdb:
postgres=# \lList of databasesName | Owner | Encoding | Collate | Ctype | Access privileges-----------+----------+----------+---------+-------+-----------------------localdb | postgres | UTF8 | C | C |foreigndb | postgres | UTF8 | C | C |(2 rows)
And a look at the account_metrics table:
foreigndb=# select * from account_metrics;id | time_spent | pages_viewed----+------------+--------------1 | 60 | 52 | 100 | 23 | 15 | 5(3 rows)
For security reasons, you’ll likely want to create a read-only user to act as the go-between. This foreign user is the user that we’ll use for user mapping, which will be discussed later in this article.
Let’s create a user fdwUser . Then, in the foreign database (foreigndb) we’ll grant this user read-only access to the table in question, and usage on the schema where our table lives (in this case public )
foreigndb=# CREATE USER fdwUser WITH PASSWORD 'secret';CREATE ROLEforeigndb=# GRANT USAGE ON SCHEMA PUBLIC TO fdwUser;GRANTforeigndb=# GRANT SELECT ON account_metrics TO fdwUser;GRANT
When our foreign data wrapper is set up, we’ll need the foreign server to prompt the user for a password. This is configured in pg_hba.conf
First, find where your pg_hba.conf is located. The most common installations for postgreSQL are homebrew and EnterpriseDB. However, the easiest way to find your data directory (where pg_hba.conf is located) is to query it directly in a psql instance:
foreigndb=# SHOW hba_file;hba_file-----------------------------------------/Library/PostgreSQL/11/data/pg_hba.conf(1 row)foreigndb=# SHOW data_directory;data_directory-----------------------------/Library/PostgreSQL/11/data(1 row)
Depending on your OS, you may need to log in as root to access /Library/PostgreSQL/11/data by logging in as sudo su - . Brew installations won’t require you to log in as the superuser.
Next, open pg_hba.conf in your text editor of choice. Under IPv4 local connections add a line for the foreign database using the read-only user. A record can have one of 7 formats, see the documentation for more information:
# IPv4 local connections:host foreigndb fdwuser 127.0.0.1/32 md5
Save the file and exit. If you logged in as root, logout using ctrl + d. Now you need to signal the server to reload the configuration file. Depending on how you’ve set up your databases, you’ll likely need to do this as the postgres user by using sudo -u postgres:
user$ sudo -u postgres pg_ctl reload -D /Library/PostgreSQL/11/data/server signaled
Now connect to localdb and create the foreign data wrapper extension by running CREATE EXTENSION postgres_fdw; or CREATE EXTENSION IF NOT EXISTS postgres_fdw;
localdb=# CREATE EXTENSION IF NOT EXISTS postgres_fdw;CREATE EXTENSION
Check that worked by querying the database’s extensions:
localdb=# select * from pg_extension;extname | extowner | extnamespace | extrelocatable | extversion | extconfig | extcondition--------------+----------+--------------+----------------+------------+-----------+--------------plpgsql | 10 | 11 | f | 1.0 | |postgres_fdw | 10 | 2200 | t | 1.0 | |(2 rows)
Now we’re going to create the foreign server that we’ll import the foreign schema into. You can name this whatever you want. In this example I’ll name this oneforeigndb_fdw . We’ll create the server with OPTIONS for our host, port, and the name of the foreign database as follows:
localdb=# CREATE SERVER foreigndb_fdw FOREIGN DATA WRAPPER postgres_fdw OPTIONS (host '127.0.0.1', port '5432', dbname 'foreigndb');CREATE SERVER
Let’s check and make sure that worked:
If you’re using psql you can use \des in the working database to list your foreign servers. You can also query it from pg_foreign_server :
localdb=# \desList of foreign serversName | Owner | Foreign-data wrapper---------------+----------+----------------------foreigndb_fdw | postgres | postgres_fdw(1 row)localdb=# select * from pg_foreign_server;srvname | srvowner | srvfdw | srvtype | srvversion | srvacl | srvoptions---------------+----------+--------+---------+------------+--------+---------------------------------------------foreigndb_fdw | 10 | 41198 | | | | {host=127.0.0.1,port=5432,dbname=foreigndb}(1 row)
Now we’re going to create the user mapping. Let’s say that all of the objects and tables in localdb are owned by localuser . We’re going to create the user mapping for the foreign schema for this user as well. I don’t recommend setting up user mapping for the postgres superuser.
localdb=# CREATE USER MAPPING FOR localuser SERVER foreigndb_fdw OPTIONS (user 'fdwuser', password 'secret');CREATE USER MAPPING
Now, let’s check and make sure that worked by querying pg_user_mapping (restricted for users that are not the superuser) or pg_user_mappings which is not restricted:
localdb=# select * from pg_user_mapping;umuser | umserver | umoptions--------+----------+--------------------------------41201 | 41199 | {user=fdwuser,password=secret}(1 row)localdb=# select * from pg_user_mappings;umid | srvid | srvname | umuser | usename | umoptions-------+-------+---------------+--------+-----------+--------------------------------41202 | 41199 | foreigndb_fdw | 41201 | localuser | {user=fdwuser,password=secret}(1 row)
An important note about the fdwuser and its password
As we set up pg_hba.conf earlier to be md5 for this connection, we will need to supply a password. That password is required to be passed in to the usermapping. That password, as you can see above, is stored in plaintext in pg_user_mapping and pg_user_mappings. This can make things a little tricky if you have multiple environments, so you’ll need to give the fdwUser the same password in each environment. Otherwise, you will need to explicitly drop and recreate the FDW if you want the password to be different across environments. This is one reason why this user should not have write permission for tables, to help prevent injection attack. Make sure the password you’re using has high entropy and make sure you’re using unique passwords for all of your database users. If needed, set up a .pgpass file so you don’t need to remember them all.
As we aren’t creating user mapping for the postgres superuser, we’ll need to grant our local user localuser access to the foreign data wrapper. Logged in as the postgres user in localdb do the following:
localdb=# GRANT USAGE ON FOREIGN SERVER foreigndb_fdw TO localuser;GRANT
Now we should be able to import the foreign schema as localuser .
Now it’s finally time to import the foreign schema. In this case, we’ll import the public schema and limit it to the table that we’d like. I’m going to import this into the public schema of the local database, but you may want to create a different schema specifically for foreign tables. If you do so, you will need to use schema-qualified language when querying the foreign table.
Postgres also allows for you to create foreign tables that are mirrors of tables in the foreign database, or import only some columns from a foreign table. For more information, see the documentation.
Log in as localuser and import the foreigndb’s public schema:
user$ psql -U localuser -d localdbPassword for user localuser:psql (11.1)Type "help" for help.localdb=> IMPORT FOREIGN SCHEMA public LIMIT TO (account_metrics) FROM SERVER foreigndb_fdw INTO public;IMPORT FOREIGN SCHEMA
The localuser now has read-only access to the account_metrics table located in foreigndb :
localdb=> select * from account_metrics;id | time_spent | pages_viewed----+------------+--------------1 | 60 | 52 | 100 | 23 | 15 | 5(3 rows)
What about other access? Test that you’re read-only by trying to insert a row into the foreign table:
localdb=> INSERT INTO account_metrics(time_spent,pages_viewed) VALUES (10,1);ERROR: permission denied for table account_metricsCONTEXT: remote SQL command: INSERT INTO public.account_metrics(id, time_spent, pages_viewed) VALUES ($1, $2, $3)
As well, you can confirm that you can only access this table as the localuser and not the postgres user:
user$ psql -U postgres -d localdbpsql (11.1)Type "help" for help.localdb=# select * from account_metrics;ERROR: user mapping not found for "postgres"
Query away!
The easiest way I’ve found to completely delete a foreign data wrapper (and drop the FDW user) is by dropping the extension using CASCADE, revoking the permissions for the read-only user, and dropping any owned objects that depend on the read-only user. Don’t be alarmed, doing this won’t drop the original table from foreigndb :
user$ psql -U postgres -d localdbpsql (11.1)Type "help" for help.localdb=# DROP EXTENSION IF EXISTS postgres_fdw CASCADE;NOTICE: drop cascades to 3 other objectsDETAIL: drop cascades to server foreigndb_fdwdrop cascades to user mapping for localuser on server foreigndb_fdwdrop cascades to foreign table account_metricsDROP EXTENSIONlocaldb=# REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA public FROM fdwuser;REVOKElocaldb=# DROP OWNED BY fdwuser;DROP OWNEDlocaldb=# \c foreigndbYou are now connected to database "foreigndb" as user "postgres".foreigndb=# REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA public FROM fdwuser;REVOKEforeigndb=# DROP OWNED BY fdwuser;DROP OWNEDforeigndb=# DROP ROLE fdwuser;DROP ROLE
And that’s all there is to it! You’ve now completed your foreign data wrapper, and can freely query your imported foreign schema remotely.
Enjoy your newfound powers!
|
[
{
"code": null,
"e": 364,
"s": 172,
"text": "A foreign data wrapper is an extension available in PostgreSQL that allows you to access a table or schema in one database from another. Foreign data wrappers can serve all sorts of purposes:"
},
{
"code": null,
"e": 393,
"s": 364,
"text": "Completing a data flow cycle"
},
{
"code": null,
"e": 524,
"s": 393,
"text": "Your data may be segregated across databases, but still related in ways that makes being able to combine or aggregate it desirable"
},
{
"code": null,
"e": 584,
"s": 524,
"text": "Allows you to control the permissions on the foreign tables"
},
{
"code": null,
"e": 594,
"s": 584,
"text": "Let’s go!"
},
{
"code": null,
"e": 727,
"s": 594,
"text": "For this example, we’ll use the databases localdb and foreigndb. I want to access a table account_metrics in foreigndb from localdb:"
},
{
"code": null,
"e": 1010,
"s": 727,
"text": "postgres=# \\lList of databasesName | Owner | Encoding | Collate | Ctype | Access privileges-----------+----------+----------+---------+-------+-----------------------localdb | postgres | UTF8 | C | C |foreigndb | postgres | UTF8 | C | C |(2 rows)"
},
{
"code": null,
"e": 1051,
"s": 1010,
"text": "And a look at the account_metrics table:"
},
{
"code": null,
"e": 1251,
"s": 1051,
"text": "foreigndb=# select * from account_metrics;id | time_spent | pages_viewed----+------------+--------------1 | 60 | 52 | 100 | 23 | 15 | 5(3 rows)"
},
{
"code": null,
"e": 1455,
"s": 1251,
"text": "For security reasons, you’ll likely want to create a read-only user to act as the go-between. This foreign user is the user that we’ll use for user mapping, which will be discussed later in this article."
},
{
"code": null,
"e": 1661,
"s": 1455,
"text": "Let’s create a user fdwUser . Then, in the foreign database (foreigndb) we’ll grant this user read-only access to the table in question, and usage on the schema where our table lives (in this case public )"
},
{
"code": null,
"e": 1845,
"s": 1661,
"text": "foreigndb=# CREATE USER fdwUser WITH PASSWORD 'secret';CREATE ROLEforeigndb=# GRANT USAGE ON SCHEMA PUBLIC TO fdwUser;GRANTforeigndb=# GRANT SELECT ON account_metrics TO fdwUser;GRANT"
},
{
"code": null,
"e": 1985,
"s": 1845,
"text": "When our foreign data wrapper is set up, we’ll need the foreign server to prompt the user for a password. This is configured in pg_hba.conf"
},
{
"code": null,
"e": 2236,
"s": 1985,
"text": "First, find where your pg_hba.conf is located. The most common installations for postgreSQL are homebrew and EnterpriseDB. However, the easiest way to find your data directory (where pg_hba.conf is located) is to query it directly in a psql instance:"
},
{
"code": null,
"e": 2467,
"s": 2236,
"text": "foreigndb=# SHOW hba_file;hba_file-----------------------------------------/Library/PostgreSQL/11/data/pg_hba.conf(1 row)foreigndb=# SHOW data_directory;data_directory-----------------------------/Library/PostgreSQL/11/data(1 row)"
},
{
"code": null,
"e": 2652,
"s": 2467,
"text": "Depending on your OS, you may need to log in as root to access /Library/PostgreSQL/11/data by logging in as sudo su - . Brew installations won’t require you to log in as the superuser."
},
{
"code": null,
"e": 2877,
"s": 2652,
"text": "Next, open pg_hba.conf in your text editor of choice. Under IPv4 local connections add a line for the foreign database using the read-only user. A record can have one of 7 formats, see the documentation for more information:"
},
{
"code": null,
"e": 2970,
"s": 2877,
"text": "# IPv4 local connections:host foreigndb fdwuser 127.0.0.1/32 md5"
},
{
"code": null,
"e": 3236,
"s": 2970,
"text": "Save the file and exit. If you logged in as root, logout using ctrl + d. Now you need to signal the server to reload the configuration file. Depending on how you’ve set up your databases, you’ll likely need to do this as the postgres user by using sudo -u postgres:"
},
{
"code": null,
"e": 3320,
"s": 3236,
"text": "user$ sudo -u postgres pg_ctl reload -D /Library/PostgreSQL/11/data/server signaled"
},
{
"code": null,
"e": 3479,
"s": 3320,
"text": "Now connect to localdb and create the foreign data wrapper extension by running CREATE EXTENSION postgres_fdw; or CREATE EXTENSION IF NOT EXISTS postgres_fdw;"
},
{
"code": null,
"e": 3550,
"s": 3479,
"text": "localdb=# CREATE EXTENSION IF NOT EXISTS postgres_fdw;CREATE EXTENSION"
},
{
"code": null,
"e": 3607,
"s": 3550,
"text": "Check that worked by querying the database’s extensions:"
},
{
"code": null,
"e": 4007,
"s": 3607,
"text": "localdb=# select * from pg_extension;extname | extowner | extnamespace | extrelocatable | extversion | extconfig | extcondition--------------+----------+--------------+----------------+------------+-----------+--------------plpgsql | 10 | 11 | f | 1.0 | |postgres_fdw | 10 | 2200 | t | 1.0 | |(2 rows)"
},
{
"code": null,
"e": 4288,
"s": 4007,
"text": "Now we’re going to create the foreign server that we’ll import the foreign schema into. You can name this whatever you want. In this example I’ll name this oneforeigndb_fdw . We’ll create the server with OPTIONS for our host, port, and the name of the foreign database as follows:"
},
{
"code": null,
"e": 4434,
"s": 4288,
"text": "localdb=# CREATE SERVER foreigndb_fdw FOREIGN DATA WRAPPER postgres_fdw OPTIONS (host '127.0.0.1', port '5432', dbname 'foreigndb');CREATE SERVER"
},
{
"code": null,
"e": 4473,
"s": 4434,
"text": "Let’s check and make sure that worked:"
},
{
"code": null,
"e": 4612,
"s": 4473,
"text": "If you’re using psql you can use \\des in the working database to list your foreign servers. You can also query it from pg_foreign_server :"
},
{
"code": null,
"e": 5152,
"s": 4612,
"text": "localdb=# \\desList of foreign serversName | Owner | Foreign-data wrapper---------------+----------+----------------------foreigndb_fdw | postgres | postgres_fdw(1 row)localdb=# select * from pg_foreign_server;srvname | srvowner | srvfdw | srvtype | srvversion | srvacl | srvoptions---------------+----------+--------+---------+------------+--------+---------------------------------------------foreigndb_fdw | 10 | 41198 | | | | {host=127.0.0.1,port=5432,dbname=foreigndb}(1 row)"
},
{
"code": null,
"e": 5432,
"s": 5152,
"text": "Now we’re going to create the user mapping. Let’s say that all of the objects and tables in localdb are owned by localuser . We’re going to create the user mapping for the foreign schema for this user as well. I don’t recommend setting up user mapping for the postgres superuser."
},
{
"code": null,
"e": 5561,
"s": 5432,
"text": "localdb=# CREATE USER MAPPING FOR localuser SERVER foreigndb_fdw OPTIONS (user 'fdwuser', password 'secret');CREATE USER MAPPING"
},
{
"code": null,
"e": 5727,
"s": 5561,
"text": "Now, let’s check and make sure that worked by querying pg_user_mapping (restricted for users that are not the superuser) or pg_user_mappings which is not restricted:"
},
{
"code": null,
"e": 6203,
"s": 5727,
"text": "localdb=# select * from pg_user_mapping;umuser | umserver | umoptions--------+----------+--------------------------------41201 | 41199 | {user=fdwuser,password=secret}(1 row)localdb=# select * from pg_user_mappings;umid | srvid | srvname | umuser | usename | umoptions-------+-------+---------------+--------+-----------+--------------------------------41202 | 41199 | foreigndb_fdw | 41201 | localuser | {user=fdwuser,password=secret}(1 row)"
},
{
"code": null,
"e": 6256,
"s": 6203,
"text": "An important note about the fdwuser and its password"
},
{
"code": null,
"e": 7105,
"s": 6256,
"text": "As we set up pg_hba.conf earlier to be md5 for this connection, we will need to supply a password. That password is required to be passed in to the usermapping. That password, as you can see above, is stored in plaintext in pg_user_mapping and pg_user_mappings. This can make things a little tricky if you have multiple environments, so you’ll need to give the fdwUser the same password in each environment. Otherwise, you will need to explicitly drop and recreate the FDW if you want the password to be different across environments. This is one reason why this user should not have write permission for tables, to help prevent injection attack. Make sure the password you’re using has high entropy and make sure you’re using unique passwords for all of your database users. If needed, set up a .pgpass file so you don’t need to remember them all."
},
{
"code": null,
"e": 7309,
"s": 7105,
"text": "As we aren’t creating user mapping for the postgres superuser, we’ll need to grant our local user localuser access to the foreign data wrapper. Logged in as the postgres user in localdb do the following:"
},
{
"code": null,
"e": 7382,
"s": 7309,
"text": "localdb=# GRANT USAGE ON FOREIGN SERVER foreigndb_fdw TO localuser;GRANT"
},
{
"code": null,
"e": 7448,
"s": 7382,
"text": "Now we should be able to import the foreign schema as localuser ."
},
{
"code": null,
"e": 7831,
"s": 7448,
"text": "Now it’s finally time to import the foreign schema. In this case, we’ll import the public schema and limit it to the table that we’d like. I’m going to import this into the public schema of the local database, but you may want to create a different schema specifically for foreign tables. If you do so, you will need to use schema-qualified language when querying the foreign table."
},
{
"code": null,
"e": 8032,
"s": 7831,
"text": "Postgres also allows for you to create foreign tables that are mirrors of tables in the foreign database, or import only some columns from a foreign table. For more information, see the documentation."
},
{
"code": null,
"e": 8094,
"s": 8032,
"text": "Log in as localuser and import the foreigndb’s public schema:"
},
{
"code": null,
"e": 8314,
"s": 8094,
"text": "user$ psql -U localuser -d localdbPassword for user localuser:psql (11.1)Type \"help\" for help.localdb=> IMPORT FOREIGN SCHEMA public LIMIT TO (account_metrics) FROM SERVER foreigndb_fdw INTO public;IMPORT FOREIGN SCHEMA"
},
{
"code": null,
"e": 8405,
"s": 8314,
"text": "The localuser now has read-only access to the account_metrics table located in foreigndb :"
},
{
"code": null,
"e": 8603,
"s": 8405,
"text": "localdb=> select * from account_metrics;id | time_spent | pages_viewed----+------------+--------------1 | 60 | 52 | 100 | 23 | 15 | 5(3 rows)"
},
{
"code": null,
"e": 8705,
"s": 8603,
"text": "What about other access? Test that you’re read-only by trying to insert a row into the foreign table:"
},
{
"code": null,
"e": 8948,
"s": 8705,
"text": "localdb=> INSERT INTO account_metrics(time_spent,pages_viewed) VALUES (10,1);ERROR: permission denied for table account_metricsCONTEXT: remote SQL command: INSERT INTO public.account_metrics(id, time_spent, pages_viewed) VALUES ($1, $2, $3)"
},
{
"code": null,
"e": 9053,
"s": 8948,
"text": "As well, you can confirm that you can only access this table as the localuser and not the postgres user:"
},
{
"code": null,
"e": 9204,
"s": 9053,
"text": "user$ psql -U postgres -d localdbpsql (11.1)Type \"help\" for help.localdb=# select * from account_metrics;ERROR: user mapping not found for \"postgres\""
},
{
"code": null,
"e": 9216,
"s": 9204,
"text": "Query away!"
},
{
"code": null,
"e": 9546,
"s": 9216,
"text": "The easiest way I’ve found to completely delete a foreign data wrapper (and drop the FDW user) is by dropping the extension using CASCADE, revoking the permissions for the read-only user, and dropping any owned objects that depend on the read-only user. Don’t be alarmed, doing this won’t drop the original table from foreigndb :"
},
{
"code": null,
"e": 10260,
"s": 9546,
"text": "user$ psql -U postgres -d localdbpsql (11.1)Type \"help\" for help.localdb=# DROP EXTENSION IF EXISTS postgres_fdw CASCADE;NOTICE: drop cascades to 3 other objectsDETAIL: drop cascades to server foreigndb_fdwdrop cascades to user mapping for localuser on server foreigndb_fdwdrop cascades to foreign table account_metricsDROP EXTENSIONlocaldb=# REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA public FROM fdwuser;REVOKElocaldb=# DROP OWNED BY fdwuser;DROP OWNEDlocaldb=# \\c foreigndbYou are now connected to database \"foreigndb\" as user \"postgres\".foreigndb=# REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA public FROM fdwuser;REVOKEforeigndb=# DROP OWNED BY fdwuser;DROP OWNEDforeigndb=# DROP ROLE fdwuser;DROP ROLE"
},
{
"code": null,
"e": 10399,
"s": 10260,
"text": "And that’s all there is to it! You’ve now completed your foreign data wrapper, and can freely query your imported foreign schema remotely."
}
] |
OpenNLP - Tokenization
|
The process of chopping the given sentence into smaller parts (tokens) is known as tokenization. In general, the given raw text is tokenized based on a set of delimiters (mostly whitespaces).
Tokenization is used in tasks such as spell-checking, processing searches, identifying parts of speech, sentence detection, document classification of documents, etc.
The opennlp.tools.tokenize package contains the classes and interfaces that are used to perform tokenization.
To tokenize the given sentences into simpler fragments, the OpenNLP library provides three different classes −
SimpleTokenizer − This class tokenizes the given raw text using character classes.
SimpleTokenizer − This class tokenizes the given raw text using character classes.
WhitespaceTokenizer − This class uses whitespaces to tokenize the given text.
WhitespaceTokenizer − This class uses whitespaces to tokenize the given text.
TokenizerME − This class converts raw text into separate tokens. It uses Maximum Entropy to make its decisions.
TokenizerME − This class converts raw text into separate tokens. It uses Maximum Entropy to make its decisions.
To tokenize a sentence using the SimpleTokenizer class, you need to −
Create an object of the respective class.
Create an object of the respective class.
Tokenize the sentence using the tokenize() method.
Tokenize the sentence using the tokenize() method.
Print the tokens.
Print the tokens.
Following are the steps to be followed to write a program which tokenizes the given raw text.
Step 1 − Instantiating the respective class
In both the classes, there are no constructors available to instantiate them. Therefore, we need to create objects of these classes using the static variable INSTANCE.
SimpleTokenizer tokenizer = SimpleTokenizer.INSTANCE;
Step 2 − Tokenize the sentences
Both these classes contain a method called tokenize(). This method accepts a raw text in String format. On invoking, it tokenizes the given String and returns an array of Strings (tokens).
Tokenize the sentence using the tokenizer() method as shown below.
//Tokenizing the given sentence
String tokens[] = tokenizer.tokenize(sentence);
Step 3 − Print the tokens
After tokenizing the sentence, you can print the tokens using for loop, as shown below.
//Printing the tokens
for(String token : tokens)
System.out.println(token);
Example
Following is the program which tokenizes the given sentence using the SimpleTokenizer class. Save this program in a file with the name SimpleTokenizerExample.java.
import opennlp.tools.tokenize.SimpleTokenizer;
public class SimpleTokenizerExample {
public static void main(String args[]){
String sentence = "Hi. How are you? Welcome to Tutorialspoint. "
+ "We provide free tutorials on various technologies";
//Instantiating SimpleTokenizer class
SimpleTokenizer simpleTokenizer = SimpleTokenizer.INSTANCE;
//Tokenizing the given sentence
String tokens[] = simpleTokenizer.tokenize(sentence);
//Printing the tokens
for(String token : tokens) {
System.out.println(token);
}
}
}
Compile and execute the saved Java file from the Command prompt using the following commands −
javac SimpleTokenizerExample.java
java SimpleTokenizerExample
On executing, the above program reads the given String (raw text), tokenizes it, and displays the following output −
Hi
.
How
are
you
?
Welcome
to
Tutorialspoint
.
We
provide
free
tutorials
on
various
technologies
To tokenize a sentence using the WhitespaceTokenizer class, you need to −
Create an object of the respective class.
Create an object of the respective class.
Tokenize the sentence using the tokenize() method.
Tokenize the sentence using the tokenize() method.
Print the tokens.
Print the tokens.
Following are the steps to be followed to write a program which tokenizes the given raw text.
Step 1 − Instantiating the respective class
In both the classes, there are no constructors available to instantiate them. Therefore, we need to create objects of these classes using the static variable INSTANCE.
WhitespaceTokenizer tokenizer = WhitespaceTokenizer.INSTANCE;
Step 2 − Tokenize the sentences
Both these classes contain a method called tokenize(). This method accepts a raw text in String format. On invoking, it tokenizes the given String and returns an array of Strings (tokens).
Tokenize the sentence using the tokenizer() method as shown below.
//Tokenizing the given sentence
String tokens[] = tokenizer.tokenize(sentence);
Step 3 − Print the tokens
After tokenizing the sentence, you can print the tokens using for loop, as shown below.
//Printing the tokens
for(String token : tokens)
System.out.println(token);
Example
Following is the program which tokenizes the given sentence using the WhitespaceTokenizer class. Save this program in a file with the name WhitespaceTokenizerExample.java.
import opennlp.tools.tokenize.WhitespaceTokenizer;
public class WhitespaceTokenizerExample {
public static void main(String args[]){
String sentence = "Hi. How are you? Welcome to Tutorialspoint. "
+ "We provide free tutorials on various technologies";
//Instantiating whitespaceTokenizer class
WhitespaceTokenizer whitespaceTokenizer = WhitespaceTokenizer.INSTANCE;
//Tokenizing the given paragraph
String tokens[] = whitespaceTokenizer.tokenize(sentence);
//Printing the tokens
for(String token : tokens)
System.out.println(token);
}
}
Compile and execute the saved Java file from the Command prompt using the following commands −
javac WhitespaceTokenizerExample.java
java WhitespaceTokenizerExample
On executing, the above program reads the given String (raw text), tokenizes it, and displays the following output.
Hi.
How
are
you?
Welcome
to
Tutorialspoint.
We
provide
free
tutorials
on
various
technologies
OpenNLP also uses a predefined model, a file named de-token.bin, to tokenize the sentences. It is trained to tokenize the sentences in a given raw text.
The TokenizerME class of the opennlp.tools.tokenizer package is used to load this model, and tokenize the given raw text using OpenNLP library. To do so, you need to −
Load the en-token.bin model using the TokenizerModel class.
Load the en-token.bin model using the TokenizerModel class.
Instantiate the TokenizerME class.
Instantiate the TokenizerME class.
Tokenize the sentences using the tokenize() method of this class.
Tokenize the sentences using the tokenize() method of this class.
Following are the steps to be followed to write a program which tokenizes the sentences from the given raw text using the TokenizerME class.
Step 1 − Loading the model
The model for tokenization is represented by the class named TokenizerModel, which belongs to the package opennlp.tools.tokenize.
To load a tokenizer model −
Create an InputStream object of the model (Instantiate the FileInputStream and pass the path of the model in String format to its constructor).
Create an InputStream object of the model (Instantiate the FileInputStream and pass the path of the model in String format to its constructor).
Instantiate the TokenizerModel class and pass the InputStream (object) of the model as a parameter to its constructor, as shown in the following code block.
Instantiate the TokenizerModel class and pass the InputStream (object) of the model as a parameter to its constructor, as shown in the following code block.
//Loading the Tokenizer model
InputStream inputStream = new FileInputStream("C:/OpenNLP_models/en-token.bin");
TokenizerModel tokenModel = new TokenizerModel(inputStream);
Step 2 − Instantiating the TokenizerME class
The TokenizerME class of the package opennlp.tools.tokenize contains methods to chop the raw text into smaller parts (tokens). It uses Maximum Entropy to make its decisions.
Instantiate this class and pass the model object created in the previous step as shown below.
//Instantiating the TokenizerME class
TokenizerME tokenizer = new TokenizerME(tokenModel);
Step 3 − Tokenizing the sentence
The tokenize() method of the TokenizerME class is used to tokenize the raw text passed to it. This method accepts a String variable as a parameter, and returns an array of Strings (tokens).
Invoke this method by passing the String format of the sentence to this method, as follows.
//Tokenizing the given raw text
String tokens[] = tokenizer.tokenize(paragraph);
Example
Following is the program which tokenizes the given raw text. Save this program in a file with the name TokenizerMEExample.java.
import java.io.FileInputStream;
import java.io.InputStream;
import opennlp.tools.tokenize.TokenizerME;
import opennlp.tools.tokenize.TokenizerModel;
public class TokenizerMEExample {
public static void main(String args[]) throws Exception{
String sentence = "Hi. How are you? Welcome to Tutorialspoint. "
+ "We provide free tutorials on various technologies";
//Loading the Tokenizer model
InputStream inputStream = new FileInputStream("C:/OpenNLP_models/en-token.bin");
TokenizerModel tokenModel = new TokenizerModel(inputStream);
//Instantiating the TokenizerME class
TokenizerME tokenizer = new TokenizerME(tokenModel);
//Tokenizing the given raw text
String tokens[] = tokenizer.tokenize(sentence);
//Printing the tokens
for (String a : tokens)
System.out.println(a);
}
}
Compile and execute the saved Java file from the Command prompt using the following commands −
javac TokenizerMEExample.java
java TokenizerMEExample
On executing, the above program reads the given String and detects the sentences in it and displays the following output −
Hi
.
How
are
you
?
Welcome
to
Tutorialspoint
.
We
provide
free
tutorials
on
various
technologie
We can also get the positions or spans of the tokens using the tokenizePos() method. This is the method of the Tokenizer interface of the package opennlp.tools.tokenize. Since all the (three) Tokenizer classes implement this interface, you can find this method in all of them.
This method accepts the sentence or raw text in the form of a string and returns an array of objects of the type Span.
You can get the positions of the tokens using the tokenizePos() method, as follows −
//Retrieving the tokens
tokenizer.tokenizePos(sentence);
The class named Span of the opennlp.tools.util package is used to store the start and end integer of sets.
You can store the spans returned by the tokenizePos() method in the Span array and print them, as shown in the following code block.
//Retrieving the tokens
Span[] tokens = tokenizer.tokenizePos(sentence);
//Printing the spans of tokens
for( Span token : tokens)
System.out.println(token);
The substring() method of the String class accepts the begin and the end offsets and returns the respective string. We can use this method to print the tokens and their spans (positions) together, as shown in the following code block.
//Printing the spans of tokens
for(Span token : tokens)
System.out.println(token +" "+sent.substring(token.getStart(), token.getEnd()));
Example(SimpleTokenizer)
Following is the program which retrieves the token spans of the raw text using the SimpleTokenizer class. It also prints the tokens along with their positions. Save this program in a file with named SimpleTokenizerSpans.java.
import opennlp.tools.tokenize.SimpleTokenizer;
import opennlp.tools.util.Span;
public class SimpleTokenizerSpans {
public static void main(String args[]){
String sent = "Hi. How are you? Welcome to Tutorialspoint. "
+ "We provide free tutorials on various technologies";
//Instantiating SimpleTokenizer class
SimpleTokenizer simpleTokenizer = SimpleTokenizer.INSTANCE;
//Retrieving the boundaries of the tokens
Span[] tokens = simpleTokenizer.tokenizePos(sent);
//Printing the spans of tokens
for( Span token : tokens)
System.out.println(token +" "+sent.substring(token.getStart(), token.getEnd()));
}
}
Compile and execute the saved Java file from the Command prompt using the following commands −
javac SimpleTokenizerSpans.java
java SimpleTokenizerSpans
On executing, the above program reads the given String (raw text), tokenizes it, and displays the following output −
[0..2) Hi
[2..3) .
[4..7) How
[8..11) are
[12..15) you
[15..16) ?
[17..24) Welcome
[25..27) to
[28..42) Tutorialspoint
[42..43) .
[44..46) We
[47..54) provide
[55..59) free
[60..69) tutorials
[70..72) on
[73..80) various
[81..93) technologies
Example (WhitespaceTokenizer)
Following is the program which retrieves the token spans of the raw text using the WhitespaceTokenizer class. It also prints the tokens along with their positions. Save this program in a file with the name WhitespaceTokenizerSpans.java.
import opennlp.tools.tokenize.WhitespaceTokenizer;
import opennlp.tools.util.Span;
public class WhitespaceTokenizerSpans {
public static void main(String args[]){
String sent = "Hi. How are you? Welcome to Tutorialspoint. "
+ "We provide free tutorials on various technologies";
//Instantiating SimpleTokenizer class
WhitespaceTokenizer whitespaceTokenizer = WhitespaceTokenizer.INSTANCE;
//Retrieving the tokens
Span[] tokens = whitespaceTokenizer.tokenizePos(sent);
//Printing the spans of tokens
for( Span token : tokens)
System.out.println(token +"
"+sent.substring(token.getStart(), token.getEnd()));
}
}
Compile and execute the saved java file from the command prompt using the following commands
javac WhitespaceTokenizerSpans.java
java WhitespaceTokenizerSpans
On executing, the above program reads the given String (raw text), tokenizes it, and displays the following output.
[0..3) Hi.
[4..7) How
[8..11) are
[12..16) you?
[17..24) Welcome
[25..27) to
[28..43) Tutorialspoint.
[44..46) We
[47..54) provide
[55..59) free
[60..69) tutorials
[70..72) on
[73..80) various
[81..93) technologies
Example (TokenizerME)
Following is the program which retrieves the token spans of the raw text using the TokenizerME class. It also prints the tokens along with their positions. Save this program in a file with the name TokenizerMESpans.java.
import java.io.FileInputStream;
import java.io.InputStream;
import opennlp.tools.tokenize.TokenizerME;
import opennlp.tools.tokenize.TokenizerModel;
import opennlp.tools.util.Span;
public class TokenizerMESpans {
public static void main(String args[]) throws Exception{
String sent = "Hello John how are you welcome to Tutorialspoint";
//Loading the Tokenizer model
InputStream inputStream = new FileInputStream("C:/OpenNLP_models/en-token.bin");
TokenizerModel tokenModel = new TokenizerModel(inputStream);
//Instantiating the TokenizerME class
TokenizerME tokenizer = new TokenizerME(tokenModel);
//Retrieving the positions of the tokens
Span tokens[] = tokenizer.tokenizePos(sent);
//Printing the spans of tokens
for(Span token : tokens)
System.out.println(token +" "+sent.substring(token.getStart(), token.getEnd()));
}
}
Compile and execute the saved Java file from the Command prompt using the following commands −
javac TokenizerMESpans.java
java TokenizerMESpans
On executing, the above program reads the given String (raw text), tokenizes it, and displays the following output −
[0..5) Hello
[6..10) John
[11..14) how
[15..18) are
[19..22) you
[23..30) welcome
[31..33) to
[34..48) Tutorialspoint
The getTokenProbabilities() method of the TokenizerME class is used to get the probabilities associated with the most recent calls to the tokenizePos() method.
//Getting the probabilities of the recent calls to tokenizePos() method
double[] probs = detector.getSentenceProbabilities();
Following is the program to print the probabilities associated with the calls to tokenizePos() method. Save this program in a file with the name TokenizerMEProbs.java.
import java.io.FileInputStream;
import java.io.InputStream;
import opennlp.tools.tokenize.TokenizerME;
import opennlp.tools.tokenize.TokenizerModel;
import opennlp.tools.util.Span;
public class TokenizerMEProbs {
public static void main(String args[]) throws Exception{
String sent = "Hello John how are you welcome to Tutorialspoint";
//Loading the Tokenizer model
InputStream inputStream = new FileInputStream("C:/OpenNLP_models/en-token.bin");
TokenizerModel tokenModel = new TokenizerModel(inputStream);
//Instantiating the TokenizerME class
TokenizerME tokenizer = new TokenizerME(tokenModel);
//Retrieving the positions of the tokens
Span tokens[] = tokenizer.tokenizePos(sent);
//Getting the probabilities of the recent calls to tokenizePos() method
double[] probs = tokenizer.getTokenProbabilities();
//Printing the spans of tokens
for(Span token : tokens)
System.out.println(token +" "+sent.substring(token.getStart(), token.getEnd()));
System.out.println(" ");
for(int i = 0; i<probs.length; i++)
System.out.println(probs[i]);
}
}
Compile and execute the saved Java file from the Command prompt using the following commands −
javac TokenizerMEProbs.java
java TokenizerMEProbs
On executing, the above program reads the given String and tokenizes the sentences and prints them. In addition, it also returns the probabilities associated with the most recent calls to the tokenizerPos() method.
[0..5) Hello
[6..10) John
[11..14) how
[15..18) are
[19..22) you
[23..30) welcome
[31..33) to
[34..48) Tutorialspoint
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2044,
"s": 1852,
"text": "The process of chopping the given sentence into smaller parts (tokens) is known as tokenization. In general, the given raw text is tokenized based on a set of delimiters (mostly whitespaces)."
},
{
"code": null,
"e": 2211,
"s": 2044,
"text": "Tokenization is used in tasks such as spell-checking, processing searches, identifying parts of speech, sentence detection, document classification of documents, etc."
},
{
"code": null,
"e": 2321,
"s": 2211,
"text": "The opennlp.tools.tokenize package contains the classes and interfaces that are used to perform tokenization."
},
{
"code": null,
"e": 2432,
"s": 2321,
"text": "To tokenize the given sentences into simpler fragments, the OpenNLP library provides three different classes −"
},
{
"code": null,
"e": 2515,
"s": 2432,
"text": "SimpleTokenizer − This class tokenizes the given raw text using character classes."
},
{
"code": null,
"e": 2598,
"s": 2515,
"text": "SimpleTokenizer − This class tokenizes the given raw text using character classes."
},
{
"code": null,
"e": 2676,
"s": 2598,
"text": "WhitespaceTokenizer − This class uses whitespaces to tokenize the given text."
},
{
"code": null,
"e": 2754,
"s": 2676,
"text": "WhitespaceTokenizer − This class uses whitespaces to tokenize the given text."
},
{
"code": null,
"e": 2866,
"s": 2754,
"text": "TokenizerME − This class converts raw text into separate tokens. It uses Maximum Entropy to make its decisions."
},
{
"code": null,
"e": 2978,
"s": 2866,
"text": "TokenizerME − This class converts raw text into separate tokens. It uses Maximum Entropy to make its decisions."
},
{
"code": null,
"e": 3048,
"s": 2978,
"text": "To tokenize a sentence using the SimpleTokenizer class, you need to −"
},
{
"code": null,
"e": 3090,
"s": 3048,
"text": "Create an object of the respective class."
},
{
"code": null,
"e": 3132,
"s": 3090,
"text": "Create an object of the respective class."
},
{
"code": null,
"e": 3183,
"s": 3132,
"text": "Tokenize the sentence using the tokenize() method."
},
{
"code": null,
"e": 3234,
"s": 3183,
"text": "Tokenize the sentence using the tokenize() method."
},
{
"code": null,
"e": 3252,
"s": 3234,
"text": "Print the tokens."
},
{
"code": null,
"e": 3270,
"s": 3252,
"text": "Print the tokens."
},
{
"code": null,
"e": 3364,
"s": 3270,
"text": "Following are the steps to be followed to write a program which tokenizes the given raw text."
},
{
"code": null,
"e": 3408,
"s": 3364,
"text": "Step 1 − Instantiating the respective class"
},
{
"code": null,
"e": 3576,
"s": 3408,
"text": "In both the classes, there are no constructors available to instantiate them. Therefore, we need to create objects of these classes using the static variable INSTANCE."
},
{
"code": null,
"e": 3633,
"s": 3576,
"text": "SimpleTokenizer tokenizer = SimpleTokenizer.INSTANCE; "
},
{
"code": null,
"e": 3665,
"s": 3633,
"text": "Step 2 − Tokenize the sentences"
},
{
"code": null,
"e": 3854,
"s": 3665,
"text": "Both these classes contain a method called tokenize(). This method accepts a raw text in String format. On invoking, it tokenizes the given String and returns an array of Strings (tokens)."
},
{
"code": null,
"e": 3921,
"s": 3854,
"text": "Tokenize the sentence using the tokenizer() method as shown below."
},
{
"code": null,
"e": 4004,
"s": 3921,
"text": "//Tokenizing the given sentence \n String tokens[] = tokenizer.tokenize(sentence); "
},
{
"code": null,
"e": 4030,
"s": 4004,
"text": "Step 3 − Print the tokens"
},
{
"code": null,
"e": 4118,
"s": 4030,
"text": "After tokenizing the sentence, you can print the tokens using for loop, as shown below."
},
{
"code": null,
"e": 4205,
"s": 4118,
"text": "//Printing the tokens \nfor(String token : tokens) \n System.out.println(token);"
},
{
"code": null,
"e": 4213,
"s": 4205,
"text": "Example"
},
{
"code": null,
"e": 4377,
"s": 4213,
"text": "Following is the program which tokenizes the given sentence using the SimpleTokenizer class. Save this program in a file with the name SimpleTokenizerExample.java."
},
{
"code": null,
"e": 5022,
"s": 4377,
"text": "import opennlp.tools.tokenize.SimpleTokenizer; \npublic class SimpleTokenizerExample { \n public static void main(String args[]){ \n \n String sentence = \"Hi. How are you? Welcome to Tutorialspoint. \" \n + \"We provide free tutorials on various technologies\"; \n \n //Instantiating SimpleTokenizer class \n SimpleTokenizer simpleTokenizer = SimpleTokenizer.INSTANCE; \n \n //Tokenizing the given sentence \n String tokens[] = simpleTokenizer.tokenize(sentence); \n \n //Printing the tokens \n for(String token : tokens) { \n System.out.println(token); \n } \n } \n}"
},
{
"code": null,
"e": 5117,
"s": 5022,
"text": "Compile and execute the saved Java file from the Command prompt using the following commands −"
},
{
"code": null,
"e": 5180,
"s": 5117,
"text": "javac SimpleTokenizerExample.java \njava SimpleTokenizerExample"
},
{
"code": null,
"e": 5297,
"s": 5180,
"text": "On executing, the above program reads the given String (raw text), tokenizes it, and displays the following output −"
},
{
"code": null,
"e": 5412,
"s": 5297,
"text": "Hi \n. \nHow \nare \nyou \n? \nWelcome \nto \nTutorialspoint \n. \nWe \nprovide \nfree \ntutorials \non \nvarious \ntechnologies \n"
},
{
"code": null,
"e": 5486,
"s": 5412,
"text": "To tokenize a sentence using the WhitespaceTokenizer class, you need to −"
},
{
"code": null,
"e": 5528,
"s": 5486,
"text": "Create an object of the respective class."
},
{
"code": null,
"e": 5570,
"s": 5528,
"text": "Create an object of the respective class."
},
{
"code": null,
"e": 5621,
"s": 5570,
"text": "Tokenize the sentence using the tokenize() method."
},
{
"code": null,
"e": 5672,
"s": 5621,
"text": "Tokenize the sentence using the tokenize() method."
},
{
"code": null,
"e": 5690,
"s": 5672,
"text": "Print the tokens."
},
{
"code": null,
"e": 5708,
"s": 5690,
"text": "Print the tokens."
},
{
"code": null,
"e": 5802,
"s": 5708,
"text": "Following are the steps to be followed to write a program which tokenizes the given raw text."
},
{
"code": null,
"e": 5846,
"s": 5802,
"text": "Step 1 − Instantiating the respective class"
},
{
"code": null,
"e": 6014,
"s": 5846,
"text": "In both the classes, there are no constructors available to instantiate them. Therefore, we need to create objects of these classes using the static variable INSTANCE."
},
{
"code": null,
"e": 6077,
"s": 6014,
"text": "WhitespaceTokenizer tokenizer = WhitespaceTokenizer.INSTANCE; "
},
{
"code": null,
"e": 6109,
"s": 6077,
"text": "Step 2 − Tokenize the sentences"
},
{
"code": null,
"e": 6298,
"s": 6109,
"text": "Both these classes contain a method called tokenize(). This method accepts a raw text in String format. On invoking, it tokenizes the given String and returns an array of Strings (tokens)."
},
{
"code": null,
"e": 6365,
"s": 6298,
"text": "Tokenize the sentence using the tokenizer() method as shown below."
},
{
"code": null,
"e": 6448,
"s": 6365,
"text": "//Tokenizing the given sentence \n String tokens[] = tokenizer.tokenize(sentence); "
},
{
"code": null,
"e": 6474,
"s": 6448,
"text": "Step 3 − Print the tokens"
},
{
"code": null,
"e": 6562,
"s": 6474,
"text": "After tokenizing the sentence, you can print the tokens using for loop, as shown below."
},
{
"code": null,
"e": 6649,
"s": 6562,
"text": "//Printing the tokens \nfor(String token : tokens) \n System.out.println(token);"
},
{
"code": null,
"e": 6657,
"s": 6649,
"text": "Example"
},
{
"code": null,
"e": 6829,
"s": 6657,
"text": "Following is the program which tokenizes the given sentence using the WhitespaceTokenizer class. Save this program in a file with the name WhitespaceTokenizerExample.java."
},
{
"code": null,
"e": 7494,
"s": 6829,
"text": "import opennlp.tools.tokenize.WhitespaceTokenizer; \n\npublic class WhitespaceTokenizerExample { \n \n public static void main(String args[]){ \n \n String sentence = \"Hi. How are you? Welcome to Tutorialspoint. \" \n + \"We provide free tutorials on various technologies\"; \n \n //Instantiating whitespaceTokenizer class \n WhitespaceTokenizer whitespaceTokenizer = WhitespaceTokenizer.INSTANCE; \n \n //Tokenizing the given paragraph \n String tokens[] = whitespaceTokenizer.tokenize(sentence); \n \n //Printing the tokens \n for(String token : tokens) \n System.out.println(token); \n } \n}"
},
{
"code": null,
"e": 7589,
"s": 7494,
"text": "Compile and execute the saved Java file from the Command prompt using the following commands −"
},
{
"code": null,
"e": 7661,
"s": 7589,
"text": "javac WhitespaceTokenizerExample.java \njava WhitespaceTokenizerExample "
},
{
"code": null,
"e": 7777,
"s": 7661,
"text": "On executing, the above program reads the given String (raw text), tokenizes it, and displays the following output."
},
{
"code": null,
"e": 7885,
"s": 7777,
"text": "Hi. \nHow \nare \nyou? \nWelcome \nto \nTutorialspoint. \nWe \nprovide \nfree \ntutorials \non \nvarious \ntechnologies\n"
},
{
"code": null,
"e": 8038,
"s": 7885,
"text": "OpenNLP also uses a predefined model, a file named de-token.bin, to tokenize the sentences. It is trained to tokenize the sentences in a given raw text."
},
{
"code": null,
"e": 8206,
"s": 8038,
"text": "The TokenizerME class of the opennlp.tools.tokenizer package is used to load this model, and tokenize the given raw text using OpenNLP library. To do so, you need to −"
},
{
"code": null,
"e": 8266,
"s": 8206,
"text": "Load the en-token.bin model using the TokenizerModel class."
},
{
"code": null,
"e": 8326,
"s": 8266,
"text": "Load the en-token.bin model using the TokenizerModel class."
},
{
"code": null,
"e": 8361,
"s": 8326,
"text": "Instantiate the TokenizerME class."
},
{
"code": null,
"e": 8396,
"s": 8361,
"text": "Instantiate the TokenizerME class."
},
{
"code": null,
"e": 8462,
"s": 8396,
"text": "Tokenize the sentences using the tokenize() method of this class."
},
{
"code": null,
"e": 8528,
"s": 8462,
"text": "Tokenize the sentences using the tokenize() method of this class."
},
{
"code": null,
"e": 8669,
"s": 8528,
"text": "Following are the steps to be followed to write a program which tokenizes the sentences from the given raw text using the TokenizerME class."
},
{
"code": null,
"e": 8696,
"s": 8669,
"text": "Step 1 − Loading the model"
},
{
"code": null,
"e": 8826,
"s": 8696,
"text": "The model for tokenization is represented by the class named TokenizerModel, which belongs to the package opennlp.tools.tokenize."
},
{
"code": null,
"e": 8854,
"s": 8826,
"text": "To load a tokenizer model −"
},
{
"code": null,
"e": 8998,
"s": 8854,
"text": "Create an InputStream object of the model (Instantiate the FileInputStream and pass the path of the model in String format to its constructor)."
},
{
"code": null,
"e": 9142,
"s": 8998,
"text": "Create an InputStream object of the model (Instantiate the FileInputStream and pass the path of the model in String format to its constructor)."
},
{
"code": null,
"e": 9299,
"s": 9142,
"text": "Instantiate the TokenizerModel class and pass the InputStream (object) of the model as a parameter to its constructor, as shown in the following code block."
},
{
"code": null,
"e": 9456,
"s": 9299,
"text": "Instantiate the TokenizerModel class and pass the InputStream (object) of the model as a parameter to its constructor, as shown in the following code block."
},
{
"code": null,
"e": 9630,
"s": 9456,
"text": "//Loading the Tokenizer model \nInputStream inputStream = new FileInputStream(\"C:/OpenNLP_models/en-token.bin\"); \nTokenizerModel tokenModel = new TokenizerModel(inputStream);"
},
{
"code": null,
"e": 9675,
"s": 9630,
"text": "Step 2 − Instantiating the TokenizerME class"
},
{
"code": null,
"e": 9849,
"s": 9675,
"text": "The TokenizerME class of the package opennlp.tools.tokenize contains methods to chop the raw text into smaller parts (tokens). It uses Maximum Entropy to make its decisions."
},
{
"code": null,
"e": 9943,
"s": 9849,
"text": "Instantiate this class and pass the model object created in the previous step as shown below."
},
{
"code": null,
"e": 10035,
"s": 9943,
"text": "//Instantiating the TokenizerME class \nTokenizerME tokenizer = new TokenizerME(tokenModel);"
},
{
"code": null,
"e": 10068,
"s": 10035,
"text": "Step 3 − Tokenizing the sentence"
},
{
"code": null,
"e": 10258,
"s": 10068,
"text": "The tokenize() method of the TokenizerME class is used to tokenize the raw text passed to it. This method accepts a String variable as a parameter, and returns an array of Strings (tokens)."
},
{
"code": null,
"e": 10350,
"s": 10258,
"text": "Invoke this method by passing the String format of the sentence to this method, as follows."
},
{
"code": null,
"e": 10432,
"s": 10350,
"text": "//Tokenizing the given raw text \nString tokens[] = tokenizer.tokenize(paragraph);"
},
{
"code": null,
"e": 10440,
"s": 10432,
"text": "Example"
},
{
"code": null,
"e": 10568,
"s": 10440,
"text": "Following is the program which tokenizes the given raw text. Save this program in a file with the name TokenizerMEExample.java."
},
{
"code": null,
"e": 11508,
"s": 10568,
"text": "import java.io.FileInputStream; \nimport java.io.InputStream; \nimport opennlp.tools.tokenize.TokenizerME; \nimport opennlp.tools.tokenize.TokenizerModel; \n\npublic class TokenizerMEExample { \n \n public static void main(String args[]) throws Exception{ \n \n String sentence = \"Hi. How are you? Welcome to Tutorialspoint. \" \n + \"We provide free tutorials on various technologies\"; \n \n //Loading the Tokenizer model \n InputStream inputStream = new FileInputStream(\"C:/OpenNLP_models/en-token.bin\"); \n TokenizerModel tokenModel = new TokenizerModel(inputStream); \n \n //Instantiating the TokenizerME class \n TokenizerME tokenizer = new TokenizerME(tokenModel); \n \n //Tokenizing the given raw text \n String tokens[] = tokenizer.tokenize(sentence); \n \n //Printing the tokens \n for (String a : tokens) \n System.out.println(a); \n } \n} "
},
{
"code": null,
"e": 11603,
"s": 11508,
"text": "Compile and execute the saved Java file from the Command prompt using the following commands −"
},
{
"code": null,
"e": 11659,
"s": 11603,
"text": "javac TokenizerMEExample.java \njava TokenizerMEExample\n"
},
{
"code": null,
"e": 11782,
"s": 11659,
"text": "On executing, the above program reads the given String and detects the sentences in it and displays the following output −"
},
{
"code": null,
"e": 11895,
"s": 11782,
"text": "Hi \n. \nHow \nare \nyou \n? \nWelcome \nto \nTutorialspoint \n. \nWe \nprovide \nfree \ntutorials \non \nvarious \ntechnologie\n"
},
{
"code": null,
"e": 12172,
"s": 11895,
"text": "We can also get the positions or spans of the tokens using the tokenizePos() method. This is the method of the Tokenizer interface of the package opennlp.tools.tokenize. Since all the (three) Tokenizer classes implement this interface, you can find this method in all of them."
},
{
"code": null,
"e": 12291,
"s": 12172,
"text": "This method accepts the sentence or raw text in the form of a string and returns an array of objects of the type Span."
},
{
"code": null,
"e": 12376,
"s": 12291,
"text": "You can get the positions of the tokens using the tokenizePos() method, as follows −"
},
{
"code": null,
"e": 12435,
"s": 12376,
"text": "//Retrieving the tokens \ntokenizer.tokenizePos(sentence); "
},
{
"code": null,
"e": 12542,
"s": 12435,
"text": "The class named Span of the opennlp.tools.util package is used to store the start and end integer of sets."
},
{
"code": null,
"e": 12675,
"s": 12542,
"text": "You can store the spans returned by the tokenizePos() method in the Span array and print them, as shown in the following code block."
},
{
"code": null,
"e": 12845,
"s": 12675,
"text": "//Retrieving the tokens \nSpan[] tokens = tokenizer.tokenizePos(sentence);\n//Printing the spans of tokens \nfor( Span token : tokens) \n System.out.println(token);"
},
{
"code": null,
"e": 13080,
"s": 12845,
"text": "The substring() method of the String class accepts the begin and the end offsets and returns the respective string. We can use this method to print the tokens and their spans (positions) together, as shown in the following code block."
},
{
"code": null,
"e": 13223,
"s": 13080,
"text": "//Printing the spans of tokens \nfor(Span token : tokens) \n System.out.println(token +\" \"+sent.substring(token.getStart(), token.getEnd()));"
},
{
"code": null,
"e": 13248,
"s": 13223,
"text": "Example(SimpleTokenizer)"
},
{
"code": null,
"e": 13474,
"s": 13248,
"text": "Following is the program which retrieves the token spans of the raw text using the SimpleTokenizer class. It also prints the tokens along with their positions. Save this program in a file with named SimpleTokenizerSpans.java."
},
{
"code": null,
"e": 14204,
"s": 13474,
"text": "import opennlp.tools.tokenize.SimpleTokenizer; \nimport opennlp.tools.util.Span; \n\npublic class SimpleTokenizerSpans { \n public static void main(String args[]){ \n \n String sent = \"Hi. How are you? Welcome to Tutorialspoint. \" \n + \"We provide free tutorials on various technologies\"; \n \n //Instantiating SimpleTokenizer class \n SimpleTokenizer simpleTokenizer = SimpleTokenizer.INSTANCE; \n \n //Retrieving the boundaries of the tokens \n Span[] tokens = simpleTokenizer.tokenizePos(sent); \n \n //Printing the spans of tokens \n for( Span token : tokens)\n System.out.println(token +\" \"+sent.substring(token.getStart(), token.getEnd())); \n } \n} "
},
{
"code": null,
"e": 14299,
"s": 14204,
"text": "Compile and execute the saved Java file from the Command prompt using the following commands −"
},
{
"code": null,
"e": 14359,
"s": 14299,
"text": "javac SimpleTokenizerSpans.java \njava SimpleTokenizerSpans "
},
{
"code": null,
"e": 14476,
"s": 14359,
"text": "On executing, the above program reads the given String (raw text), tokenizes it, and displays the following output −"
},
{
"code": null,
"e": 14737,
"s": 14476,
"text": "[0..2) Hi \n[2..3) . \n[4..7) How \n[8..11) are \n[12..15) you \n[15..16) ? \n[17..24) Welcome \n[25..27) to \n[28..42) Tutorialspoint \n[42..43) . \n[44..46) We \n[47..54) provide \n[55..59) free \n[60..69) tutorials \n[70..72) on \n[73..80) various \n[81..93) technologies \n"
},
{
"code": null,
"e": 14767,
"s": 14737,
"text": "Example (WhitespaceTokenizer)"
},
{
"code": null,
"e": 15004,
"s": 14767,
"text": "Following is the program which retrieves the token spans of the raw text using the WhitespaceTokenizer class. It also prints the tokens along with their positions. Save this program in a file with the name WhitespaceTokenizerSpans.java."
},
{
"code": null,
"e": 15744,
"s": 15004,
"text": "import opennlp.tools.tokenize.WhitespaceTokenizer;\nimport opennlp.tools.util.Span; \npublic class WhitespaceTokenizerSpans { \n public static void main(String args[]){ \n \n String sent = \"Hi. How are you? Welcome to Tutorialspoint. \" \n + \"We provide free tutorials on various technologies\"; \n \n //Instantiating SimpleTokenizer class \n WhitespaceTokenizer whitespaceTokenizer = WhitespaceTokenizer.INSTANCE; \n \n //Retrieving the tokens \n Span[] tokens = whitespaceTokenizer.tokenizePos(sent); \n \n //Printing the spans of tokens \n for( Span token : tokens) \n System.out.println(token +\" \n \"+sent.substring(token.getStart(), token.getEnd())); \n } \n} "
},
{
"code": null,
"e": 15837,
"s": 15744,
"text": "Compile and execute the saved java file from the command prompt using the following commands"
},
{
"code": null,
"e": 15904,
"s": 15837,
"text": "javac WhitespaceTokenizerSpans.java \njava WhitespaceTokenizerSpans"
},
{
"code": null,
"e": 16020,
"s": 15904,
"text": "On executing, the above program reads the given String (raw text), tokenizes it, and displays the following output."
},
{
"code": null,
"e": 16248,
"s": 16020,
"text": "[0..3) Hi. \n[4..7) How \n[8..11) are \n[12..16) you? \n[17..24) Welcome \n[25..27) to \n[28..43) Tutorialspoint. \n[44..46) We \n[47..54) provide \n[55..59) free\n[60..69) tutorials \n[70..72) on \n[73..80) various \n[81..93) technologies\n"
},
{
"code": null,
"e": 16270,
"s": 16248,
"text": "Example (TokenizerME)"
},
{
"code": null,
"e": 16491,
"s": 16270,
"text": "Following is the program which retrieves the token spans of the raw text using the TokenizerME class. It also prints the tokens along with their positions. Save this program in a file with the name TokenizerMESpans.java."
},
{
"code": null,
"e": 17455,
"s": 16491,
"text": "import java.io.FileInputStream; \nimport java.io.InputStream; \nimport opennlp.tools.tokenize.TokenizerME; \nimport opennlp.tools.tokenize.TokenizerModel; \nimport opennlp.tools.util.Span; \n\npublic class TokenizerMESpans { \n public static void main(String args[]) throws Exception{ \n String sent = \"Hello John how are you welcome to Tutorialspoint\"; \n \n //Loading the Tokenizer model \n InputStream inputStream = new FileInputStream(\"C:/OpenNLP_models/en-token.bin\"); \n TokenizerModel tokenModel = new TokenizerModel(inputStream); \n \n //Instantiating the TokenizerME class \n TokenizerME tokenizer = new TokenizerME(tokenModel); \n \n //Retrieving the positions of the tokens \n Span tokens[] = tokenizer.tokenizePos(sent); \n \n //Printing the spans of tokens \n for(Span token : tokens) \n System.out.println(token +\" \"+sent.substring(token.getStart(), token.getEnd())); \n } \n} "
},
{
"code": null,
"e": 17550,
"s": 17455,
"text": "Compile and execute the saved Java file from the Command prompt using the following commands −"
},
{
"code": null,
"e": 17601,
"s": 17550,
"text": "javac TokenizerMESpans.java \njava TokenizerMESpans"
},
{
"code": null,
"e": 17718,
"s": 17601,
"text": "On executing, the above program reads the given String (raw text), tokenizes it, and displays the following output −"
},
{
"code": null,
"e": 17845,
"s": 17718,
"text": "[0..5) Hello \n[6..10) John \n[11..14) how \n[15..18) are \n[19..22) you \n[23..30) welcome \n[31..33) to \n[34..48) Tutorialspoint \n"
},
{
"code": null,
"e": 18005,
"s": 17845,
"text": "The getTokenProbabilities() method of the TokenizerME class is used to get the probabilities associated with the most recent calls to the tokenizePos() method."
},
{
"code": null,
"e": 18133,
"s": 18005,
"text": "//Getting the probabilities of the recent calls to tokenizePos() method \ndouble[] probs = detector.getSentenceProbabilities(); "
},
{
"code": null,
"e": 18301,
"s": 18133,
"text": "Following is the program to print the probabilities associated with the calls to tokenizePos() method. Save this program in a file with the name TokenizerMEProbs.java."
},
{
"code": null,
"e": 19550,
"s": 18301,
"text": "import java.io.FileInputStream; \nimport java.io.InputStream; \nimport opennlp.tools.tokenize.TokenizerME; \nimport opennlp.tools.tokenize.TokenizerModel; \nimport opennlp.tools.util.Span; \n\npublic class TokenizerMEProbs { \n \n public static void main(String args[]) throws Exception{ \n String sent = \"Hello John how are you welcome to Tutorialspoint\"; \n \n //Loading the Tokenizer model \n InputStream inputStream = new FileInputStream(\"C:/OpenNLP_models/en-token.bin\"); \n TokenizerModel tokenModel = new TokenizerModel(inputStream); \n \n //Instantiating the TokenizerME class \n TokenizerME tokenizer = new TokenizerME(tokenModel);\n \n //Retrieving the positions of the tokens \n Span tokens[] = tokenizer.tokenizePos(sent); \n \n //Getting the probabilities of the recent calls to tokenizePos() method \n double[] probs = tokenizer.getTokenProbabilities(); \n \n //Printing the spans of tokens \n for(Span token : tokens) \n System.out.println(token +\" \"+sent.substring(token.getStart(), token.getEnd())); \n System.out.println(\" \"); \n for(int i = 0; i<probs.length; i++) \n System.out.println(probs[i]); \n } \n} "
},
{
"code": null,
"e": 19645,
"s": 19550,
"text": "Compile and execute the saved Java file from the Command prompt using the following commands −"
},
{
"code": null,
"e": 19697,
"s": 19645,
"text": "javac TokenizerMEProbs.java \njava TokenizerMEProbs "
},
{
"code": null,
"e": 19912,
"s": 19697,
"text": "On executing, the above program reads the given String and tokenizes the sentences and prints them. In addition, it also returns the probabilities associated with the most recent calls to the tokenizerPos() method."
},
{
"code": null,
"e": 20082,
"s": 19912,
"text": "[0..5) Hello \n[6..10) John \n[11..14) how \n[15..18) are \n[19..22) you \n[23..30) welcome \n[31..33) to \n[34..48) Tutorialspoint \n \n1.0 \n1.0 \n1.0 \n1.0 \n1.0 \n1.0 \n1.0 \n1.0\n"
},
{
"code": null,
"e": 20089,
"s": 20082,
"text": " Print"
},
{
"code": null,
"e": 20100,
"s": 20089,
"text": " Add Notes"
}
] |
Form validation using HTML and JavaScript - GeeksforGeeks
|
28 Jul, 2021
Forms are used in webpages for the user to enter their required details that further send it to the server for processing. A form is also known as a web form or HTML form. Examples of form use are prevalent in e-commerce websites, online banking, online surveys to name a few.
Syntax for form in HTML
<body> <h1 style="text-align: center;">REGISTRATION FORM</h1> <form name="RegForm" action="/submit.php" onsubmit="return GEEKFORGEEKS()" method="post"> <p>Name: <input type="text" size="65" name="Name" /></p> <br /> <p>Address: <input type="text" size="65" name="Address" /></p> <br /> <p>E-mail Address: <input type="text" size="65" name="EMail" /></p> <br /> <p>Password: <input type="text" size="65" name="Password" /></p> <br /> <p>Telephone: <input type="text" size="65" name="Telephone" /></p> <br /> <p> SELECT YOUR COURSE <select type="text" value="" name="Subject"> <option>BTECH</option> <option>BBA</option> <option>BCA</option> <option>B.COM</option> <option>GEEKFORGEEKS</option> </select> </p> <br /> <br /> <p>Comments: <textarea cols="55" name="Comment"> </textarea></p> <p> <input type="submit" value="send" name="Submit" /> <input type="reset" value="Reset" name="Reset" /> </p> </form></body>
Validating a form: The data entered into a form needs to be in the right format and certain fields need to be filled in order to effectively use the submitted form. Username, password, contact information are some details that are mandatory in forms and thus need to be provided by the user.Below is a code in HTML, CSS, and JavaScript to validate a form. HTML is used to create the form.JavaScript to validate the form.
CSS to design the layout of the form.Form validation:
<script> function GEEKFORGEEKS() { var name = document.forms["RegForm"]["Name"]; var email = document.forms["RegForm"]["EMail"]; var phone = document.forms["RegForm"]["Telephone"]; var what = document.forms["RegForm"]["Subject"]; var password = document.forms["RegForm"]["Password"]; var address = document.forms["RegForm"]["Address"]; if (name.value == "") { window.alert("Please enter your name."); name.focus(); return false; } if (address.value == "") { window.alert("Please enter your address."); address.focus(); return false; } if (email.value == "") { window.alert( "Please enter a valid e-mail address."); email.focus(); return false; } if (phone.value == "") { window.alert( "Please enter your telephone number."); phone.focus(); return false; } if (password.value == "") { window.alert("Please enter your password"); password.focus(); return false; } if (what.selectedIndex < 1) { alert("Please enter your course."); what.focus(); return false; } return true; }</script>
Styling the form:
<style>div { box-sizing: border-box; width: 100%; border: 100px solid black; float: left; align-content: center; align-items: center;} form { margin: 0 auto; width: 600px;}</style>
COMBINED CODE [ALL OF THE ABOVE SECTIONS CLUBBED)
<html> <head> <script> function GEEKFORGEEKS() { var name = document.forms["RegForm"]["Name"]; var email = document.forms["RegForm"]["EMail"]; var phone = document.forms["RegForm"]["Telephone"]; var what = document.forms["RegForm"]["Subject"]; var password = document.forms["RegForm"]["Password"]; var address = document.forms["RegForm"]["Address"]; if (name.value == "") { window.alert("Please enter your name."); name.focus(); return false; } if (address.value == "") { window.alert("Please enter your address."); address.focus(); return false; } if (email.value == "") { window.alert( "Please enter a valid e-mail address."); email.focus(); return false; } if (phone.value == "") { window.alert( "Please enter your telephone number."); phone.focus(); return false; } if (password.value == "") { window.alert("Please enter your password"); password.focus(); return false; } if (what.selectedIndex < 1) { alert("Please enter your course."); what.focus(); return false; } return true; } </script> <style> div { box-sizing: border-box; width: 100%; border: 100px solid black; float: left; align-content: center; align-items: center; } form { margin: 0 auto; width: 600px; } </style> </head> <body> <h1 style="text-align: center;">REGISTRATION FORM</h1> <form name="RegForm" action="/submit.php" onsubmit="return GEEKFORGEEKS()" method="post"> <p>Name: <input type="text" size="65" name="Name" /></p> <br /> <p>Address: <input type="text" size="65" name="Address" /> </p> <br /> <p>E-mail Address: <input type="text" size="65" name="EMail" /></p> <br /> <p>Password: <input type="text" size="65" name="Password" /></p> <br /> <p>Telephone: <input type="text" size="65" name="Telephone" /></p> <br /> <p> SELECT YOUR COURSE <select type="text" value="" name="Subject"> <option>BTECH</option> <option>BBA</option> <option>BCA</option> <option>B.COM</option> <option>GEEKFORGEEKS</option> </select> </p> <br /> <br /> <p>Comments: <textarea cols="55" name="Comment"> </textarea></p> <p> <input type="submit" value="send" name="Submit" /> <input type="reset" value="Reset" name="Reset" /> </p> </form> </body></html> // updated by patelshrey115
Resulting Form:
Reference : https://en.wikipedia.org/wiki/Form_(HTML)
HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples.
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
xXShreyXx
bunnyram19
HTML-Misc
javascript-form
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to set the default value for an HTML <select> element ?
How to update Node.js and NPM to next version ?
How to set input type date in dd-mm-yyyy format using HTML ?
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
How to calculate the number of days between two dates in javascript?
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
|
[
{
"code": null,
"e": 30082,
"s": 30054,
"text": "\n28 Jul, 2021"
},
{
"code": null,
"e": 30359,
"s": 30082,
"text": "Forms are used in webpages for the user to enter their required details that further send it to the server for processing. A form is also known as a web form or HTML form. Examples of form use are prevalent in e-commerce websites, online banking, online surveys to name a few."
},
{
"code": null,
"e": 30383,
"s": 30359,
"text": "Syntax for form in HTML"
},
{
"code": "<body> <h1 style=\"text-align: center;\">REGISTRATION FORM</h1> <form name=\"RegForm\" action=\"/submit.php\" onsubmit=\"return GEEKFORGEEKS()\" method=\"post\"> <p>Name: <input type=\"text\" size=\"65\" name=\"Name\" /></p> <br /> <p>Address: <input type=\"text\" size=\"65\" name=\"Address\" /></p> <br /> <p>E-mail Address: <input type=\"text\" size=\"65\" name=\"EMail\" /></p> <br /> <p>Password: <input type=\"text\" size=\"65\" name=\"Password\" /></p> <br /> <p>Telephone: <input type=\"text\" size=\"65\" name=\"Telephone\" /></p> <br /> <p> SELECT YOUR COURSE <select type=\"text\" value=\"\" name=\"Subject\"> <option>BTECH</option> <option>BBA</option> <option>BCA</option> <option>B.COM</option> <option>GEEKFORGEEKS</option> </select> </p> <br /> <br /> <p>Comments: <textarea cols=\"55\" name=\"Comment\"> </textarea></p> <p> <input type=\"submit\" value=\"send\" name=\"Submit\" /> <input type=\"reset\" value=\"Reset\" name=\"Reset\" /> </p> </form></body>",
"e": 31773,
"s": 30383,
"text": null
},
{
"code": null,
"e": 32194,
"s": 31773,
"text": "Validating a form: The data entered into a form needs to be in the right format and certain fields need to be filled in order to effectively use the submitted form. Username, password, contact information are some details that are mandatory in forms and thus need to be provided by the user.Below is a code in HTML, CSS, and JavaScript to validate a form. HTML is used to create the form.JavaScript to validate the form."
},
{
"code": null,
"e": 32248,
"s": 32194,
"text": "CSS to design the layout of the form.Form validation:"
},
{
"code": "<script> function GEEKFORGEEKS() { var name = document.forms[\"RegForm\"][\"Name\"]; var email = document.forms[\"RegForm\"][\"EMail\"]; var phone = document.forms[\"RegForm\"][\"Telephone\"]; var what = document.forms[\"RegForm\"][\"Subject\"]; var password = document.forms[\"RegForm\"][\"Password\"]; var address = document.forms[\"RegForm\"][\"Address\"]; if (name.value == \"\") { window.alert(\"Please enter your name.\"); name.focus(); return false; } if (address.value == \"\") { window.alert(\"Please enter your address.\"); address.focus(); return false; } if (email.value == \"\") { window.alert( \"Please enter a valid e-mail address.\"); email.focus(); return false; } if (phone.value == \"\") { window.alert( \"Please enter your telephone number.\"); phone.focus(); return false; } if (password.value == \"\") { window.alert(\"Please enter your password\"); password.focus(); return false; } if (what.selectedIndex < 1) { alert(\"Please enter your course.\"); what.focus(); return false; } return true; }</script>",
"e": 33607,
"s": 32248,
"text": null
},
{
"code": null,
"e": 33625,
"s": 33607,
"text": "Styling the form:"
},
{
"code": "<style>div { box-sizing: border-box; width: 100%; border: 100px solid black; float: left; align-content: center; align-items: center;} form { margin: 0 auto; width: 600px;}</style>",
"e": 33836,
"s": 33625,
"text": null
},
{
"code": null,
"e": 33886,
"s": 33836,
"text": "COMBINED CODE [ALL OF THE ABOVE SECTIONS CLUBBED)"
},
{
"code": "<html> <head> <script> function GEEKFORGEEKS() { var name = document.forms[\"RegForm\"][\"Name\"]; var email = document.forms[\"RegForm\"][\"EMail\"]; var phone = document.forms[\"RegForm\"][\"Telephone\"]; var what = document.forms[\"RegForm\"][\"Subject\"]; var password = document.forms[\"RegForm\"][\"Password\"]; var address = document.forms[\"RegForm\"][\"Address\"]; if (name.value == \"\") { window.alert(\"Please enter your name.\"); name.focus(); return false; } if (address.value == \"\") { window.alert(\"Please enter your address.\"); address.focus(); return false; } if (email.value == \"\") { window.alert( \"Please enter a valid e-mail address.\"); email.focus(); return false; } if (phone.value == \"\") { window.alert( \"Please enter your telephone number.\"); phone.focus(); return false; } if (password.value == \"\") { window.alert(\"Please enter your password\"); password.focus(); return false; } if (what.selectedIndex < 1) { alert(\"Please enter your course.\"); what.focus(); return false; } return true; } </script> <style> div { box-sizing: border-box; width: 100%; border: 100px solid black; float: left; align-content: center; align-items: center; } form { margin: 0 auto; width: 600px; } </style> </head> <body> <h1 style=\"text-align: center;\">REGISTRATION FORM</h1> <form name=\"RegForm\" action=\"/submit.php\" onsubmit=\"return GEEKFORGEEKS()\" method=\"post\"> <p>Name: <input type=\"text\" size=\"65\" name=\"Name\" /></p> <br /> <p>Address: <input type=\"text\" size=\"65\" name=\"Address\" /> </p> <br /> <p>E-mail Address: <input type=\"text\" size=\"65\" name=\"EMail\" /></p> <br /> <p>Password: <input type=\"text\" size=\"65\" name=\"Password\" /></p> <br /> <p>Telephone: <input type=\"text\" size=\"65\" name=\"Telephone\" /></p> <br /> <p> SELECT YOUR COURSE <select type=\"text\" value=\"\" name=\"Subject\"> <option>BTECH</option> <option>BBA</option> <option>BCA</option> <option>B.COM</option> <option>GEEKFORGEEKS</option> </select> </p> <br /> <br /> <p>Comments: <textarea cols=\"55\" name=\"Comment\"> </textarea></p> <p> <input type=\"submit\" value=\"send\" name=\"Submit\" /> <input type=\"reset\" value=\"Reset\" name=\"Reset\" /> </p> </form> </body></html> // updated by patelshrey115",
"e": 37676,
"s": 33886,
"text": null
},
{
"code": null,
"e": 37692,
"s": 37676,
"text": "Resulting Form:"
},
{
"code": null,
"e": 37746,
"s": 37692,
"text": "Reference : https://en.wikipedia.org/wiki/Form_(HTML)"
},
{
"code": null,
"e": 37940,
"s": 37746,
"text": "HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples."
},
{
"code": null,
"e": 38159,
"s": 37940,
"text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples."
},
{
"code": null,
"e": 38169,
"s": 38159,
"text": "xXShreyXx"
},
{
"code": null,
"e": 38180,
"s": 38169,
"text": "bunnyram19"
},
{
"code": null,
"e": 38190,
"s": 38180,
"text": "HTML-Misc"
},
{
"code": null,
"e": 38206,
"s": 38190,
"text": "javascript-form"
},
{
"code": null,
"e": 38211,
"s": 38206,
"text": "HTML"
},
{
"code": null,
"e": 38222,
"s": 38211,
"text": "JavaScript"
},
{
"code": null,
"e": 38239,
"s": 38222,
"text": "Web Technologies"
},
{
"code": null,
"e": 38244,
"s": 38239,
"text": "HTML"
},
{
"code": null,
"e": 38342,
"s": 38244,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38404,
"s": 38342,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 38454,
"s": 38404,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 38514,
"s": 38454,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 38562,
"s": 38514,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 38623,
"s": 38562,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 38668,
"s": 38623,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 38729,
"s": 38668,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 38798,
"s": 38729,
"text": "How to calculate the number of days between two dates in javascript?"
},
{
"code": null,
"e": 38870,
"s": 38798,
"text": "Differences between Functional Components and Class Components in React"
}
] |
Compute Beta Distribution in R Programming - dbeta(), pbeta(), qbeta(), and rbeta() Functions - GeeksforGeeks
|
23 Jun, 2020
Beta Distribution in R Language is defined as property which represents the possible values of probability. This article is an illustration of dbeta, pbeta, qbeta, and rbeta functions of Beta Distribution.
It is defined as Beta Density function and is used to create beta density value corresponding to the vector of quantiles.
Syntax:dbeta(vec, shape1, shape2)
Parameter:vec: Vector to be usedshape1, shape2: beta density of input values
Returns: beta density values for a vector of quantiles
Example :
# R program to illustrate the use of # dbeta() function # Creating a vectorx_beta <- seq(0, 1.5, by = 0.025 ) # Apply beta function y_beta <- dbeta(x_beta, shape1 = 2, shape2 = 4.5) # Plot beta valuesplot(y_beta)
Output:
It is used to create cumulative distribution function of the beta distribution.
Syntax:pbeta(vec, shape1, shape2)
Parameter:vec: Vector to be usedshape1, shape2: beta density of input values
Example:
# Specify x-values for pbeta functionx_pbeta <- seq(0, 1, by = 0.025) # Apply pbeta() functiony_pbeta <- pbeta(x_pbeta, shape1 = 1, shape2 = 4) # Plot pbeta valuesplot(y_pbeta)
Output:
It is known as beta quantile function and used t return quantile values of the function.
Syntax:qbeta(vec, shape1, shape2)
Parameters:vec: Vector to be usedshape1, shape2: beta density of input values
Example:
# Specify x-values for qbeta() functionx_qbeta <- seq(0, 1, by = 0.025) # Apply qbeta() functiony_qbeta <- qbeta(x_qbeta, shape1 = 1, shape2 = 4) # Plot qbeta() valuesplot(y_qbeta)
Output:
It is defined as a random number generator that is used to set seed and specify sample size.
Syntax:rbeta(N, shape1, shape2 )
Parameters:vec: Vector to be usedshape1, shape2: beta density of input values
Example:
# Set seed for reproducibilityset.seed(13579) # Specify sample sizeN <- 10000 # Draw N beta distributed valuesy_rbeta <- rbeta(N, shape1 = 1, shape2 = 5) y_rbeta # Plot of randomly drawn beta densityplot(density(y_rbeta), main = "beta Distribution in R")
Output:
R Math-Function
R-Statistics
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Replace specific values in column in R DataFrame ?
How to change Row Names of DataFrame in R ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Change Color of Bars in Barchart using ggplot2 in R
Printing Output of an R Program
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
K-Means Clustering in R Programming
|
[
{
"code": null,
"e": 25043,
"s": 25015,
"text": "\n23 Jun, 2020"
},
{
"code": null,
"e": 25249,
"s": 25043,
"text": "Beta Distribution in R Language is defined as property which represents the possible values of probability. This article is an illustration of dbeta, pbeta, qbeta, and rbeta functions of Beta Distribution."
},
{
"code": null,
"e": 25371,
"s": 25249,
"text": "It is defined as Beta Density function and is used to create beta density value corresponding to the vector of quantiles."
},
{
"code": null,
"e": 25405,
"s": 25371,
"text": "Syntax:dbeta(vec, shape1, shape2)"
},
{
"code": null,
"e": 25482,
"s": 25405,
"text": "Parameter:vec: Vector to be usedshape1, shape2: beta density of input values"
},
{
"code": null,
"e": 25537,
"s": 25482,
"text": "Returns: beta density values for a vector of quantiles"
},
{
"code": null,
"e": 25547,
"s": 25537,
"text": "Example :"
},
{
"code": "# R program to illustrate the use of # dbeta() function # Creating a vectorx_beta <- seq(0, 1.5, by = 0.025 ) # Apply beta function y_beta <- dbeta(x_beta, shape1 = 2, shape2 = 4.5) # Plot beta valuesplot(y_beta) ",
"e": 25815,
"s": 25547,
"text": null
},
{
"code": null,
"e": 25823,
"s": 25815,
"text": "Output:"
},
{
"code": null,
"e": 25903,
"s": 25823,
"text": "It is used to create cumulative distribution function of the beta distribution."
},
{
"code": null,
"e": 25937,
"s": 25903,
"text": "Syntax:pbeta(vec, shape1, shape2)"
},
{
"code": null,
"e": 26014,
"s": 25937,
"text": "Parameter:vec: Vector to be usedshape1, shape2: beta density of input values"
},
{
"code": null,
"e": 26023,
"s": 26014,
"text": "Example:"
},
{
"code": "# Specify x-values for pbeta functionx_pbeta <- seq(0, 1, by = 0.025) # Apply pbeta() functiony_pbeta <- pbeta(x_pbeta, shape1 = 1, shape2 = 4) # Plot pbeta valuesplot(y_pbeta)",
"e": 26210,
"s": 26023,
"text": null
},
{
"code": null,
"e": 26218,
"s": 26210,
"text": "Output:"
},
{
"code": null,
"e": 26307,
"s": 26218,
"text": "It is known as beta quantile function and used t return quantile values of the function."
},
{
"code": null,
"e": 26341,
"s": 26307,
"text": "Syntax:qbeta(vec, shape1, shape2)"
},
{
"code": null,
"e": 26419,
"s": 26341,
"text": "Parameters:vec: Vector to be usedshape1, shape2: beta density of input values"
},
{
"code": null,
"e": 26428,
"s": 26419,
"text": "Example:"
},
{
"code": " # Specify x-values for qbeta() functionx_qbeta <- seq(0, 1, by = 0.025) # Apply qbeta() functiony_qbeta <- qbeta(x_qbeta, shape1 = 1, shape2 = 4) # Plot qbeta() valuesplot(y_qbeta) ",
"e": 26618,
"s": 26428,
"text": null
},
{
"code": null,
"e": 26626,
"s": 26618,
"text": "Output:"
},
{
"code": null,
"e": 26719,
"s": 26626,
"text": "It is defined as a random number generator that is used to set seed and specify sample size."
},
{
"code": null,
"e": 26752,
"s": 26719,
"text": "Syntax:rbeta(N, shape1, shape2 )"
},
{
"code": null,
"e": 26830,
"s": 26752,
"text": "Parameters:vec: Vector to be usedshape1, shape2: beta density of input values"
},
{
"code": null,
"e": 26839,
"s": 26830,
"text": "Example:"
},
{
"code": "# Set seed for reproducibilityset.seed(13579) # Specify sample sizeN <- 10000 # Draw N beta distributed valuesy_rbeta <- rbeta(N, shape1 = 1, shape2 = 5) y_rbeta # Plot of randomly drawn beta densityplot(density(y_rbeta), main = \"beta Distribution in R\")",
"e": 27106,
"s": 26839,
"text": null
},
{
"code": null,
"e": 27114,
"s": 27106,
"text": "Output:"
},
{
"code": null,
"e": 27130,
"s": 27114,
"text": "R Math-Function"
},
{
"code": null,
"e": 27143,
"s": 27130,
"text": "R-Statistics"
},
{
"code": null,
"e": 27154,
"s": 27143,
"text": "R Language"
},
{
"code": null,
"e": 27252,
"s": 27154,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27261,
"s": 27252,
"text": "Comments"
},
{
"code": null,
"e": 27274,
"s": 27261,
"text": "Old Comments"
},
{
"code": null,
"e": 27332,
"s": 27274,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 27376,
"s": 27332,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 27428,
"s": 27376,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 27460,
"s": 27428,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 27512,
"s": 27460,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 27544,
"s": 27512,
"text": "Printing Output of an R Program"
},
{
"code": null,
"e": 27582,
"s": 27544,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 27617,
"s": 27582,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 27675,
"s": 27617,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
}
] |
6 Key differences between np.ndarray and np.matrix objects | by Rukshan Pramoditha | Towards Data Science
|
Numpy is the foundational Python library that is widely used for numerical calculations and linear algebra. ndarray and matrix objects are commonly used numpy objects. ndarray objects are created from the numpy ndarray class. matrix objects are created from the numpy matrix class. If you’re new to numpy, you may get confused with numpy ndarray and numpy matrix objects. They are two different things if they seem to be the same in appearance. Today, we’ll discuss 6 such differences between them.
I recommend you to read the following content written by me.
NumPy for Data Science: Part 1 — NumPy Basics and Array Creation
We can use np.array() function to create an ndarray object.
import numpy as npA = np.array([[1, 2], [3, 4]])print(A)print()print(type(A))
We can use the np.matrix() function to create a matrix object.
import numpy as npB = np.matrix([[1, 2], [3, 4]])print(B)print()print(type(B))
Even if both ndarray and matrix objects are the same in appearance, they belong to two different classes have different functionalities. Let’s discuss them now.
We can create 1d, 2d, 3d, even 4d, 5d (but they’re hard to imagine) ndarray objects, but we can only create 2d matrix objects.
1-dimensional array
import numpy as npA = np.array([1, 2, 3])print(A)print('\nDimensions:', A.shape)print('No. of Dimensions:', A.ndim)
2-dimensional array
import numpy as npB = np.array([[1, 2], [3, 4]])print(B)print('\nDimensions:', B.shape)print('No. of Dimensions:', B.ndim)
3-dimensional array
import numpy as npC = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]])print(C)print('\nDimensions:', C.shape)print('No. of Dimensions:', C.ndim)
Matrix objects are strictly 2-dimensional. If we try to create a 1d matrix, it automatically creates a 2d matrix.
import numpy as npA = np.matrix([1, 2, 3])print(A)print()print(type(A))print('Dimensions:', A.shape)print('No. of Dimensions:', A.ndim)
If we try to create a 3d matrix, it gives an error.
np.matrix([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]])
When we multiply two ndarray objects using the * operator, the result is the element-by-element multiplication.
a = np.array([[1, 2], [3, 4]])b = np.array([[5, 6], [8, 9]])print("a", type(a))print(a)print("\nb", type(b))print(b)print("\n* operation on two ndarray objects (Elementwise)")print(a * b)
When we multiply two matrix objects using the * operator, the result is the dot (matrix) product.
c = np.matrix([[1, 2], [3, 4]])d = np.matrix([[5, 6], [8, 9]])print("c", type(c))print(c)print("\nd", type(d))print(d)print("\n* operation on two matrix objects")print(c * d)
When we use the ** operator on two ndarray objects, the result is the elementwise squared values of each element.
a = np.array([[1, 2], [3, 4]])print("a", type(a))print(a)print("\n** operation on two ndarray objects (Elementwise)")print(a ** 2)
When we use the ** operator on two matrix objects, the result is a matrix multiplication!
b = np.matrix([[1, 2], [3, 4]])print(b)print("\n** operation on two matrix objects")print(b ** 2)
Matrix objects inherit all the attributes and methods of ndarray objects.
a = np.matrix([[1, 2], [3, 4]])print(a)print('\nInverse')print(a.I)
b = np.array([[1, 2], [3, 4]])print(b)print('\nInverse')print(b.I)
To get the inverse of an ndarray object, use np.linalg.inv() function.
np.linalg.inv(b)
Here is what numpy documentation says about the usage of these two classes.
It is no longer recommended to use the matrix class, even for linear algebra. Instead, use regular numpy arrays. The matrix class may be removed in the future.
ndarray and matrix classes behave differently. It may be much easier to use the matrix class because it is like using matrices in linear algebra. If you need to work on multi-dimensional arrays, you should use the ndarray objects as they are multi-dimensional. Numpy documentation recommends you using ndarray objects instead of matrix objects. You can always convert one class type into another by using an appropriate function. Therefore, use the np.asmatrix() function to convert an ndarray object into a matrix object.
a = np.array([[1, 2], [3, 4]])print(a)print(type(a))print()b = np.asmatrix(a)print(b)print(type(b))
Also, you can use the np.asarray() function to convert a matrix object into an ndarray object.
a = np.matrix([[1, 2], [3, 4]])print(a)print(type(a))print()b = np.asarray(a)print(b)print(type(b))
Thanks for reading!
This tutorial was designed and created by Rukshan Pramoditha, the Author of Data Science 365 Blog.
Read my other articles at https://rukshanpramoditha.medium.com
|
[
{
"code": null,
"e": 670,
"s": 171,
"text": "Numpy is the foundational Python library that is widely used for numerical calculations and linear algebra. ndarray and matrix objects are commonly used numpy objects. ndarray objects are created from the numpy ndarray class. matrix objects are created from the numpy matrix class. If you’re new to numpy, you may get confused with numpy ndarray and numpy matrix objects. They are two different things if they seem to be the same in appearance. Today, we’ll discuss 6 such differences between them."
},
{
"code": null,
"e": 731,
"s": 670,
"text": "I recommend you to read the following content written by me."
},
{
"code": null,
"e": 796,
"s": 731,
"text": "NumPy for Data Science: Part 1 — NumPy Basics and Array Creation"
},
{
"code": null,
"e": 856,
"s": 796,
"text": "We can use np.array() function to create an ndarray object."
},
{
"code": null,
"e": 947,
"s": 856,
"text": "import numpy as npA = np.array([[1, 2], [3, 4]])print(A)print()print(type(A))"
},
{
"code": null,
"e": 1010,
"s": 947,
"text": "We can use the np.matrix() function to create a matrix object."
},
{
"code": null,
"e": 1103,
"s": 1010,
"text": "import numpy as npB = np.matrix([[1, 2], [3, 4]])print(B)print()print(type(B))"
},
{
"code": null,
"e": 1264,
"s": 1103,
"text": "Even if both ndarray and matrix objects are the same in appearance, they belong to two different classes have different functionalities. Let’s discuss them now."
},
{
"code": null,
"e": 1391,
"s": 1264,
"text": "We can create 1d, 2d, 3d, even 4d, 5d (but they’re hard to imagine) ndarray objects, but we can only create 2d matrix objects."
},
{
"code": null,
"e": 1411,
"s": 1391,
"text": "1-dimensional array"
},
{
"code": null,
"e": 1527,
"s": 1411,
"text": "import numpy as npA = np.array([1, 2, 3])print(A)print('\\nDimensions:', A.shape)print('No. of Dimensions:', A.ndim)"
},
{
"code": null,
"e": 1547,
"s": 1527,
"text": "2-dimensional array"
},
{
"code": null,
"e": 1683,
"s": 1547,
"text": "import numpy as npB = np.array([[1, 2], [3, 4]])print(B)print('\\nDimensions:', B.shape)print('No. of Dimensions:', B.ndim)"
},
{
"code": null,
"e": 1703,
"s": 1683,
"text": "3-dimensional array"
},
{
"code": null,
"e": 1891,
"s": 1703,
"text": "import numpy as npC = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]])print(C)print('\\nDimensions:', C.shape)print('No. of Dimensions:', C.ndim)"
},
{
"code": null,
"e": 2005,
"s": 1891,
"text": "Matrix objects are strictly 2-dimensional. If we try to create a 1d matrix, it automatically creates a 2d matrix."
},
{
"code": null,
"e": 2141,
"s": 2005,
"text": "import numpy as npA = np.matrix([1, 2, 3])print(A)print()print(type(A))print('Dimensions:', A.shape)print('No. of Dimensions:', A.ndim)"
},
{
"code": null,
"e": 2193,
"s": 2141,
"text": "If we try to create a 3d matrix, it gives an error."
},
{
"code": null,
"e": 2282,
"s": 2193,
"text": "np.matrix([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]])"
},
{
"code": null,
"e": 2394,
"s": 2282,
"text": "When we multiply two ndarray objects using the * operator, the result is the element-by-element multiplication."
},
{
"code": null,
"e": 2608,
"s": 2394,
"text": "a = np.array([[1, 2], [3, 4]])b = np.array([[5, 6], [8, 9]])print(\"a\", type(a))print(a)print(\"\\nb\", type(b))print(b)print(\"\\n* operation on two ndarray objects (Elementwise)\")print(a * b)"
},
{
"code": null,
"e": 2706,
"s": 2608,
"text": "When we multiply two matrix objects using the * operator, the result is the dot (matrix) product."
},
{
"code": null,
"e": 2909,
"s": 2706,
"text": "c = np.matrix([[1, 2], [3, 4]])d = np.matrix([[5, 6], [8, 9]])print(\"c\", type(c))print(c)print(\"\\nd\", type(d))print(d)print(\"\\n* operation on two matrix objects\")print(c * d)"
},
{
"code": null,
"e": 3023,
"s": 2909,
"text": "When we use the ** operator on two ndarray objects, the result is the elementwise squared values of each element."
},
{
"code": null,
"e": 3167,
"s": 3023,
"text": "a = np.array([[1, 2], [3, 4]])print(\"a\", type(a))print(a)print(\"\\n** operation on two ndarray objects (Elementwise)\")print(a ** 2)"
},
{
"code": null,
"e": 3257,
"s": 3167,
"text": "When we use the ** operator on two matrix objects, the result is a matrix multiplication!"
},
{
"code": null,
"e": 3369,
"s": 3257,
"text": "b = np.matrix([[1, 2], [3, 4]])print(b)print(\"\\n** operation on two matrix objects\")print(b ** 2)"
},
{
"code": null,
"e": 3443,
"s": 3369,
"text": "Matrix objects inherit all the attributes and methods of ndarray objects."
},
{
"code": null,
"e": 3525,
"s": 3443,
"text": "a = np.matrix([[1, 2], [3, 4]])print(a)print('\\nInverse')print(a.I)"
},
{
"code": null,
"e": 3605,
"s": 3525,
"text": "b = np.array([[1, 2], [3, 4]])print(b)print('\\nInverse')print(b.I)"
},
{
"code": null,
"e": 3676,
"s": 3605,
"text": "To get the inverse of an ndarray object, use np.linalg.inv() function."
},
{
"code": null,
"e": 3693,
"s": 3676,
"text": "np.linalg.inv(b)"
},
{
"code": null,
"e": 3769,
"s": 3693,
"text": "Here is what numpy documentation says about the usage of these two classes."
},
{
"code": null,
"e": 3929,
"s": 3769,
"text": "It is no longer recommended to use the matrix class, even for linear algebra. Instead, use regular numpy arrays. The matrix class may be removed in the future."
},
{
"code": null,
"e": 4452,
"s": 3929,
"text": "ndarray and matrix classes behave differently. It may be much easier to use the matrix class because it is like using matrices in linear algebra. If you need to work on multi-dimensional arrays, you should use the ndarray objects as they are multi-dimensional. Numpy documentation recommends you using ndarray objects instead of matrix objects. You can always convert one class type into another by using an appropriate function. Therefore, use the np.asmatrix() function to convert an ndarray object into a matrix object."
},
{
"code": null,
"e": 4565,
"s": 4452,
"text": "a = np.array([[1, 2], [3, 4]])print(a)print(type(a))print()b = np.asmatrix(a)print(b)print(type(b))"
},
{
"code": null,
"e": 4660,
"s": 4565,
"text": "Also, you can use the np.asarray() function to convert a matrix object into an ndarray object."
},
{
"code": null,
"e": 4760,
"s": 4660,
"text": "a = np.matrix([[1, 2], [3, 4]])print(a)print(type(a))print()b = np.asarray(a)print(b)print(type(b))"
},
{
"code": null,
"e": 4780,
"s": 4760,
"text": "Thanks for reading!"
},
{
"code": null,
"e": 4879,
"s": 4780,
"text": "This tutorial was designed and created by Rukshan Pramoditha, the Author of Data Science 365 Blog."
}
] |
Java Generics - Classes
|
A generic class declaration looks like a non-generic class declaration, except that the class name is followed by a type parameter section.
The type parameter section of a generic class can have one or more type parameters separated by commas. These classes are known as parameterized classes or parameterized types because they accept one or more parameters.
public class Box<T> {
private T t;
}
Where
Box − Box is a generic class.
Box − Box is a generic class.
T − The generic type parameter passed to generic class. It can take any Object.
T − The generic type parameter passed to generic class. It can take any Object.
t − Instance of generic type T.
t − Instance of generic type T.
The T is a type parameter passed to the generic class Box and should be passed when a Box object is created.
Create the following java program using any editor of your choice.
GenericsTester.java
package com.tutorialspoint;
public class GenericsTester {
public static void main(String[] args) {
Box<Integer> integerBox = new Box<Integer>();
Box<String> stringBox = new Box<String>();
integerBox.add(new Integer(10));
stringBox.add(new String("Hello World"));
System.out.printf("Integer Value :%d\n", integerBox.get());
System.out.printf("String Value :%s\n", stringBox.get());
}
}
class Box<T> {
private T t;
public void add(T t) {
this.t = t;
}
public T get() {
return t;
}
}
This will produce the following result.
Integer Value :10
String Value :Hello World
16 Lectures
2 hours
Malhar Lathkar
19 Lectures
5 hours
Malhar Lathkar
25 Lectures
2.5 hours
Anadi Sharma
126 Lectures
7 hours
Tushar Kale
119 Lectures
17.5 hours
Monica Mittal
76 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2780,
"s": 2640,
"text": "A generic class declaration looks like a non-generic class declaration, except that the class name is followed by a type parameter section."
},
{
"code": null,
"e": 3000,
"s": 2780,
"text": "The type parameter section of a generic class can have one or more type parameters separated by commas. These classes are known as parameterized classes or parameterized types because they accept one or more parameters."
},
{
"code": null,
"e": 3041,
"s": 3000,
"text": "public class Box<T> {\n private T t;\n}\n"
},
{
"code": null,
"e": 3047,
"s": 3041,
"text": "Where"
},
{
"code": null,
"e": 3077,
"s": 3047,
"text": "Box − Box is a generic class."
},
{
"code": null,
"e": 3107,
"s": 3077,
"text": "Box − Box is a generic class."
},
{
"code": null,
"e": 3187,
"s": 3107,
"text": "T − The generic type parameter passed to generic class. It can take any Object."
},
{
"code": null,
"e": 3267,
"s": 3187,
"text": "T − The generic type parameter passed to generic class. It can take any Object."
},
{
"code": null,
"e": 3299,
"s": 3267,
"text": "t − Instance of generic type T."
},
{
"code": null,
"e": 3331,
"s": 3299,
"text": "t − Instance of generic type T."
},
{
"code": null,
"e": 3440,
"s": 3331,
"text": "The T is a type parameter passed to the generic class Box and should be passed when a Box object is created."
},
{
"code": null,
"e": 3507,
"s": 3440,
"text": "Create the following java program using any editor of your choice."
},
{
"code": null,
"e": 3527,
"s": 3507,
"text": "GenericsTester.java"
},
{
"code": null,
"e": 4086,
"s": 3527,
"text": "package com.tutorialspoint;\n\npublic class GenericsTester {\n public static void main(String[] args) {\n Box<Integer> integerBox = new Box<Integer>();\n Box<String> stringBox = new Box<String>();\n\n integerBox.add(new Integer(10));\n stringBox.add(new String(\"Hello World\"));\n\n System.out.printf(\"Integer Value :%d\\n\", integerBox.get());\n System.out.printf(\"String Value :%s\\n\", stringBox.get());\n }\n}\n\nclass Box<T> {\n private T t;\n\n public void add(T t) {\n this.t = t;\n }\n\n public T get() {\n return t;\n } \n}"
},
{
"code": null,
"e": 4126,
"s": 4086,
"text": "This will produce the following result."
},
{
"code": null,
"e": 4171,
"s": 4126,
"text": "Integer Value :10\nString Value :Hello World\n"
},
{
"code": null,
"e": 4204,
"s": 4171,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4220,
"s": 4204,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 4253,
"s": 4220,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 4269,
"s": 4253,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 4304,
"s": 4269,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4318,
"s": 4304,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4352,
"s": 4318,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 4366,
"s": 4352,
"text": " Tushar Kale"
},
{
"code": null,
"e": 4403,
"s": 4366,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 4418,
"s": 4403,
"text": " Monica Mittal"
},
{
"code": null,
"e": 4451,
"s": 4418,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 4470,
"s": 4451,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4477,
"s": 4470,
"text": " Print"
},
{
"code": null,
"e": 4488,
"s": 4477,
"text": " Add Notes"
}
] |
Intro to NLTK for NLP with Python - Tokenization, Stopwords, Stemming, and PoS Tagging | Towards Data Science
|
NLTK (Natural Language Toolkit) is the go-to API for NLP (Natural Language Processing) with Python. It is a really powerful tool to preprocess text data for further analysis like with ML models for instance. It helps convert text into numbers, which the model can then easily work with. This is the first part of a basic introduction to NLTK for getting your feet wet and assumes some basic knowledge of Python.
First, you want to install NLTK using pip (or conda). The command for this is pretty straightforward for both Mac and Windows: pip install nltk . If this does not work, try taking a look at this page from the documentation. Note, you must have at least version — 3.5 of Python for NLTK.
To check if NLTK is installed properly, just type import nltk in your IDE. If it runs without any error, congrats! But hold ‘up, there’s still a bunch of stuff to download and install. In your IDE, after importing, continue to the next line and type nltk.download() and run this script. An installation window will pop up. Select all and click ‘Download’ to download and install the additional bundles. This will download all the dictionaries and other language and grammar data frames necessary for full NLTK functionality. NLTK fully supports the English language, but others like Spanish or French are not supported as extensively. Now we are ready to process our first natural language.
One of the very basic things we want to do is dividing a body of text into words or sentences. This is called tokenization.
from nltk import word_tokenize, sent_tokenizesent = "I will walk 500 miles and I would walk 500 more, just to be the man who walks a thousand miles to fall down at your door!"print(word_tokenize(sent))print(sent_tokenize(sent))output: [‘I’, ‘will’, ‘walk’, ‘500’, ‘miles’, ‘.’, ‘And’, ‘I’, ‘would’, ‘walk’, ‘500’, ‘more’, ‘,’, ‘just’, ‘to’, ‘be’, ‘the’, ‘man’, ‘who’, ‘walks’, ‘a’, ‘thousand’, ‘miles’, ‘to’, ‘fall’, ‘down’, ‘at’, ‘your’, ‘door’, ‘.’][‘I will walk 500 miles.’, ‘And I would walk 500 more, just to be the man who walks a thousand miles to fall down at your door.’]
We get the body of text elegantly converted into a list. The above tokenization without NLTK would take hours and hours of coding with regular expressions! You may wonder about the punctuation marks though. This is something we will have to care of separately. We could also use other tokenizers like the PunktSentenceTokenizer, which is a pre-trained unsupervised ML model. We can even train it ourselves if we want using our own dataset. Keep an eye out for my future articles. **insert shameless self-promoting call to follow** :3
Stop-words are basically words that don’t have strong meaningful connotations for instance, ‘and’, ‘a’, ‘it's’, ‘they’, etc. These have a meaningful impact when we use them to communicate with each other but for analysis by a computer, they are not really that useful (well, they probably could be but computer algorithms are not that clever yet to decipher their contextual impact accurately, to be honest). Let’s see an example:
from nltk.corpus import stopwords # the corpus module is an # extremely useful one. # More on that later.stop_words = stopwords.words('english') # this is the full list of # all stop-words stored in # nltktoken = word_tokenize(sent)cleaned_token = []for word in token: if word not in stop_words: cleaned_token.append(word)print("This is the unclean version:", token)print("This is the cleaned version:", cleaned_token)output: This is the unclean version: ['I', 'will', 'walk', '500', 'miles', 'and', 'I', 'would', 'walk', '500', 'more', ',', 'just', 'to', 'be', 'the', 'man', 'who', 'walks', 'a', 'thousand', 'miles', 'to', 'fall', 'down', 'at', 'your', 'door', '.']This is the cleaned version: ['I', 'walk', '500', 'miles', 'I', 'would', 'walk', '500', ',', 'man', 'walks', 'thousand', 'miles', 'fall', 'door', '.']
As you can see many of the words like ‘will’, ‘and’ are removed. This will save massive amounts of computation power and hence time if we were to shove bodies of texts with lots of “fluff” words into an ML model.
This is when ‘fluff’ letters (not words) are removed from a word and grouped together with its “stem form”. For instance, the words ‘play’, ‘playing’, or ‘plays’ convey the same meaning (although, again, not exactly, but for analysis with a computer, that sort of detail is still not a viable option). So instead of having them as different words, we can put them together under the same umbrella term ‘play’.
from nltk.stem import PorterStemmerstemmer = PorterStemmer()words = ['play', 'playing', 'plays', 'played', 'playfullness', 'playful']stemmed = [stemmer.stem(word) for word in words]print(stemmed)output:['play', 'play', 'play', 'play', 'playful', 'play']
We used the PorterStemmer, which is a pre-written stemmer class. There are other stemmers like SnowballStemmer and LancasterStemmer but PorterStemmer is sort of the simplest one. ‘Play’ and ‘Playful’ should have been recognized as two different words however. Notice how the last ‘playful’ got recognized as ‘play’ and not ‘playful’. This is where the simplicity of the PorterStemmer is undesirable. You can also train your own using unsupervised clustering or supervised classification ML models. Now let’s stem an actual sentence!
sent2 = "I played the play playfully as the players were playing in the play with playfullness"token = word_tokenize(sent2)stemmed = ""for word in token: stemmed += stemmer.stem(word) + " "print(stemmed)output:I play the play play as the player were play in the play with playful .
This can now be efficiently tokenized for further processing or analysis. Pretty neat, right?!
The next essential thing we want to do is tagging each word in the corpus (a corpus is just a ‘bag’ of words) we created after converting sentences by tokenizing.
from nltk import pos_tag token = word_tokenize(sent) + word_tokenize(sent2)tagged = pos_tag(cleaned_token) print(tagged)output: [('I', 'PRP'), ('will', 'MD'), ('walk', 'VB'), ('500', 'CD'), ('miles', 'NNS'), ('and', 'CC'), ('I', 'PRP'), ('would', 'MD'), ('walk', 'VB'), ('500', 'CD'), ('more', 'JJR'), (',', ','), ('just', 'RB'), ('to', 'TO'), ('be', 'VB'), ('the', 'DT'), ('man', 'NN'), ('who', 'WP'), ('walks', 'VBZ'), ('a', 'DT'), ('thousand', 'NN'), ('miles', 'NNS'), ('to', 'TO'), ('fall', 'VB'), ('down', 'RP'), ('at', 'IN'), ('your', 'PRP$'), ('door', 'NN'), ('.', '.'), ('I', 'PRP'), ('played', 'VBD'), ('the', 'DT'), ('play', 'NN'), ('playfully', 'RB'), ('as', 'IN'), ('the', 'DT'), ('players', 'NNS'), ('were', 'VBD'), ('playing', 'VBG'), ('in', 'IN'), ('the', 'DT'), ('play', 'NN'), ('with', 'IN'), ('playfullness', 'NN'), ('.', '.')]
The pos_tag() method takes in a list of tokenized words, and tags each of them with a corresponding Parts of Speech identifier into tuples. For example, VB refers to ‘verb’, NNS refers to ‘plural nouns’, DT refers to a ‘determiner’. Refer to this website for a list of tags. These tags are almost always pretty accurate but we should be aware that they can be inaccurate at times. However, pre-trained models usually assume the English being used is written properly, following the grammatical rules.
This can be a problem when analyzing informal texts like from the internet. Remember the data frames we downloaded after pip installing NLTK? Those contain the datasets that were used to train these models initially. To apply these models in the context of our own interests, we would need to train these models on new datasets containing informal languages first.
In my future articles, I will talk more about NLTK basics and how we can use built-in methods of NLTK to easily train our own ML models. For further resources, you can check out the NLTK documentation and the book.
This article from 2001 titled “Unreasonable Effectiveness of Data” illustrated how inefficient data can be when it comes to deciphering meaningful patterns and trends from them, no matter which ML algorithm we use. But that is not a problem when it comes to text data. THE most abundant form of data available on the internet is text data. Imagine the potentials and the possibilities of the applications of ML on this humungous database. But the first barrier to actually utilizing these heaps of data is converting them into computation-friendly formats for ML algorithms for analysis, which is the preprocessing stage that NLTK holds the key to. Happy learning!
towardsdatascience.com
P.S. If you want more short, to the point articles on Data Science and how a biologist navigates his way through the Data revolution, consider following my blog.
|
[
{
"code": null,
"e": 584,
"s": 172,
"text": "NLTK (Natural Language Toolkit) is the go-to API for NLP (Natural Language Processing) with Python. It is a really powerful tool to preprocess text data for further analysis like with ML models for instance. It helps convert text into numbers, which the model can then easily work with. This is the first part of a basic introduction to NLTK for getting your feet wet and assumes some basic knowledge of Python."
},
{
"code": null,
"e": 871,
"s": 584,
"text": "First, you want to install NLTK using pip (or conda). The command for this is pretty straightforward for both Mac and Windows: pip install nltk . If this does not work, try taking a look at this page from the documentation. Note, you must have at least version — 3.5 of Python for NLTK."
},
{
"code": null,
"e": 1562,
"s": 871,
"text": "To check if NLTK is installed properly, just type import nltk in your IDE. If it runs without any error, congrats! But hold ‘up, there’s still a bunch of stuff to download and install. In your IDE, after importing, continue to the next line and type nltk.download() and run this script. An installation window will pop up. Select all and click ‘Download’ to download and install the additional bundles. This will download all the dictionaries and other language and grammar data frames necessary for full NLTK functionality. NLTK fully supports the English language, but others like Spanish or French are not supported as extensively. Now we are ready to process our first natural language."
},
{
"code": null,
"e": 1686,
"s": 1562,
"text": "One of the very basic things we want to do is dividing a body of text into words or sentences. This is called tokenization."
},
{
"code": null,
"e": 2267,
"s": 1686,
"text": "from nltk import word_tokenize, sent_tokenizesent = \"I will walk 500 miles and I would walk 500 more, just to be the man who walks a thousand miles to fall down at your door!\"print(word_tokenize(sent))print(sent_tokenize(sent))output: [‘I’, ‘will’, ‘walk’, ‘500’, ‘miles’, ‘.’, ‘And’, ‘I’, ‘would’, ‘walk’, ‘500’, ‘more’, ‘,’, ‘just’, ‘to’, ‘be’, ‘the’, ‘man’, ‘who’, ‘walks’, ‘a’, ‘thousand’, ‘miles’, ‘to’, ‘fall’, ‘down’, ‘at’, ‘your’, ‘door’, ‘.’][‘I will walk 500 miles.’, ‘And I would walk 500 more, just to be the man who walks a thousand miles to fall down at your door.’]"
},
{
"code": null,
"e": 2801,
"s": 2267,
"text": "We get the body of text elegantly converted into a list. The above tokenization without NLTK would take hours and hours of coding with regular expressions! You may wonder about the punctuation marks though. This is something we will have to care of separately. We could also use other tokenizers like the PunktSentenceTokenizer, which is a pre-trained unsupervised ML model. We can even train it ourselves if we want using our own dataset. Keep an eye out for my future articles. **insert shameless self-promoting call to follow** :3"
},
{
"code": null,
"e": 3232,
"s": 2801,
"text": "Stop-words are basically words that don’t have strong meaningful connotations for instance, ‘and’, ‘a’, ‘it's’, ‘they’, etc. These have a meaningful impact when we use them to communicate with each other but for analysis by a computer, they are not really that useful (well, they probably could be but computer algorithms are not that clever yet to decipher their contextual impact accurately, to be honest). Let’s see an example:"
},
{
"code": null,
"e": 4229,
"s": 3232,
"text": "from nltk.corpus import stopwords # the corpus module is an # extremely useful one. # More on that later.stop_words = stopwords.words('english') # this is the full list of # all stop-words stored in # nltktoken = word_tokenize(sent)cleaned_token = []for word in token: if word not in stop_words: cleaned_token.append(word)print(\"This is the unclean version:\", token)print(\"This is the cleaned version:\", cleaned_token)output: This is the unclean version: ['I', 'will', 'walk', '500', 'miles', 'and', 'I', 'would', 'walk', '500', 'more', ',', 'just', 'to', 'be', 'the', 'man', 'who', 'walks', 'a', 'thousand', 'miles', 'to', 'fall', 'down', 'at', 'your', 'door', '.']This is the cleaned version: ['I', 'walk', '500', 'miles', 'I', 'would', 'walk', '500', ',', 'man', 'walks', 'thousand', 'miles', 'fall', 'door', '.']"
},
{
"code": null,
"e": 4442,
"s": 4229,
"text": "As you can see many of the words like ‘will’, ‘and’ are removed. This will save massive amounts of computation power and hence time if we were to shove bodies of texts with lots of “fluff” words into an ML model."
},
{
"code": null,
"e": 4852,
"s": 4442,
"text": "This is when ‘fluff’ letters (not words) are removed from a word and grouped together with its “stem form”. For instance, the words ‘play’, ‘playing’, or ‘plays’ convey the same meaning (although, again, not exactly, but for analysis with a computer, that sort of detail is still not a viable option). So instead of having them as different words, we can put them together under the same umbrella term ‘play’."
},
{
"code": null,
"e": 5114,
"s": 4852,
"text": "from nltk.stem import PorterStemmerstemmer = PorterStemmer()words = ['play', 'playing', 'plays', 'played', 'playfullness', 'playful']stemmed = [stemmer.stem(word) for word in words]print(stemmed)output:['play', 'play', 'play', 'play', 'playful', 'play']"
},
{
"code": null,
"e": 5647,
"s": 5114,
"text": "We used the PorterStemmer, which is a pre-written stemmer class. There are other stemmers like SnowballStemmer and LancasterStemmer but PorterStemmer is sort of the simplest one. ‘Play’ and ‘Playful’ should have been recognized as two different words however. Notice how the last ‘playful’ got recognized as ‘play’ and not ‘playful’. This is where the simplicity of the PorterStemmer is undesirable. You can also train your own using unsupervised clustering or supervised classification ML models. Now let’s stem an actual sentence!"
},
{
"code": null,
"e": 5940,
"s": 5647,
"text": "sent2 = \"I played the play playfully as the players were playing in the play with playfullness\"token = word_tokenize(sent2)stemmed = \"\"for word in token: stemmed += stemmer.stem(word) + \" \"print(stemmed)output:I play the play play as the player were play in the play with playful ."
},
{
"code": null,
"e": 6035,
"s": 5940,
"text": "This can now be efficiently tokenized for further processing or analysis. Pretty neat, right?!"
},
{
"code": null,
"e": 6198,
"s": 6035,
"text": "The next essential thing we want to do is tagging each word in the corpus (a corpus is just a ‘bag’ of words) we created after converting sentences by tokenizing."
},
{
"code": null,
"e": 7060,
"s": 6198,
"text": "from nltk import pos_tag token = word_tokenize(sent) + word_tokenize(sent2)tagged = pos_tag(cleaned_token) print(tagged)output: [('I', 'PRP'), ('will', 'MD'), ('walk', 'VB'), ('500', 'CD'), ('miles', 'NNS'), ('and', 'CC'), ('I', 'PRP'), ('would', 'MD'), ('walk', 'VB'), ('500', 'CD'), ('more', 'JJR'), (',', ','), ('just', 'RB'), ('to', 'TO'), ('be', 'VB'), ('the', 'DT'), ('man', 'NN'), ('who', 'WP'), ('walks', 'VBZ'), ('a', 'DT'), ('thousand', 'NN'), ('miles', 'NNS'), ('to', 'TO'), ('fall', 'VB'), ('down', 'RP'), ('at', 'IN'), ('your', 'PRP$'), ('door', 'NN'), ('.', '.'), ('I', 'PRP'), ('played', 'VBD'), ('the', 'DT'), ('play', 'NN'), ('playfully', 'RB'), ('as', 'IN'), ('the', 'DT'), ('players', 'NNS'), ('were', 'VBD'), ('playing', 'VBG'), ('in', 'IN'), ('the', 'DT'), ('play', 'NN'), ('with', 'IN'), ('playfullness', 'NN'), ('.', '.')]"
},
{
"code": null,
"e": 7561,
"s": 7060,
"text": "The pos_tag() method takes in a list of tokenized words, and tags each of them with a corresponding Parts of Speech identifier into tuples. For example, VB refers to ‘verb’, NNS refers to ‘plural nouns’, DT refers to a ‘determiner’. Refer to this website for a list of tags. These tags are almost always pretty accurate but we should be aware that they can be inaccurate at times. However, pre-trained models usually assume the English being used is written properly, following the grammatical rules."
},
{
"code": null,
"e": 7926,
"s": 7561,
"text": "This can be a problem when analyzing informal texts like from the internet. Remember the data frames we downloaded after pip installing NLTK? Those contain the datasets that were used to train these models initially. To apply these models in the context of our own interests, we would need to train these models on new datasets containing informal languages first."
},
{
"code": null,
"e": 8141,
"s": 7926,
"text": "In my future articles, I will talk more about NLTK basics and how we can use built-in methods of NLTK to easily train our own ML models. For further resources, you can check out the NLTK documentation and the book."
},
{
"code": null,
"e": 8806,
"s": 8141,
"text": "This article from 2001 titled “Unreasonable Effectiveness of Data” illustrated how inefficient data can be when it comes to deciphering meaningful patterns and trends from them, no matter which ML algorithm we use. But that is not a problem when it comes to text data. THE most abundant form of data available on the internet is text data. Imagine the potentials and the possibilities of the applications of ML on this humungous database. But the first barrier to actually utilizing these heaps of data is converting them into computation-friendly formats for ML algorithms for analysis, which is the preprocessing stage that NLTK holds the key to. Happy learning!"
},
{
"code": null,
"e": 8829,
"s": 8806,
"text": "towardsdatascience.com"
}
] |
Django for Data Scientists — An Introduction to Django and Django’s ORM | by Dominik Polzer | Towards Data Science
|
The extensive feature set of Django as a high-level Web framework can scare off Data Analysts and Data Scientists who never really had contact with Web development. Unfortunately, this could keep them from experiencing Django’s impressive and easy to use Data Management abilities.
While the most Django tutorials cover the entire range of functions in several hours of video footage, I would like to concentrate and highlight Django’s great database interaction features without overloading the reader with the almost limitless feature set. The article should explain it as simple as possible, so you could use Django for your Data Management tasks without understanding Django in every detail. But why use Django at all?
Use the language you are comfortable with: Django ORM allows you to interact with your database without using any SQL commandsAll in one place: Simply use the amazing functionalities and modules for Data Processing, Data Management and Data Visualization provided by Python while interacting with your databaseDjango comes with a powerful built-in database management GUI — Django AdminIn case you want to visualize insights of the data in your database and share them in an App — Django gives you everything you need for this
Use the language you are comfortable with: Django ORM allows you to interact with your database without using any SQL commands
All in one place: Simply use the amazing functionalities and modules for Data Processing, Data Management and Data Visualization provided by Python while interacting with your database
Django comes with a powerful built-in database management GUI — Django Admin
In case you want to visualize insights of the data in your database and share them in an App — Django gives you everything you need for this
A short introduction — What is Django and Django ORM?
Prerequisites to interact with your database — Install Django, start a project and connect it to your Database
Use Django ORM in standalone python scripts
A short introduction: Django as a Web Framework
Django Admin —A built-in Web Interface for Data Management
Summary
Django is a Python Web framework which helps developers to bring applications from concept to completion as fast as possible.1 A High-level framework like Django offers a comprehensive set of features for web development like an HTTP application server, a storage mechanism such as a database, a template engine, a request dispatcher and an authentication module.2
As I mentioned before, I try to focus on the part of Django that allows you to interact with your relational databases, the Object-Relation Mapper (ORM).3 The ORM brings you all functions to create and manipulate data and tables of your database without using any SQL commands.4
What I tried to explain with the following image, each Django App includes a module named mocels.py, which defines the structure of the database tables you want to create. To translate the Python Objects into database tables, the ORM comes into place. The ORM is responsible for the communication with your database, which includes the translation of your defined models into the right database structure and the execution of any database operations.
In case you are new to Django, you can install it with pip and the following command:
python -m pip install Django
When you start a new project with Django-admin, a number of files and code is already automatically generated for you, giving you the basic structure, example templates and a default configuration. On the command line, navigate to the folder you want to use as the location for your project folder and run the following command, to start the project data_management:
django-admin startproject data_management
Django-admin startproject creates a set of files that primarily determines the basic configuration of the Django project. Since we will mainly be using Django’s ORM in the following, we can ignore most of these settings for now.
The project folder you just created represents the environment you are moving in. In order for your project to be able to really do something, you still need the actual web application. This is achieved with the help of manage.py, which gives you the possibility to interact with your project. To create your first app, just make sure you are in you project folder and execute the following command:
python manage.py startapp data_processig
The last two steps will create the following project structure.
To tell your project which apps to use, you still need to register your app in settings.py. Add the created App data_processing_app to the list INSTALLED_APPS :
#settings.pyINSTALLED_APPS = [ 'django.contrib.admin’, 'django.contrib.auth’, 'django.contrib.contenttypes’, 'django.contrib.sessions’, 'django.contrib.messages’, 'django.contrib.staticfiles’, 'data_processing_app']
Before we can go into more detail about the Django ORM, we first need a link to the database of our choice, in my case MySQL. At first, we need to make sure that the required MySQL DB API Driver is installed. Django’s recommended choise is mysqlclient.5
pip install mysqlclient
In the following you link Django to an existing database, so you must first create a new database/schema. The name of my created schema is personal_dashboard .
To connect Django to your MySQL and the right database, you have to define the connection parameters in settings.py :
Thats it, Django should be connected to your database! A easy way to test it to just use python manage.py runserver . This comand will run a lightweight development Web server on the local machine. During this process Django checks the settings and will tell you if the connection to the database cannot be established.
Go to models.py and create a new model. The model will later represents the table in your database. To make it a bit more interesting, let me show it with an example.
I am tracking my working hours with a tool called Toggl Track. To use these recordings for my own visualizations and calculations, Toggl provides an API that allows me to query this data. The data returned by the API has approximately the following structure:
In the following, I will try to reproduce the structure in my own database. The table workspaces contains only the workspace-id wid and the name of the workspace. To map the table via Django go to models.py and create a new class.
Start with creating a model that holds the information about your workspaces. You will find the name of your Python class/model later in your database table. The full name of the created table is composed of <appname>_<modelname>, for the case shown here, the table takes the following name: data_processing_app_toggl_workspaces
To add a field/column to the table, add a field with the appropriate field type. You can find a summary of all field types in the Django docs. In this case we only need an integer field that holds the ID of the workspaces and a char field that holds the name of the workspace. To roll out the changes to your database, you need to run the following two commands.
python manage.py makemigrations,which is creating new migrations based on the changes you have made to your models
python manage.py migrate, applies the migrations
After you have successfully executed both commands, the table data_processing_app_toggl_workspaces should appear in your database.
Next, I need a model that I will later populate with the clients model. Each client is assigned to a workspace. Since each workspace usually has multiple clients, this is a many-to-one relationship, which is established in Django using the ForeignKey field.
Similarly, the creation and linking of the other tables is performed. The following code shows the mapping of all required tables to Django models.
If you want to use the Django functionality without a web server, you have to set the settings.py as environment variable and make it accessible. This is done by adding the following lines to the beginning of your script:
import osimport djangoos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'data_management.settings')django.setup()
Now to create a new entry of the just generated table data_processing_app_toggl_workspaces, first create a new object to your toggl_workspaces class:
new_workspace = models.toggl_workspaces(wid="12512465", name="test_workspace")
With .save() you save the new entry in your database.
new_workspaces.save()
The following script stores the contents of the sample data frames in the corresponding tables.
In order to be able to display, evaluate and visualize your data on a website, the next paragraph shows you how the communication between HTML pages and your database takes place.
As mentioned before, I don’t want to go too deep into Django as a web framework here. Nevertheless, I think its usefull to get a common understanding of the Django moduls and what they do. The following figure describes how the individual components of the project structure are interrelated. The displayed request-response cycle shows only a simplified form of the processes and do not contain the used Middlewares, but it puts the just created files into a rough context.
The incoming Requests are mainly handled by Middlewares, which have been omitted from the figure for simplicity. Django allready includes some built-in Middlewares like the AuthenticationMiddleware, CsrfViewMiddleware or the SessionMiddleware. Each of these are responsible for one specific task.6
You can find a list of used Middlewares in settings.py :
After the WSGI (Web Server Gateway Interface) and the first Middlewares7, like the Security and AuthentificationMiddleware, the ‘Request will reach the URL Router, which uses the in urls.py defined variable urlpatterns and is looking for a urlpattern which matches the url in the Request.8
As mentioned before, you can start a web server on your local machine with the command python manage.py runserver . Unless otherwise specified, the local web server runs on port 8000 and the address 127.0.0.1. So if you call up the address http://127.0.0.1:8000/example in your browser, Django searches the urlpatterns list for the entry ‘example. The URL router in this case points to the function example in views.py in your first created app data_processing_app .
The function render is used to combine a given context dictonary and a HTML tempate and returns a HttpResonse.9 In the example, I pass the variable test_string to my template. Alternatively I have the possibility to pass data from my database to my HTML template. I will explain how this works in the following.
To access the data from your database and use it within your HTML template is now pretty simple.
To be able to retrieve the data from your database in the following, we cronstruct a queryset via a manager on your model class.10 Manger describes the interface that allows you to perform database query operations. For each model there is at least one manager called objects.11
To return all object in the database you are using the all() method. So if you apply the all() method to the objects manager of your model time_entries , you will get back a QuerySet with all entries in your database.
import data_processing_app.models as modelsQuerySet = models.time_entries.objects.all()
To build and test your querries, you can use the manage.py shell. After starting a new shell with the command python manage.py shell you need to import your models (import data_processing_app.models as models ). Now you are able to create a new QuerySet.
To be able to display this query on your HTML page, you have to include it in the context of your request. For this it is enough to include your QuerySet in the dictonary context in the corresponding function in your views. Within your HTML you can then simply output the passed values with {{ <variable_name> }} .
The following figure shows this for the example we used.
Django comes with a lot of methods to manipulate and create QuerySets. You will find a comprehensive documentation in the Django docs. So much in advance, there is hardly anything that is not possible. The querys can be extended and refined as required.
Here is just an example that I use to filter the entries in time_entries by the client Dans Computer Serviceand then sum up the duration of all entries to the client by calendar week. This way I calculate the number of hours I have worked each week for a particular client.
The first step is to filter the table time_entries by the field name in the table toggl_clients . Since the tables connected via the ForeignKeys project and client you can do that by:
queryset = models.time_entries.objects.filter(project__client__name="Dans Computer Service")
Now, calculate the sum of hours per week: To generate per-object summaries you can use the annotate() clause. I am using .annotate() in the following to calculate the sum of the duration for each calendar week.
queryset_sum_week = QuerySet.annotate(week=ExtractWeek('start')).values('week') .annotate(week_total=Sum('duration') / 3600).order_by('week')
This results in the following QuerySet, with the entries for calendar weeks and the sum of the durations of all entries in that week.
In order not to go beyond the scope of this article, I don’t want to go into this in detail, but you will find all methods in the Django docs to be able to build your queries as you wish.
The next paragraph shows you what is probably Django’s most important data management tool, an integrated user interface for maintaining data.
Django Admin is a powerful built-in feature. It provides an interface with all the models metadata and gives you the ability to easily manage your database entries. The Groups and Users tables are created by automatically. In Users you can directly create new users and give them the appropriate access permissions. Access to Django Admin is granted to so-called superusers and staff users.
If you are launching the site for the first time and have not yet created a user, you can create a superuser using the command python manage.py createsuperuser and then log in to Django admin.
If you have registered your models in admin.py, you can manage all entries of your tables in the admin area and also create new ones. Django Admin is really well thought out and is available without any development effort.
I tried to explain all the required Django functionalities you need to create tables in your database, populate them, generate queries and maintain your data via Django Admin.
For performance reasons, there are certainly reasons not to use Python and Django for operations with large amounts of data. But, Django gives you all the functionality to interact with your database in a easy, understandable and pythonic way. And especially the last point opens you a whole new world of Data Analytics, Data Science and Data Visualization. Python offers you a huge treasure chest of data analysis and visualization tools and that gives you the chance to possibly uncover an insight or two in your data.
Hope the article gives you a quick and easy introduction to Django and shows that Django is a powerful tool not only for web development.
Thanks for reading!
[1] Meet Django, https://www.djangoproject.com/
[2] Web Frameworks for Python, https://wiki.python.org/moin/WebFrameworks
[3] Django ORM, https://www.fullstackpython.com/django-orm.html
[4] Katie McLaughlin, An introduction to the Django ORM, https://opensource.com/article/17/11/django-orm
[5] Databases, https://docs.djangoproject.com/en/3.1/ref/databases/#mysql-notes
[6] Middleware, https://docs.djangoproject.com/en/3.1/topics/http/middleware/
[7] URL dispatcher, https://docs.djangoproject.com/en/3.1/topics/http/urls/
[8] Django Request-Response Cycle — An easy to follow guide, https://data-flair.training/blogs/django-request-response-cycle/
[9] Django shortcut functions, https://docs.djangoproject.com/en/3.1/topics/http/shortcuts/
[10] Making queries, https://docs.djangoproject.com/en/3.1/topics/db/queries/
[11] Manager names, https://docs.djangoproject.com/en/3.1/topics/db/managers/#django.db.models.Manager
|
[
{
"code": null,
"e": 328,
"s": 46,
"text": "The extensive feature set of Django as a high-level Web framework can scare off Data Analysts and Data Scientists who never really had contact with Web development. Unfortunately, this could keep them from experiencing Django’s impressive and easy to use Data Management abilities."
},
{
"code": null,
"e": 769,
"s": 328,
"text": "While the most Django tutorials cover the entire range of functions in several hours of video footage, I would like to concentrate and highlight Django’s great database interaction features without overloading the reader with the almost limitless feature set. The article should explain it as simple as possible, so you could use Django for your Data Management tasks without understanding Django in every detail. But why use Django at all?"
},
{
"code": null,
"e": 1296,
"s": 769,
"text": "Use the language you are comfortable with: Django ORM allows you to interact with your database without using any SQL commandsAll in one place: Simply use the amazing functionalities and modules for Data Processing, Data Management and Data Visualization provided by Python while interacting with your databaseDjango comes with a powerful built-in database management GUI — Django AdminIn case you want to visualize insights of the data in your database and share them in an App — Django gives you everything you need for this"
},
{
"code": null,
"e": 1423,
"s": 1296,
"text": "Use the language you are comfortable with: Django ORM allows you to interact with your database without using any SQL commands"
},
{
"code": null,
"e": 1608,
"s": 1423,
"text": "All in one place: Simply use the amazing functionalities and modules for Data Processing, Data Management and Data Visualization provided by Python while interacting with your database"
},
{
"code": null,
"e": 1685,
"s": 1608,
"text": "Django comes with a powerful built-in database management GUI — Django Admin"
},
{
"code": null,
"e": 1826,
"s": 1685,
"text": "In case you want to visualize insights of the data in your database and share them in an App — Django gives you everything you need for this"
},
{
"code": null,
"e": 1880,
"s": 1826,
"text": "A short introduction — What is Django and Django ORM?"
},
{
"code": null,
"e": 1991,
"s": 1880,
"text": "Prerequisites to interact with your database — Install Django, start a project and connect it to your Database"
},
{
"code": null,
"e": 2035,
"s": 1991,
"text": "Use Django ORM in standalone python scripts"
},
{
"code": null,
"e": 2083,
"s": 2035,
"text": "A short introduction: Django as a Web Framework"
},
{
"code": null,
"e": 2142,
"s": 2083,
"text": "Django Admin —A built-in Web Interface for Data Management"
},
{
"code": null,
"e": 2150,
"s": 2142,
"text": "Summary"
},
{
"code": null,
"e": 2515,
"s": 2150,
"text": "Django is a Python Web framework which helps developers to bring applications from concept to completion as fast as possible.1 A High-level framework like Django offers a comprehensive set of features for web development like an HTTP application server, a storage mechanism such as a database, a template engine, a request dispatcher and an authentication module.2"
},
{
"code": null,
"e": 2794,
"s": 2515,
"text": "As I mentioned before, I try to focus on the part of Django that allows you to interact with your relational databases, the Object-Relation Mapper (ORM).3 The ORM brings you all functions to create and manipulate data and tables of your database without using any SQL commands.4"
},
{
"code": null,
"e": 3245,
"s": 2794,
"text": "What I tried to explain with the following image, each Django App includes a module named mocels.py, which defines the structure of the database tables you want to create. To translate the Python Objects into database tables, the ORM comes into place. The ORM is responsible for the communication with your database, which includes the translation of your defined models into the right database structure and the execution of any database operations."
},
{
"code": null,
"e": 3331,
"s": 3245,
"text": "In case you are new to Django, you can install it with pip and the following command:"
},
{
"code": null,
"e": 3360,
"s": 3331,
"text": "python -m pip install Django"
},
{
"code": null,
"e": 3727,
"s": 3360,
"text": "When you start a new project with Django-admin, a number of files and code is already automatically generated for you, giving you the basic structure, example templates and a default configuration. On the command line, navigate to the folder you want to use as the location for your project folder and run the following command, to start the project data_management:"
},
{
"code": null,
"e": 3769,
"s": 3727,
"text": "django-admin startproject data_management"
},
{
"code": null,
"e": 3998,
"s": 3769,
"text": "Django-admin startproject creates a set of files that primarily determines the basic configuration of the Django project. Since we will mainly be using Django’s ORM in the following, we can ignore most of these settings for now."
},
{
"code": null,
"e": 4398,
"s": 3998,
"text": "The project folder you just created represents the environment you are moving in. In order for your project to be able to really do something, you still need the actual web application. This is achieved with the help of manage.py, which gives you the possibility to interact with your project. To create your first app, just make sure you are in you project folder and execute the following command:"
},
{
"code": null,
"e": 4439,
"s": 4398,
"text": "python manage.py startapp data_processig"
},
{
"code": null,
"e": 4503,
"s": 4439,
"text": "The last two steps will create the following project structure."
},
{
"code": null,
"e": 4664,
"s": 4503,
"text": "To tell your project which apps to use, you still need to register your app in settings.py. Add the created App data_processing_app to the list INSTALLED_APPS :"
},
{
"code": null,
"e": 4901,
"s": 4664,
"text": "#settings.pyINSTALLED_APPS = [ 'django.contrib.admin’, 'django.contrib.auth’, 'django.contrib.contenttypes’, 'django.contrib.sessions’, 'django.contrib.messages’, 'django.contrib.staticfiles’, 'data_processing_app']"
},
{
"code": null,
"e": 5155,
"s": 4901,
"text": "Before we can go into more detail about the Django ORM, we first need a link to the database of our choice, in my case MySQL. At first, we need to make sure that the required MySQL DB API Driver is installed. Django’s recommended choise is mysqlclient.5"
},
{
"code": null,
"e": 5179,
"s": 5155,
"text": "pip install mysqlclient"
},
{
"code": null,
"e": 5339,
"s": 5179,
"text": "In the following you link Django to an existing database, so you must first create a new database/schema. The name of my created schema is personal_dashboard ."
},
{
"code": null,
"e": 5457,
"s": 5339,
"text": "To connect Django to your MySQL and the right database, you have to define the connection parameters in settings.py :"
},
{
"code": null,
"e": 5777,
"s": 5457,
"text": "Thats it, Django should be connected to your database! A easy way to test it to just use python manage.py runserver . This comand will run a lightweight development Web server on the local machine. During this process Django checks the settings and will tell you if the connection to the database cannot be established."
},
{
"code": null,
"e": 5944,
"s": 5777,
"text": "Go to models.py and create a new model. The model will later represents the table in your database. To make it a bit more interesting, let me show it with an example."
},
{
"code": null,
"e": 6204,
"s": 5944,
"text": "I am tracking my working hours with a tool called Toggl Track. To use these recordings for my own visualizations and calculations, Toggl provides an API that allows me to query this data. The data returned by the API has approximately the following structure:"
},
{
"code": null,
"e": 6435,
"s": 6204,
"text": "In the following, I will try to reproduce the structure in my own database. The table workspaces contains only the workspace-id wid and the name of the workspace. To map the table via Django go to models.py and create a new class."
},
{
"code": null,
"e": 6764,
"s": 6435,
"text": "Start with creating a model that holds the information about your workspaces. You will find the name of your Python class/model later in your database table. The full name of the created table is composed of <appname>_<modelname>, for the case shown here, the table takes the following name: data_processing_app_toggl_workspaces"
},
{
"code": null,
"e": 7127,
"s": 6764,
"text": "To add a field/column to the table, add a field with the appropriate field type. You can find a summary of all field types in the Django docs. In this case we only need an integer field that holds the ID of the workspaces and a char field that holds the name of the workspace. To roll out the changes to your database, you need to run the following two commands."
},
{
"code": null,
"e": 7242,
"s": 7127,
"text": "python manage.py makemigrations,which is creating new migrations based on the changes you have made to your models"
},
{
"code": null,
"e": 7291,
"s": 7242,
"text": "python manage.py migrate, applies the migrations"
},
{
"code": null,
"e": 7422,
"s": 7291,
"text": "After you have successfully executed both commands, the table data_processing_app_toggl_workspaces should appear in your database."
},
{
"code": null,
"e": 7680,
"s": 7422,
"text": "Next, I need a model that I will later populate with the clients model. Each client is assigned to a workspace. Since each workspace usually has multiple clients, this is a many-to-one relationship, which is established in Django using the ForeignKey field."
},
{
"code": null,
"e": 7828,
"s": 7680,
"text": "Similarly, the creation and linking of the other tables is performed. The following code shows the mapping of all required tables to Django models."
},
{
"code": null,
"e": 8050,
"s": 7828,
"text": "If you want to use the Django functionality without a web server, you have to set the settings.py as environment variable and make it accessible. This is done by adding the following lines to the beginning of your script:"
},
{
"code": null,
"e": 8162,
"s": 8050,
"text": "import osimport djangoos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'data_management.settings')django.setup()"
},
{
"code": null,
"e": 8312,
"s": 8162,
"text": "Now to create a new entry of the just generated table data_processing_app_toggl_workspaces, first create a new object to your toggl_workspaces class:"
},
{
"code": null,
"e": 8424,
"s": 8312,
"text": "new_workspace = models.toggl_workspaces(wid=\"12512465\", name=\"test_workspace\")"
},
{
"code": null,
"e": 8478,
"s": 8424,
"text": "With .save() you save the new entry in your database."
},
{
"code": null,
"e": 8500,
"s": 8478,
"text": "new_workspaces.save()"
},
{
"code": null,
"e": 8596,
"s": 8500,
"text": "The following script stores the contents of the sample data frames in the corresponding tables."
},
{
"code": null,
"e": 8776,
"s": 8596,
"text": "In order to be able to display, evaluate and visualize your data on a website, the next paragraph shows you how the communication between HTML pages and your database takes place."
},
{
"code": null,
"e": 9250,
"s": 8776,
"text": "As mentioned before, I don’t want to go too deep into Django as a web framework here. Nevertheless, I think its usefull to get a common understanding of the Django moduls and what they do. The following figure describes how the individual components of the project structure are interrelated. The displayed request-response cycle shows only a simplified form of the processes and do not contain the used Middlewares, but it puts the just created files into a rough context."
},
{
"code": null,
"e": 9548,
"s": 9250,
"text": "The incoming Requests are mainly handled by Middlewares, which have been omitted from the figure for simplicity. Django allready includes some built-in Middlewares like the AuthenticationMiddleware, CsrfViewMiddleware or the SessionMiddleware. Each of these are responsible for one specific task.6"
},
{
"code": null,
"e": 9605,
"s": 9548,
"text": "You can find a list of used Middlewares in settings.py :"
},
{
"code": null,
"e": 9895,
"s": 9605,
"text": "After the WSGI (Web Server Gateway Interface) and the first Middlewares7, like the Security and AuthentificationMiddleware, the ‘Request will reach the URL Router, which uses the in urls.py defined variable urlpatterns and is looking for a urlpattern which matches the url in the Request.8"
},
{
"code": null,
"e": 10362,
"s": 9895,
"text": "As mentioned before, you can start a web server on your local machine with the command python manage.py runserver . Unless otherwise specified, the local web server runs on port 8000 and the address 127.0.0.1. So if you call up the address http://127.0.0.1:8000/example in your browser, Django searches the urlpatterns list for the entry ‘example. The URL router in this case points to the function example in views.py in your first created app data_processing_app ."
},
{
"code": null,
"e": 10674,
"s": 10362,
"text": "The function render is used to combine a given context dictonary and a HTML tempate and returns a HttpResonse.9 In the example, I pass the variable test_string to my template. Alternatively I have the possibility to pass data from my database to my HTML template. I will explain how this works in the following."
},
{
"code": null,
"e": 10771,
"s": 10674,
"text": "To access the data from your database and use it within your HTML template is now pretty simple."
},
{
"code": null,
"e": 11050,
"s": 10771,
"text": "To be able to retrieve the data from your database in the following, we cronstruct a queryset via a manager on your model class.10 Manger describes the interface that allows you to perform database query operations. For each model there is at least one manager called objects.11"
},
{
"code": null,
"e": 11268,
"s": 11050,
"text": "To return all object in the database you are using the all() method. So if you apply the all() method to the objects manager of your model time_entries , you will get back a QuerySet with all entries in your database."
},
{
"code": null,
"e": 11356,
"s": 11268,
"text": "import data_processing_app.models as modelsQuerySet = models.time_entries.objects.all()"
},
{
"code": null,
"e": 11611,
"s": 11356,
"text": "To build and test your querries, you can use the manage.py shell. After starting a new shell with the command python manage.py shell you need to import your models (import data_processing_app.models as models ). Now you are able to create a new QuerySet."
},
{
"code": null,
"e": 11926,
"s": 11611,
"text": "To be able to display this query on your HTML page, you have to include it in the context of your request. For this it is enough to include your QuerySet in the dictonary context in the corresponding function in your views. Within your HTML you can then simply output the passed values with {{ <variable_name> }} ."
},
{
"code": null,
"e": 11983,
"s": 11926,
"text": "The following figure shows this for the example we used."
},
{
"code": null,
"e": 12237,
"s": 11983,
"text": "Django comes with a lot of methods to manipulate and create QuerySets. You will find a comprehensive documentation in the Django docs. So much in advance, there is hardly anything that is not possible. The querys can be extended and refined as required."
},
{
"code": null,
"e": 12511,
"s": 12237,
"text": "Here is just an example that I use to filter the entries in time_entries by the client Dans Computer Serviceand then sum up the duration of all entries to the client by calendar week. This way I calculate the number of hours I have worked each week for a particular client."
},
{
"code": null,
"e": 12695,
"s": 12511,
"text": "The first step is to filter the table time_entries by the field name in the table toggl_clients . Since the tables connected via the ForeignKeys project and client you can do that by:"
},
{
"code": null,
"e": 12788,
"s": 12695,
"text": "queryset = models.time_entries.objects.filter(project__client__name=\"Dans Computer Service\")"
},
{
"code": null,
"e": 12999,
"s": 12788,
"text": "Now, calculate the sum of hours per week: To generate per-object summaries you can use the annotate() clause. I am using .annotate() in the following to calculate the sum of the duration for each calendar week."
},
{
"code": null,
"e": 13143,
"s": 12999,
"text": "queryset_sum_week = QuerySet.annotate(week=ExtractWeek('start')).values('week') .annotate(week_total=Sum('duration') / 3600).order_by('week')"
},
{
"code": null,
"e": 13277,
"s": 13143,
"text": "This results in the following QuerySet, with the entries for calendar weeks and the sum of the durations of all entries in that week."
},
{
"code": null,
"e": 13465,
"s": 13277,
"text": "In order not to go beyond the scope of this article, I don’t want to go into this in detail, but you will find all methods in the Django docs to be able to build your queries as you wish."
},
{
"code": null,
"e": 13608,
"s": 13465,
"text": "The next paragraph shows you what is probably Django’s most important data management tool, an integrated user interface for maintaining data."
},
{
"code": null,
"e": 13999,
"s": 13608,
"text": "Django Admin is a powerful built-in feature. It provides an interface with all the models metadata and gives you the ability to easily manage your database entries. The Groups and Users tables are created by automatically. In Users you can directly create new users and give them the appropriate access permissions. Access to Django Admin is granted to so-called superusers and staff users."
},
{
"code": null,
"e": 14192,
"s": 13999,
"text": "If you are launching the site for the first time and have not yet created a user, you can create a superuser using the command python manage.py createsuperuser and then log in to Django admin."
},
{
"code": null,
"e": 14415,
"s": 14192,
"text": "If you have registered your models in admin.py, you can manage all entries of your tables in the admin area and also create new ones. Django Admin is really well thought out and is available without any development effort."
},
{
"code": null,
"e": 14591,
"s": 14415,
"text": "I tried to explain all the required Django functionalities you need to create tables in your database, populate them, generate queries and maintain your data via Django Admin."
},
{
"code": null,
"e": 15112,
"s": 14591,
"text": "For performance reasons, there are certainly reasons not to use Python and Django for operations with large amounts of data. But, Django gives you all the functionality to interact with your database in a easy, understandable and pythonic way. And especially the last point opens you a whole new world of Data Analytics, Data Science and Data Visualization. Python offers you a huge treasure chest of data analysis and visualization tools and that gives you the chance to possibly uncover an insight or two in your data."
},
{
"code": null,
"e": 15250,
"s": 15112,
"text": "Hope the article gives you a quick and easy introduction to Django and shows that Django is a powerful tool not only for web development."
},
{
"code": null,
"e": 15270,
"s": 15250,
"text": "Thanks for reading!"
},
{
"code": null,
"e": 15318,
"s": 15270,
"text": "[1] Meet Django, https://www.djangoproject.com/"
},
{
"code": null,
"e": 15392,
"s": 15318,
"text": "[2] Web Frameworks for Python, https://wiki.python.org/moin/WebFrameworks"
},
{
"code": null,
"e": 15456,
"s": 15392,
"text": "[3] Django ORM, https://www.fullstackpython.com/django-orm.html"
},
{
"code": null,
"e": 15561,
"s": 15456,
"text": "[4] Katie McLaughlin, An introduction to the Django ORM, https://opensource.com/article/17/11/django-orm"
},
{
"code": null,
"e": 15641,
"s": 15561,
"text": "[5] Databases, https://docs.djangoproject.com/en/3.1/ref/databases/#mysql-notes"
},
{
"code": null,
"e": 15719,
"s": 15641,
"text": "[6] Middleware, https://docs.djangoproject.com/en/3.1/topics/http/middleware/"
},
{
"code": null,
"e": 15795,
"s": 15719,
"text": "[7] URL dispatcher, https://docs.djangoproject.com/en/3.1/topics/http/urls/"
},
{
"code": null,
"e": 15921,
"s": 15795,
"text": "[8] Django Request-Response Cycle — An easy to follow guide, https://data-flair.training/blogs/django-request-response-cycle/"
},
{
"code": null,
"e": 16013,
"s": 15921,
"text": "[9] Django shortcut functions, https://docs.djangoproject.com/en/3.1/topics/http/shortcuts/"
},
{
"code": null,
"e": 16091,
"s": 16013,
"text": "[10] Making queries, https://docs.djangoproject.com/en/3.1/topics/db/queries/"
}
] |
Private and Protected Members in C++
|
A class in C++ has public, private and protected sections which contain the corresponding class members.
The private data members cannot be accessed from outside the class. They can only be accessed by class or friend functions. All the class members are private by default.
The protected members in a class are similar to private members but they can be accessed by derived classes or child classes while private members cannot.
A program that demonstrates private and protected members in a class is given as follows −
Live Demo
#include <iostream>
using namespace std;
class Base {
public :
int a = 8;
protected :
int b = 10;
private :
int c = 20;
};
class Derived : public Base {
public :
void func() {
cout << "The value of a : " << a;
cout << "\nThe value of b : " << b;
}
};
int main() {
Derived obj;
obj.func();
return 0;
}
The output of the above program is as follows.
The value of a : 8
The value of b : 10
Now, let us understand the above program.
In the class Base, the data members are a, b and c which are public, protected and private respectively. The code snippet for this is given as follows.
class Base {
public :
int a = 8;
protected :
int b = 10;
private :
int c = 20;
};
The class Derived inherits the class Base. The function func() prints the values of a and b. It cannot print the value of c as that is private to class Base and cannot be accessed in class Derived. The code snippet for this is given as follows.
class Derived : public Base {
public :
void func() {
cout << "The value of a : " << a;
cout << "\nThe value of b : " << b;
}
};
In the function main(), the object obj of class Derived is created. Then the function func() is called. The code snippet for this is given as follows.
int main() {
Derived obj;
obj.func();
return 0;
}
|
[
{
"code": null,
"e": 1167,
"s": 1062,
"text": "A class in C++ has public, private and protected sections which contain the corresponding class members."
},
{
"code": null,
"e": 1337,
"s": 1167,
"text": "The private data members cannot be accessed from outside the class. They can only be accessed by class or friend functions. All the class members are private by default."
},
{
"code": null,
"e": 1492,
"s": 1337,
"text": "The protected members in a class are similar to private members but they can be accessed by derived classes or child classes while private members cannot."
},
{
"code": null,
"e": 1583,
"s": 1492,
"text": "A program that demonstrates private and protected members in a class is given as follows −"
},
{
"code": null,
"e": 1594,
"s": 1583,
"text": " Live Demo"
},
{
"code": null,
"e": 1943,
"s": 1594,
"text": "#include <iostream>\nusing namespace std;\nclass Base {\n public :\n int a = 8;\n protected :\n int b = 10;\n private :\n int c = 20;\n};\nclass Derived : public Base {\n public :\n void func() {\n cout << \"The value of a : \" << a;\n cout << \"\\nThe value of b : \" << b;\n }\n};\nint main() {\n Derived obj;\n obj.func();\n return 0;\n}"
},
{
"code": null,
"e": 1990,
"s": 1943,
"text": "The output of the above program is as follows."
},
{
"code": null,
"e": 2029,
"s": 1990,
"text": "The value of a : 8\nThe value of b : 10"
},
{
"code": null,
"e": 2071,
"s": 2029,
"text": "Now, let us understand the above program."
},
{
"code": null,
"e": 2223,
"s": 2071,
"text": "In the class Base, the data members are a, b and c which are public, protected and private respectively. The code snippet for this is given as follows."
},
{
"code": null,
"e": 2323,
"s": 2223,
"text": "class Base {\n public :\n int a = 8;\n protected :\n int b = 10;\n private :\n int c = 20;\n};"
},
{
"code": null,
"e": 2568,
"s": 2323,
"text": "The class Derived inherits the class Base. The function func() prints the values of a and b. It cannot print the value of c as that is private to class Base and cannot be accessed in class Derived. The code snippet for this is given as follows."
},
{
"code": null,
"e": 2717,
"s": 2568,
"text": "class Derived : public Base {\n public :\n void func() {\n cout << \"The value of a : \" << a;\n cout << \"\\nThe value of b : \" << b;\n }\n};"
},
{
"code": null,
"e": 2868,
"s": 2717,
"text": "In the function main(), the object obj of class Derived is created. Then the function func() is called. The code snippet for this is given as follows."
},
{
"code": null,
"e": 2927,
"s": 2868,
"text": "int main() {\n Derived obj;\n obj.func();\n return 0;\n}"
}
] |
Python | Pandas dataframe.sum() - GeeksforGeeks
|
22 Oct, 2019
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas dataframe.sum() function return the sum of the values for the requested axis. If the input is index axis then it adds all the values in a column and repeats the same for all the columns and returns a series containing the sum of all the values in each column. It also provides support to skip the missing values in the dataframe while calculating the sum in the dataframe.
Syntax: DataFrame.sum(axis=None, skipna=None, level=None, numeric_only=None, min_count=0, **kwargs)
Parameters :axis : {index (0), columns (1)}skipna : Exclude NA/null values when computing the result.level : If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a Seriesnumeric_only : Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series.min_count : The required number of valid values to perform the operation. If fewer than min_count non-NA values are present the result will be NA.
Returns : sum : Series or DataFrame (if level specified)
For link to the CSV file used in the code, click here
Example #1: Use sum() function to find the sum of all the values over the index axis.
# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.read_csv("nba.csv") # Print the dataframedf
Now find the sum of all values along the index axis. We are going to skip the NaN values in the calculation of the sum.
# finding sum over index axis# By default the axis is set to 0df.sum(axis = 0, skipna = True)
Output : Example #2: Use sum() function to find the sum of all the values over the column axis.
Now we will find the sum along the column axis. We are going to set skipna to be true. If we do not skip the NaN values then it will result in NaN values.
# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.read_csv("nba.csv") # sum over the column axis.df.sum(axis = 1, skipna = True)
Output :
Akanksha_Rai
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
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Enumerate() in Python
Create a Pandas DataFrame from Lists
*args and **kwargs in Python
Check if element exists in list in Python
Convert integer to string in Python
How To Convert Python Dictionary To JSON?
isupper(), islower(), lower(), upper() in Python and their applications
|
[
{
"code": null,
"e": 24984,
"s": 24956,
"text": "\n22 Oct, 2019"
},
{
"code": null,
"e": 25198,
"s": 24984,
"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": 25578,
"s": 25198,
"text": "Pandas dataframe.sum() function return the sum of the values for the requested axis. If the input is index axis then it adds all the values in a column and repeats the same for all the columns and returns a series containing the sum of all the values in each column. It also provides support to skip the missing values in the dataframe while calculating the sum in the dataframe."
},
{
"code": null,
"e": 25678,
"s": 25578,
"text": "Syntax: DataFrame.sum(axis=None, skipna=None, level=None, numeric_only=None, min_count=0, **kwargs)"
},
{
"code": null,
"e": 26187,
"s": 25678,
"text": "Parameters :axis : {index (0), columns (1)}skipna : Exclude NA/null values when computing the result.level : If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a Seriesnumeric_only : Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series.min_count : The required number of valid values to perform the operation. If fewer than min_count non-NA values are present the result will be NA."
},
{
"code": null,
"e": 26244,
"s": 26187,
"text": "Returns : sum : Series or DataFrame (if level specified)"
},
{
"code": null,
"e": 26298,
"s": 26244,
"text": "For link to the CSV file used in the code, click here"
},
{
"code": null,
"e": 26384,
"s": 26298,
"text": "Example #1: Use sum() function to find the sum of all the values over the index axis."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.read_csv(\"nba.csv\") # Print the dataframedf",
"e": 26507,
"s": 26384,
"text": null
},
{
"code": null,
"e": 26627,
"s": 26507,
"text": "Now find the sum of all values along the index axis. We are going to skip the NaN values in the calculation of the sum."
},
{
"code": "# finding sum over index axis# By default the axis is set to 0df.sum(axis = 0, skipna = True)",
"e": 26721,
"s": 26627,
"text": null
},
{
"code": null,
"e": 26817,
"s": 26721,
"text": "Output : Example #2: Use sum() function to find the sum of all the values over the column axis."
},
{
"code": null,
"e": 26972,
"s": 26817,
"text": "Now we will find the sum along the column axis. We are going to set skipna to be true. If we do not skip the NaN values then it will result in NaN values."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.read_csv(\"nba.csv\") # sum over the column axis.df.sum(axis = 1, skipna = True)",
"e": 27130,
"s": 26972,
"text": null
},
{
"code": null,
"e": 27139,
"s": 27130,
"text": "Output :"
},
{
"code": null,
"e": 27152,
"s": 27139,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 27176,
"s": 27152,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 27208,
"s": 27176,
"text": "Python pandas-dataFrame-methods"
},
{
"code": null,
"e": 27222,
"s": 27208,
"text": "Python-pandas"
},
{
"code": null,
"e": 27229,
"s": 27222,
"text": "Python"
},
{
"code": null,
"e": 27327,
"s": 27229,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27345,
"s": 27327,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27377,
"s": 27345,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27419,
"s": 27377,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27441,
"s": 27419,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27478,
"s": 27441,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 27507,
"s": 27478,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 27549,
"s": 27507,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27585,
"s": 27549,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 27627,
"s": 27585,
"text": "How To Convert Python Dictionary To JSON?"
}
] |
Violinplot using Seaborn in Python - GeeksforGeeks
|
15 Jan, 2022
Seaborn is an amazing visualization library for statistical graphics plotting in Python. It provides beautiful default styles and color palettes to make statistical plots more attractive. It is built on the top of matplotlib library and also closely integrated into the data structures from pandas.
A violin plot plays a similar activity that is pursued through whisker or box plot do. As it shows several quantitative data across one or more categorical variables. It can be an effective and attractive way to show multiple data at several units. A “wide-form” Data Frame helps to maintain each numeric column which can be plotted on the graph. It is possible to use NumPy or Python objects, but pandas objects are preferable because the associated names will be used to annotate the axes.
Syntax: seaborn.violinplot(x=None, y=None, hue=None, data=None, order=None, hue_order=None, bw=’scott’, cut=2, scale=’area’, scale_hue=True, gridsize=100, width=0.8, inner=’box’, split=False, dodge=True, orient=None, linewidth=None, color=None, palette=None, saturation=0.75, ax=None, **kwargs)Parameters: x, y, hue: Inputs for plotting long-form data. data: Dataset for plotting. scale: The method used to scale the width of each violin.
Returns: This method returns the Axes object with the plot drawn onto it.
Example 1: Basic visualization of “fmri” dataset using violinplot()
Python3
import seaborn seaborn.set(style = 'whitegrid')fmri = seaborn.load_dataset("fmri") seaborn.violinplot(x ="timepoint", y ="signal", data = fmri)
Output:
Example 2: Grouping data points on the basis of category, here as region and event.
Python3
import seaborn seaborn.set(style = 'whitegrid')fmri = seaborn.load_dataset("fmri") seaborn.violinplot(x ="timepoint", y ="signal", hue ="region", style ="event", data = fmri)
Output:
Example 3: Basic visualization of “tips” dataset using lineplot()
Python3
import seaborn seaborn.set(style = 'whitegrid') tip = seaborn.load_dataset('tips') seaborn.violinplot(x ='day', y ='tip', data = tip)
Output:
1.Draw a single horizontal swarm plot using only one axis:
If we use only one data variable instead of two data variables then it means that the axis denotes each of these data variables as an axis.
X denotes an x-axis and y denote a y-axis.
Syntax:
seaborn.violinplot(x)
Code:
Python3
# Python program to illustrate# violinplot using inbuilt data-set# given in seaborn # importing the required moduleimport seaborn # use to set style of background of plotseaborn.set(style="whitegrid") # loading data-settips = seaborn.load_dataset("tips") seaborn.violinplot(x=tip["total_bill"])
Output:
2. Draw horizontal violinplot:
In the above example we see how to plot a single horizontal violinplot plot and here can perform multiple horizontal plot with exchange the data variable with another axis.
Python3
# Python program to illustrate# violinplot using inbuilt data-set# given in seaborn # importing the required moduleimport seaborn # use to set style of background of plotseaborn.set(style="whitegrid") # loading data-settips = seaborn.load_dataset("tips") seaborn.violinplot(x="tip", y="day", data=tip)
Output:
3. Using hue parameter:
While the points are plotted in two dimensions, another dimension can be added to the plot by coloring the points according to a third variable.
Syntax:
sns.violinplot(x, y, hue, data)
Python3
# Python program to illustrate# violinplot using inbuilt data-set# given in seaborn # importing the required moduleimport seaborn # use to set style of background of plotseaborn.set(style="whitegrid") # loading data-settips = seaborn.load_dataset("tips") seaborn.violinplot(x="day", y="total_bill", hue="time", data=tips)
Output:
4. Draw outlines around the data points using linewidth:
Width of the gray lines that frame the plot elements. Whenever we increase linewidth than the point also will increase automatically.
Syntax:
seaborn.violinplot(x, y, data, linewidth)
Python3
# Python program to illustrate# violinplot using inbuilt data-set# given in seaborn # importing the required moduleimport seaborn # use to set style of background of plotseaborn.set(style="whitegrid") # loading data-settips = seaborn.load_dataset("tips") seaborn.violinplot(x ='day', y ='tip', data = tip, linewidth = 4)
Output:
5. Draw each level of the hue variable at different locations on the major categorical axis:
When using hue nesting, setting dodge should be True will separate the point for different hue levels along the categorical axis. And Palette is used for the different levels of the hue variable.
Syntax:
seaborn.violinplot(x, y, data, hue, palette, dodge)
Python3
# Python program to illustrate# violinplot using inbuilt data-set# given in seaborn # importing the required moduleimport seaborn # use to set style of background of plotseaborn.set(style="whitegrid") # loading data-settips = seaborn.load_dataset("tips") seaborn.violinplot(x="day", y="total_bill", hue="smoker", data=tips, palette="Set2", dodge=True)
Output:
Possible values of palette are:
Accent, Accent_r, Blues, Blues_r, BrBG, BrBG_r, BuGn, BuGn_r, BuPu, BuPu_r, CMRmap, CMRmap_r, Dark2, Dark2_r,
GnBu, GnBu_r, Greens, Greens_r, Greys, Greys_r, OrRd, OrRd_r, Oranges, Oranges_r, PRGn, PRGn_r, Paired, Paired_r,
Pastel1, Pastel1_r, Pastel2, Pastel2_r, PiYG, PiYG_r, PuBu, PuBuGn, PuBuGn_r, PuBu_r, PuOr, PuOr_r, PuRd, PuRd_r,
Purples, Purples_r, RdBu, RdBu_r, RdGy, RdGy_r, RdPu, RdPu_r, RdYlBu, RdYlBu_r, RdYlGn, RdYlGn_r, Reds, Reds_r, Set1,
Set1_r, Set2, Set2_r, Set3, Set3_r, Spectral, Spectral_r, Wistia, Wistia_r, YlGn, YlGnBu, YlGnBu_r, YlGn_r, YlOrBr,
YlOrBr_r, YlOrRd, YlOrRd_r, afmhot, afmhot_r, autumn, autumn_r, binary, binary_r, bone, bone_r, brg, brg_r, bwr, bwr_r,
cividis, cividis_r, cool, cool_r, coolwarm, coolwarm_r, copper, copper_r, cubehelix, cubehelix_r, flag, flag_r, gist_earth,
gist_earth_r, gist_gray, gist_gray_r, gist_heat, gist_heat_r, gist_ncar, gist_ncar_r, gist_rainbow, gist_rainbow_r, gist_stern,
7. Control violin order by passing an explicit order:
Python3
# Python program to illustrate# violinplot using inbuilt data-set# given in seaborn # importing the required moduleimport seaborn # use to set style of background of plotseaborn.set(style="whitegrid") # loading data-settips = seaborn.load_dataset("tips") seaborn.violinplot(x="time", y="tip", data=tips, order=["Dinner", "Lunch"])
Output:
8. Adding the palette attributes:
Using the palette we can generate the point with different colors. In this below example we can see the palette can be responsible for a generate the violinplot with different colormap values.
Syntax:
seaborn.violinplot( x, y, data, palette=”color_name”)
Python3
# Python program to illustrate# violinplot using inbuilt data-set# given in seaborn # importing the required moduleimport seaborn # use to set style of background of plotseaborn.set(style="whitegrid") # loading data-settips = seaborn.load_dataset("tips") seaborn.violinplot(x='day', y='total_bill', data=tips, hue='time', palette='pastel')
Output:
9. Adding the saturation parameter:
Proportion of the original saturation to draw colors at. Large patches often look better with slightly desaturated colors, but set this to 1 if you want the plot colors to perfectly match the input color spec.
Syntax:
seaborn.violinplot(x, y, data, saturation)
Python3
# Python program to illustrate# violinplot using inbuilt data-set# given in seaborn # importing the required moduleimport seaborn # use to set style of background of plotseaborn.set(style="whitegrid") # loading data-settips = seaborn.load_dataset("tips") seaborn.violinplot(x ='day', y ='tip', data = tip, saturation =0.03)
Output:
10. Adding color parameter:
It will Color for all the elements or seed for a gradient palette.
Syntax:
seaborn.violinplot(x, y, data, color)
Python3
# Python program to illustrate# violinplot using inbuilt data-set# given in seaborn # importing the required moduleimport seaborn # use to set style of background of plotseaborn.set(style="whitegrid") # loading data-settips = seaborn.load_dataset("tips") seaborn.violinplot(x ='day', y ='tip', data = tip, color = "Yellow")
Output:
11. Scale the violin width by the number of observations in each bin:
Python3
# Python program to illustrate# violinplot using inbuilt data-set# given in seaborn # importing the required moduleimport seaborn # use to set style of background of plotseaborn.set(style="whitegrid") # loading data-settips = seaborn.load_dataset("tips") seaborn.violinplot(x="day", y="total_bill", hue="sex", data=tip, palette="Set2", split=True, scale="count")
Output:
kumar_satyam
ruhelaa48
Python-Seaborn
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
|
[
{
"code": null,
"e": 28117,
"s": 28089,
"text": "\n15 Jan, 2022"
},
{
"code": null,
"e": 28416,
"s": 28117,
"text": "Seaborn is an amazing visualization library for statistical graphics plotting in Python. It provides beautiful default styles and color palettes to make statistical plots more attractive. It is built on the top of matplotlib library and also closely integrated into the data structures from pandas."
},
{
"code": null,
"e": 28908,
"s": 28416,
"text": "A violin plot plays a similar activity that is pursued through whisker or box plot do. As it shows several quantitative data across one or more categorical variables. It can be an effective and attractive way to show multiple data at several units. A “wide-form” Data Frame helps to maintain each numeric column which can be plotted on the graph. It is possible to use NumPy or Python objects, but pandas objects are preferable because the associated names will be used to annotate the axes."
},
{
"code": null,
"e": 29349,
"s": 28908,
"text": "Syntax: seaborn.violinplot(x=None, y=None, hue=None, data=None, order=None, hue_order=None, bw=’scott’, cut=2, scale=’area’, scale_hue=True, gridsize=100, width=0.8, inner=’box’, split=False, dodge=True, orient=None, linewidth=None, color=None, palette=None, saturation=0.75, ax=None, **kwargs)Parameters: x, y, hue: Inputs for plotting long-form data. data: Dataset for plotting. scale: The method used to scale the width of each violin. "
},
{
"code": null,
"e": 29423,
"s": 29349,
"text": "Returns: This method returns the Axes object with the plot drawn onto it."
},
{
"code": null,
"e": 29493,
"s": 29423,
"text": "Example 1: Basic visualization of “fmri” dataset using violinplot() "
},
{
"code": null,
"e": 29501,
"s": 29493,
"text": "Python3"
},
{
"code": "import seaborn seaborn.set(style = 'whitegrid')fmri = seaborn.load_dataset(\"fmri\") seaborn.violinplot(x =\"timepoint\", y =\"signal\", data = fmri)",
"e": 29679,
"s": 29501,
"text": null
},
{
"code": null,
"e": 29687,
"s": 29679,
"text": "Output:"
},
{
"code": null,
"e": 29772,
"s": 29687,
"text": "Example 2: Grouping data points on the basis of category, here as region and event. "
},
{
"code": null,
"e": 29780,
"s": 29772,
"text": "Python3"
},
{
"code": "import seaborn seaborn.set(style = 'whitegrid')fmri = seaborn.load_dataset(\"fmri\") seaborn.violinplot(x =\"timepoint\", y =\"signal\", hue =\"region\", style =\"event\", data = fmri)",
"e": 30013,
"s": 29780,
"text": null
},
{
"code": null,
"e": 30021,
"s": 30013,
"text": "Output:"
},
{
"code": null,
"e": 30087,
"s": 30021,
"text": "Example 3: Basic visualization of “tips” dataset using lineplot()"
},
{
"code": null,
"e": 30095,
"s": 30087,
"text": "Python3"
},
{
"code": "import seaborn seaborn.set(style = 'whitegrid') tip = seaborn.load_dataset('tips') seaborn.violinplot(x ='day', y ='tip', data = tip)",
"e": 30237,
"s": 30095,
"text": null
},
{
"code": null,
"e": 30245,
"s": 30237,
"text": "Output:"
},
{
"code": null,
"e": 30304,
"s": 30245,
"text": "1.Draw a single horizontal swarm plot using only one axis:"
},
{
"code": null,
"e": 30444,
"s": 30304,
"text": "If we use only one data variable instead of two data variables then it means that the axis denotes each of these data variables as an axis."
},
{
"code": null,
"e": 30487,
"s": 30444,
"text": "X denotes an x-axis and y denote a y-axis."
},
{
"code": null,
"e": 30496,
"s": 30487,
"text": "Syntax: "
},
{
"code": null,
"e": 30518,
"s": 30496,
"text": "seaborn.violinplot(x)"
},
{
"code": null,
"e": 30524,
"s": 30518,
"text": "Code:"
},
{
"code": null,
"e": 30532,
"s": 30524,
"text": "Python3"
},
{
"code": "# Python program to illustrate# violinplot using inbuilt data-set# given in seaborn # importing the required moduleimport seaborn # use to set style of background of plotseaborn.set(style=\"whitegrid\") # loading data-settips = seaborn.load_dataset(\"tips\") seaborn.violinplot(x=tip[\"total_bill\"])",
"e": 30828,
"s": 30532,
"text": null
},
{
"code": null,
"e": 30836,
"s": 30828,
"text": "Output:"
},
{
"code": null,
"e": 30867,
"s": 30836,
"text": "2. Draw horizontal violinplot:"
},
{
"code": null,
"e": 31040,
"s": 30867,
"text": "In the above example we see how to plot a single horizontal violinplot plot and here can perform multiple horizontal plot with exchange the data variable with another axis."
},
{
"code": null,
"e": 31048,
"s": 31040,
"text": "Python3"
},
{
"code": "# Python program to illustrate# violinplot using inbuilt data-set# given in seaborn # importing the required moduleimport seaborn # use to set style of background of plotseaborn.set(style=\"whitegrid\") # loading data-settips = seaborn.load_dataset(\"tips\") seaborn.violinplot(x=\"tip\", y=\"day\", data=tip)",
"e": 31351,
"s": 31048,
"text": null
},
{
"code": null,
"e": 31359,
"s": 31351,
"text": "Output:"
},
{
"code": null,
"e": 31383,
"s": 31359,
"text": "3. Using hue parameter:"
},
{
"code": null,
"e": 31528,
"s": 31383,
"text": "While the points are plotted in two dimensions, another dimension can be added to the plot by coloring the points according to a third variable."
},
{
"code": null,
"e": 31536,
"s": 31528,
"text": "Syntax:"
},
{
"code": null,
"e": 31568,
"s": 31536,
"text": "sns.violinplot(x, y, hue, data)"
},
{
"code": null,
"e": 31576,
"s": 31568,
"text": "Python3"
},
{
"code": "# Python program to illustrate# violinplot using inbuilt data-set# given in seaborn # importing the required moduleimport seaborn # use to set style of background of plotseaborn.set(style=\"whitegrid\") # loading data-settips = seaborn.load_dataset(\"tips\") seaborn.violinplot(x=\"day\", y=\"total_bill\", hue=\"time\", data=tips)",
"e": 31899,
"s": 31576,
"text": null
},
{
"code": null,
"e": 31907,
"s": 31899,
"text": "Output:"
},
{
"code": null,
"e": 31964,
"s": 31907,
"text": "4. Draw outlines around the data points using linewidth:"
},
{
"code": null,
"e": 32098,
"s": 31964,
"text": "Width of the gray lines that frame the plot elements. Whenever we increase linewidth than the point also will increase automatically."
},
{
"code": null,
"e": 32106,
"s": 32098,
"text": "Syntax:"
},
{
"code": null,
"e": 32148,
"s": 32106,
"text": "seaborn.violinplot(x, y, data, linewidth)"
},
{
"code": null,
"e": 32156,
"s": 32148,
"text": "Python3"
},
{
"code": "# Python program to illustrate# violinplot using inbuilt data-set# given in seaborn # importing the required moduleimport seaborn # use to set style of background of plotseaborn.set(style=\"whitegrid\") # loading data-settips = seaborn.load_dataset(\"tips\") seaborn.violinplot(x ='day', y ='tip', data = tip, linewidth = 4)",
"e": 32478,
"s": 32156,
"text": null
},
{
"code": null,
"e": 32486,
"s": 32478,
"text": "Output:"
},
{
"code": null,
"e": 32579,
"s": 32486,
"text": "5. Draw each level of the hue variable at different locations on the major categorical axis:"
},
{
"code": null,
"e": 32775,
"s": 32579,
"text": "When using hue nesting, setting dodge should be True will separate the point for different hue levels along the categorical axis. And Palette is used for the different levels of the hue variable."
},
{
"code": null,
"e": 32783,
"s": 32775,
"text": "Syntax:"
},
{
"code": null,
"e": 32835,
"s": 32783,
"text": "seaborn.violinplot(x, y, data, hue, palette, dodge)"
},
{
"code": null,
"e": 32843,
"s": 32835,
"text": "Python3"
},
{
"code": "# Python program to illustrate# violinplot using inbuilt data-set# given in seaborn # importing the required moduleimport seaborn # use to set style of background of plotseaborn.set(style=\"whitegrid\") # loading data-settips = seaborn.load_dataset(\"tips\") seaborn.violinplot(x=\"day\", y=\"total_bill\", hue=\"smoker\", data=tips, palette=\"Set2\", dodge=True)",
"e": 33214,
"s": 32843,
"text": null
},
{
"code": null,
"e": 33222,
"s": 33214,
"text": "Output:"
},
{
"code": null,
"e": 33254,
"s": 33222,
"text": "Possible values of palette are:"
},
{
"code": null,
"e": 33364,
"s": 33254,
"text": "Accent, Accent_r, Blues, Blues_r, BrBG, BrBG_r, BuGn, BuGn_r, BuPu, BuPu_r, CMRmap, CMRmap_r, Dark2, Dark2_r,"
},
{
"code": null,
"e": 33478,
"s": 33364,
"text": "GnBu, GnBu_r, Greens, Greens_r, Greys, Greys_r, OrRd, OrRd_r, Oranges, Oranges_r, PRGn, PRGn_r, Paired, Paired_r,"
},
{
"code": null,
"e": 33592,
"s": 33478,
"text": "Pastel1, Pastel1_r, Pastel2, Pastel2_r, PiYG, PiYG_r, PuBu, PuBuGn, PuBuGn_r, PuBu_r, PuOr, PuOr_r, PuRd, PuRd_r,"
},
{
"code": null,
"e": 33710,
"s": 33592,
"text": "Purples, Purples_r, RdBu, RdBu_r, RdGy, RdGy_r, RdPu, RdPu_r, RdYlBu, RdYlBu_r, RdYlGn, RdYlGn_r, Reds, Reds_r, Set1,"
},
{
"code": null,
"e": 33826,
"s": 33710,
"text": "Set1_r, Set2, Set2_r, Set3, Set3_r, Spectral, Spectral_r, Wistia, Wistia_r, YlGn, YlGnBu, YlGnBu_r, YlGn_r, YlOrBr,"
},
{
"code": null,
"e": 33946,
"s": 33826,
"text": "YlOrBr_r, YlOrRd, YlOrRd_r, afmhot, afmhot_r, autumn, autumn_r, binary, binary_r, bone, bone_r, brg, brg_r, bwr, bwr_r,"
},
{
"code": null,
"e": 34070,
"s": 33946,
"text": "cividis, cividis_r, cool, cool_r, coolwarm, coolwarm_r, copper, copper_r, cubehelix, cubehelix_r, flag, flag_r, gist_earth,"
},
{
"code": null,
"e": 34199,
"s": 34070,
"text": "gist_earth_r, gist_gray, gist_gray_r, gist_heat, gist_heat_r, gist_ncar, gist_ncar_r, gist_rainbow, gist_rainbow_r, gist_stern, "
},
{
"code": null,
"e": 34253,
"s": 34199,
"text": "7. Control violin order by passing an explicit order:"
},
{
"code": null,
"e": 34261,
"s": 34253,
"text": "Python3"
},
{
"code": "# Python program to illustrate# violinplot using inbuilt data-set# given in seaborn # importing the required moduleimport seaborn # use to set style of background of plotseaborn.set(style=\"whitegrid\") # loading data-settips = seaborn.load_dataset(\"tips\") seaborn.violinplot(x=\"time\", y=\"tip\", data=tips, order=[\"Dinner\", \"Lunch\"])",
"e": 34611,
"s": 34261,
"text": null
},
{
"code": null,
"e": 34619,
"s": 34611,
"text": "Output:"
},
{
"code": null,
"e": 34653,
"s": 34619,
"text": "8. Adding the palette attributes:"
},
{
"code": null,
"e": 34846,
"s": 34653,
"text": "Using the palette we can generate the point with different colors. In this below example we can see the palette can be responsible for a generate the violinplot with different colormap values."
},
{
"code": null,
"e": 34854,
"s": 34846,
"text": "Syntax:"
},
{
"code": null,
"e": 34908,
"s": 34854,
"text": "seaborn.violinplot( x, y, data, palette=”color_name”)"
},
{
"code": null,
"e": 34916,
"s": 34908,
"text": "Python3"
},
{
"code": "# Python program to illustrate# violinplot using inbuilt data-set# given in seaborn # importing the required moduleimport seaborn # use to set style of background of plotseaborn.set(style=\"whitegrid\") # loading data-settips = seaborn.load_dataset(\"tips\") seaborn.violinplot(x='day', y='total_bill', data=tips, hue='time', palette='pastel')",
"e": 35275,
"s": 34916,
"text": null
},
{
"code": null,
"e": 35283,
"s": 35275,
"text": "Output:"
},
{
"code": null,
"e": 35319,
"s": 35283,
"text": "9. Adding the saturation parameter:"
},
{
"code": null,
"e": 35529,
"s": 35319,
"text": "Proportion of the original saturation to draw colors at. Large patches often look better with slightly desaturated colors, but set this to 1 if you want the plot colors to perfectly match the input color spec."
},
{
"code": null,
"e": 35537,
"s": 35529,
"text": "Syntax:"
},
{
"code": null,
"e": 35580,
"s": 35537,
"text": "seaborn.violinplot(x, y, data, saturation)"
},
{
"code": null,
"e": 35588,
"s": 35580,
"text": "Python3"
},
{
"code": "# Python program to illustrate# violinplot using inbuilt data-set# given in seaborn # importing the required moduleimport seaborn # use to set style of background of plotseaborn.set(style=\"whitegrid\") # loading data-settips = seaborn.load_dataset(\"tips\") seaborn.violinplot(x ='day', y ='tip', data = tip, saturation =0.03)",
"e": 35931,
"s": 35588,
"text": null
},
{
"code": null,
"e": 35939,
"s": 35931,
"text": "Output:"
},
{
"code": null,
"e": 35967,
"s": 35939,
"text": "10. Adding color parameter:"
},
{
"code": null,
"e": 36034,
"s": 35967,
"text": "It will Color for all the elements or seed for a gradient palette."
},
{
"code": null,
"e": 36042,
"s": 36034,
"text": "Syntax:"
},
{
"code": null,
"e": 36080,
"s": 36042,
"text": "seaborn.violinplot(x, y, data, color)"
},
{
"code": null,
"e": 36088,
"s": 36080,
"text": "Python3"
},
{
"code": "# Python program to illustrate# violinplot using inbuilt data-set# given in seaborn # importing the required moduleimport seaborn # use to set style of background of plotseaborn.set(style=\"whitegrid\") # loading data-settips = seaborn.load_dataset(\"tips\") seaborn.violinplot(x ='day', y ='tip', data = tip, color = \"Yellow\")",
"e": 36413,
"s": 36088,
"text": null
},
{
"code": null,
"e": 36421,
"s": 36413,
"text": "Output:"
},
{
"code": null,
"e": 36491,
"s": 36421,
"text": "11. Scale the violin width by the number of observations in each bin:"
},
{
"code": null,
"e": 36499,
"s": 36491,
"text": "Python3"
},
{
"code": "# Python program to illustrate# violinplot using inbuilt data-set# given in seaborn # importing the required moduleimport seaborn # use to set style of background of plotseaborn.set(style=\"whitegrid\") # loading data-settips = seaborn.load_dataset(\"tips\") seaborn.violinplot(x=\"day\", y=\"total_bill\", hue=\"sex\", data=tip, palette=\"Set2\", split=True, scale=\"count\")",
"e": 36901,
"s": 36499,
"text": null
},
{
"code": null,
"e": 36909,
"s": 36901,
"text": "Output:"
},
{
"code": null,
"e": 36922,
"s": 36909,
"text": "kumar_satyam"
},
{
"code": null,
"e": 36932,
"s": 36922,
"text": "ruhelaa48"
},
{
"code": null,
"e": 36947,
"s": 36932,
"text": "Python-Seaborn"
},
{
"code": null,
"e": 36954,
"s": 36947,
"text": "Python"
},
{
"code": null,
"e": 37052,
"s": 36954,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37080,
"s": 37052,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 37130,
"s": 37080,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 37152,
"s": 37130,
"text": "Python map() function"
},
{
"code": null,
"e": 37196,
"s": 37152,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 37214,
"s": 37196,
"text": "Python Dictionary"
},
{
"code": null,
"e": 37237,
"s": 37214,
"text": "Taking input in Python"
},
{
"code": null,
"e": 37272,
"s": 37237,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 37304,
"s": 37272,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 37326,
"s": 37304,
"text": "Enumerate() in Python"
}
] |
Cube - CUBEVALUE Function
|
The CUBEVALUE function returns an aggregated value from the cube.
CUBEVALUE (connection, [member_expression1], [member_expression2], ...)
A text string of a multidimensional expression (MDX) that evaluates to a member or tuple within the cube.
OR
A set defined with the CUBESET function.
Use the Argument member_expression as a slicer to define the portion of the cube for which the aggregated value is returned.
Use the Argument member_expression as a slicer to define the portion of the cube for which the aggregated value is returned.
If no measure is specified in member_expression, the default measure for that cube is used.
If no measure is specified in member_expression, the default measure for that cube is used.
When the CUBEVALUE function evaluates, it temporarily displays a "#GETTING_DATA..." message in the cell before all of the data is retrieved.
When the CUBEVALUE function evaluates, it temporarily displays a "#GETTING_DATA..." message in the cell before all of the data is retrieved.
If a cell reference is used for member_expression, and that cell reference contains a CUBE function, then member_expression uses the MDX expression for the item in the referenced cell, and not the value displayed in that referenced cell.
If a cell reference is used for member_expression, and that cell reference contains a CUBE function, then member_expression uses the MDX expression for the item in the referenced cell, and not the value displayed in that referenced cell.
If the connection name is not a valid workbook connection stored in the workbook, CUBEVALUE returns a #NAME? Error value. If the Online Analytical Processing (OLAP) server is not running, not available, or returns an error message, CUBEVALUE returns a #NAME? Error value.
If the connection name is not a valid workbook connection stored in the workbook, CUBEVALUE returns a #NAME? Error value. If the Online Analytical Processing (OLAP) server is not running, not available, or returns an error message, CUBEVALUE returns a #NAME? Error value.
If at least one element within the tuple is invalid, CUBEVALUE returns a #VALUE! Error value.
If at least one element within the tuple is invalid, CUBEVALUE returns a #VALUE! Error value.
CUBEVALUE returns a #N/A error value when
The member_expression syntax is incorrect
The member specified by member_expression doesn't exist in the cube
The tuple is invalid because there is no intersection for the specified values. (This can occur with multiple elements from the same hierarchy).
The set contains at least one member with a different dimension than the other members.
CUBEVALUE may return a #N/A error value if you reference a session-based object, such as a calculated member or named set, in a PivotTable when sharing a connection. The PivotTable is deleted or you convert the PivotTable to formulas. (On the Options tab, in the Tools group, click OLAP Tools, and then clickConvert to Formulas.)
CUBEVALUE returns a #N/A error value when
The member_expression syntax is incorrect
The member_expression syntax is incorrect
The member specified by member_expression doesn't exist in the cube
The member specified by member_expression doesn't exist in the cube
The tuple is invalid because there is no intersection for the specified values. (This can occur with multiple elements from the same hierarchy).
The tuple is invalid because there is no intersection for the specified values. (This can occur with multiple elements from the same hierarchy).
The set contains at least one member with a different dimension than the other members.
The set contains at least one member with a different dimension than the other members.
CUBEVALUE may return a #N/A error value if you reference a session-based object, such as a calculated member or named set, in a PivotTable when sharing a connection. The PivotTable is deleted or you convert the PivotTable to formulas. (On the Options tab, in the Tools group, click OLAP Tools, and then clickConvert to Formulas.)
CUBEVALUE may return a #N/A error value if you reference a session-based object, such as a calculated member or named set, in a PivotTable when sharing a connection. The PivotTable is deleted or you convert the PivotTable to formulas. (On the Options tab, in the Tools group, click OLAP Tools, and then clickConvert to Formulas.)
Issue: Null values are converted to zero-length strings
In Excel, if a cell has no data because you never changed it or you deleted the contents, the cell contains an empty value. In many database systems, an empty value is called a Null value. An empty or Null value literally means "No value." However, a formula can never return an empty string or Null value. A formula always returns one of three values −
A number value
A text value, which may be a zero-length string
An error value, such as #NUM! or #VALUE
In Excel, if a cell has no data because you never changed it or you deleted the contents, the cell contains an empty value. In many database systems, an empty value is called a Null value. An empty or Null value literally means "No value." However, a formula can never return an empty string or Null value. A formula always returns one of three values −
A number value
A text value, which may be a zero-length string
An error value, such as #NUM! or #VALUE
If a formula contains a CUBEVALUE function connected to an Online Analytical Processing (OLAP) database and a query to this database results in a Null value, Excel converts this Null value to a zero-length string, even if the formula would otherwise return a number value. This can lead to a situation where a range of cells contain a combination of numeric and zero-length string values, and this situation can affect the results of other formulas that reference that range of cells.
If a formula contains a CUBEVALUE function connected to an Online Analytical Processing (OLAP) database and a query to this database results in a Null value, Excel converts this Null value to a zero-length string, even if the formula would otherwise return a number value. This can lead to a situation where a range of cells contain a combination of numeric and zero-length string values, and this situation can affect the results of other formulas that reference that range of cells.
For example, if A1 and A3 contain numbers, and A2 contains a formula with a CUBEVALUE function that returns a zero-length string, the following formula would return a #VALUE! Error −
=A1+A2+A3
For example, if A1 and A3 contain numbers, and A2 contains a formula with a CUBEVALUE function that returns a zero-length string, the following formula would return a #VALUE! Error −
=A1+A2+A3
To prevent this, you can test for a zero-length string by using the ISTEXT function. You can use the IF function to replace the zero-length with a 0 (zero) as follows −
To prevent this, you can test for a zero-length string by using the ISTEXT function. You can use the IF function to replace the zero-length with a 0 (zero) as follows −
=IF(ISTEXT(A1),0,A1)+IF(ISTEXT(A2),0,A2)+IF(ISTEXT(A3),0,A3)
Alternatively, you can nest the CUBEVALUE function in an IF condition that returns a 0 value if the CUBEVALUE function evaluates to a zero-length string as follows −
Alternatively, you can nest the CUBEVALUE function in an IF condition that returns a 0 value if the CUBEVALUE function evaluates to a zero-length string as follows −
=IF (CUBEVALUE ("Sales","[Measures].[Profit]","[Time].[2004]",
"[All Product].[Beverages]")="", 0, CUBEVALUE("Sales",
"[Measures].[Profit]","[Time].[2004]","[All Product].[Beverages]"))
Excel 2007, Excel 2010, Excel 2013, Excel 2016
296 Lectures
146 hours
Arun Motoori
56 Lectures
5.5 hours
Pavan Lalwani
120 Lectures
6.5 hours
Inf Sid
134 Lectures
8.5 hours
Yoda Learning
46 Lectures
7.5 hours
William Fiset
25 Lectures
1.5 hours
Sasha Miller
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1920,
"s": 1854,
"text": "The CUBEVALUE function returns an aggregated value from the cube."
},
{
"code": null,
"e": 1993,
"s": 1920,
"text": "CUBEVALUE (connection, [member_expression1], [member_expression2], ...)\n"
},
{
"code": null,
"e": 2099,
"s": 1993,
"text": "A text string of a multidimensional expression (MDX) that evaluates to a member or tuple within the cube."
},
{
"code": null,
"e": 2102,
"s": 2099,
"text": "OR"
},
{
"code": null,
"e": 2143,
"s": 2102,
"text": "A set defined with the CUBESET function."
},
{
"code": null,
"e": 2268,
"s": 2143,
"text": "Use the Argument member_expression as a slicer to define the portion of the cube for which the aggregated value is returned."
},
{
"code": null,
"e": 2393,
"s": 2268,
"text": "Use the Argument member_expression as a slicer to define the portion of the cube for which the aggregated value is returned."
},
{
"code": null,
"e": 2485,
"s": 2393,
"text": "If no measure is specified in member_expression, the default measure for that cube is used."
},
{
"code": null,
"e": 2577,
"s": 2485,
"text": "If no measure is specified in member_expression, the default measure for that cube is used."
},
{
"code": null,
"e": 2718,
"s": 2577,
"text": "When the CUBEVALUE function evaluates, it temporarily displays a \"#GETTING_DATA...\" message in the cell before all of the data is retrieved."
},
{
"code": null,
"e": 2859,
"s": 2718,
"text": "When the CUBEVALUE function evaluates, it temporarily displays a \"#GETTING_DATA...\" message in the cell before all of the data is retrieved."
},
{
"code": null,
"e": 3097,
"s": 2859,
"text": "If a cell reference is used for member_expression, and that cell reference contains a CUBE function, then member_expression uses the MDX expression for the item in the referenced cell, and not the value displayed in that referenced cell."
},
{
"code": null,
"e": 3335,
"s": 3097,
"text": "If a cell reference is used for member_expression, and that cell reference contains a CUBE function, then member_expression uses the MDX expression for the item in the referenced cell, and not the value displayed in that referenced cell."
},
{
"code": null,
"e": 3607,
"s": 3335,
"text": "If the connection name is not a valid workbook connection stored in the workbook, CUBEVALUE returns a #NAME? Error value. If the Online Analytical Processing (OLAP) server is not running, not available, or returns an error message, CUBEVALUE returns a #NAME? Error value."
},
{
"code": null,
"e": 3879,
"s": 3607,
"text": "If the connection name is not a valid workbook connection stored in the workbook, CUBEVALUE returns a #NAME? Error value. If the Online Analytical Processing (OLAP) server is not running, not available, or returns an error message, CUBEVALUE returns a #NAME? Error value."
},
{
"code": null,
"e": 3973,
"s": 3879,
"text": "If at least one element within the tuple is invalid, CUBEVALUE returns a #VALUE! Error value."
},
{
"code": null,
"e": 4067,
"s": 3973,
"text": "If at least one element within the tuple is invalid, CUBEVALUE returns a #VALUE! Error value."
},
{
"code": null,
"e": 4785,
"s": 4067,
"text": "CUBEVALUE returns a #N/A error value when\n\nThe member_expression syntax is incorrect\nThe member specified by member_expression doesn't exist in the cube\nThe tuple is invalid because there is no intersection for the specified values. (This can occur with multiple elements from the same hierarchy).\nThe set contains at least one member with a different dimension than the other members.\nCUBEVALUE may return a #N/A error value if you reference a session-based object, such as a calculated member or named set, in a PivotTable when sharing a connection. The PivotTable is deleted or you convert the PivotTable to formulas. (On the Options tab, in the Tools group, click OLAP Tools, and then clickConvert to Formulas.)\n\n"
},
{
"code": null,
"e": 4827,
"s": 4785,
"text": "CUBEVALUE returns a #N/A error value when"
},
{
"code": null,
"e": 4869,
"s": 4827,
"text": "The member_expression syntax is incorrect"
},
{
"code": null,
"e": 4911,
"s": 4869,
"text": "The member_expression syntax is incorrect"
},
{
"code": null,
"e": 4979,
"s": 4911,
"text": "The member specified by member_expression doesn't exist in the cube"
},
{
"code": null,
"e": 5047,
"s": 4979,
"text": "The member specified by member_expression doesn't exist in the cube"
},
{
"code": null,
"e": 5192,
"s": 5047,
"text": "The tuple is invalid because there is no intersection for the specified values. (This can occur with multiple elements from the same hierarchy)."
},
{
"code": null,
"e": 5337,
"s": 5192,
"text": "The tuple is invalid because there is no intersection for the specified values. (This can occur with multiple elements from the same hierarchy)."
},
{
"code": null,
"e": 5425,
"s": 5337,
"text": "The set contains at least one member with a different dimension than the other members."
},
{
"code": null,
"e": 5513,
"s": 5425,
"text": "The set contains at least one member with a different dimension than the other members."
},
{
"code": null,
"e": 5844,
"s": 5513,
"text": "CUBEVALUE may return a #N/A error value if you reference a session-based object, such as a calculated member or named set, in a PivotTable when sharing a connection. The PivotTable is deleted or you convert the PivotTable to formulas. (On the Options tab, in the Tools group, click OLAP Tools, and then clickConvert to Formulas.)\n"
},
{
"code": null,
"e": 6174,
"s": 5844,
"text": "CUBEVALUE may return a #N/A error value if you reference a session-based object, such as a calculated member or named set, in a PivotTable when sharing a connection. The PivotTable is deleted or you convert the PivotTable to formulas. (On the Options tab, in the Tools group, click OLAP Tools, and then clickConvert to Formulas.)"
},
{
"code": null,
"e": 6230,
"s": 6174,
"text": "Issue: Null values are converted to zero-length strings"
},
{
"code": null,
"e": 6690,
"s": 6230,
"text": "In Excel, if a cell has no data because you never changed it or you deleted the contents, the cell contains an empty value. In many database systems, an empty value is called a Null value. An empty or Null value literally means \"No value.\" However, a formula can never return an empty string or Null value. A formula always returns one of three values −\n\nA number value\nA text value, which may be a zero-length string\nAn error value, such as #NUM! or #VALUE\n\n"
},
{
"code": null,
"e": 7044,
"s": 6690,
"text": "In Excel, if a cell has no data because you never changed it or you deleted the contents, the cell contains an empty value. In many database systems, an empty value is called a Null value. An empty or Null value literally means \"No value.\" However, a formula can never return an empty string or Null value. A formula always returns one of three values −"
},
{
"code": null,
"e": 7059,
"s": 7044,
"text": "A number value"
},
{
"code": null,
"e": 7107,
"s": 7059,
"text": "A text value, which may be a zero-length string"
},
{
"code": null,
"e": 7147,
"s": 7107,
"text": "An error value, such as #NUM! or #VALUE"
},
{
"code": null,
"e": 7633,
"s": 7147,
"text": "If a formula contains a CUBEVALUE function connected to an Online Analytical Processing (OLAP) database and a query to this database results in a Null value, Excel converts this Null value to a zero-length string, even if the formula would otherwise return a number value. This can lead to a situation where a range of cells contain a combination of numeric and zero-length string values, and this situation can affect the results of other formulas that reference that range of cells. "
},
{
"code": null,
"e": 8119,
"s": 7633,
"text": "If a formula contains a CUBEVALUE function connected to an Online Analytical Processing (OLAP) database and a query to this database results in a Null value, Excel converts this Null value to a zero-length string, even if the formula would otherwise return a number value. This can lead to a situation where a range of cells contain a combination of numeric and zero-length string values, and this situation can affect the results of other formulas that reference that range of cells. "
},
{
"code": null,
"e": 8312,
"s": 8119,
"text": "For example, if A1 and A3 contain numbers, and A2 contains a formula with a CUBEVALUE function that returns a zero-length string, the following formula would return a #VALUE! Error −\n=A1+A2+A3"
},
{
"code": null,
"e": 8495,
"s": 8312,
"text": "For example, if A1 and A3 contain numbers, and A2 contains a formula with a CUBEVALUE function that returns a zero-length string, the following formula would return a #VALUE! Error −"
},
{
"code": null,
"e": 8505,
"s": 8495,
"text": "=A1+A2+A3"
},
{
"code": null,
"e": 8674,
"s": 8505,
"text": "To prevent this, you can test for a zero-length string by using the ISTEXT function. You can use the IF function to replace the zero-length with a 0 (zero) as follows −"
},
{
"code": null,
"e": 8843,
"s": 8674,
"text": "To prevent this, you can test for a zero-length string by using the ISTEXT function. You can use the IF function to replace the zero-length with a 0 (zero) as follows −"
},
{
"code": null,
"e": 8905,
"s": 8843,
"text": "=IF(ISTEXT(A1),0,A1)+IF(ISTEXT(A2),0,A2)+IF(ISTEXT(A3),0,A3)\n"
},
{
"code": null,
"e": 9071,
"s": 8905,
"text": "Alternatively, you can nest the CUBEVALUE function in an IF condition that returns a 0 value if the CUBEVALUE function evaluates to a zero-length string as follows −"
},
{
"code": null,
"e": 9237,
"s": 9071,
"text": "Alternatively, you can nest the CUBEVALUE function in an IF condition that returns a 0 value if the CUBEVALUE function evaluates to a zero-length string as follows −"
},
{
"code": null,
"e": 9430,
"s": 9237,
"text": "=IF (CUBEVALUE (\"Sales\",\"[Measures].[Profit]\",\"[Time].[2004]\",\n \"[All Product].[Beverages]\")=\"\", 0, CUBEVALUE(\"Sales\",\n \"[Measures].[Profit]\",\"[Time].[2004]\",\"[All Product].[Beverages]\"))\n"
},
{
"code": null,
"e": 9477,
"s": 9430,
"text": "Excel 2007, Excel 2010, Excel 2013, Excel 2016"
},
{
"code": null,
"e": 9513,
"s": 9477,
"text": "\n 296 Lectures \n 146 hours \n"
},
{
"code": null,
"e": 9527,
"s": 9513,
"text": " Arun Motoori"
},
{
"code": null,
"e": 9562,
"s": 9527,
"text": "\n 56 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 9577,
"s": 9562,
"text": " Pavan Lalwani"
},
{
"code": null,
"e": 9613,
"s": 9577,
"text": "\n 120 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 9622,
"s": 9613,
"text": " Inf Sid"
},
{
"code": null,
"e": 9658,
"s": 9622,
"text": "\n 134 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 9673,
"s": 9658,
"text": " Yoda Learning"
},
{
"code": null,
"e": 9708,
"s": 9673,
"text": "\n 46 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 9723,
"s": 9708,
"text": " William Fiset"
},
{
"code": null,
"e": 9758,
"s": 9723,
"text": "\n 25 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 9772,
"s": 9758,
"text": " Sasha Miller"
},
{
"code": null,
"e": 9779,
"s": 9772,
"text": " Print"
},
{
"code": null,
"e": 9790,
"s": 9779,
"text": " Add Notes"
}
] |
Random Forests and the Bias-Variance Tradeoff | by Prratek Ramchandani | Towards Data Science
|
The Random Forest is an extremely popular machine learning algorithm. Often, with not too much pre-processing, one can throw together a quick and dirty model with no hyperparameter tuning and acheive results that aren’t awful. As an example, I put together a RandomForestRegressor in Python using scikit-learn for the New York City Taxi Fare Prediction playground competition on Kaggle recently, passing in no arguments to the model constructor and using 1/100 for the training data (554238 of ~55M rows), for a validation R2 of ~0.8. Try it yourself!
NOTE: This snippet assumes you split the data into training and validation sets with your features and target variable separated. You can see the full code on my GitHub profile.
Part of what makes this algorithm so clever is how it handles something called the bias-variance tradeoff. I explore this aspect of Random Forests in the following 5 steps:
Bias and VarianceDecision TreesBagging, Bootstrapping, and Random ForestsHyperparameter TuningRandom Forests and the Bias-Variance Tradeoff
Bias and Variance
Decision Trees
Bagging, Bootstrapping, and Random Forests
Hyperparameter Tuning
Random Forests and the Bias-Variance Tradeoff
The Mean Squared Error (MSE) of a statistical model can be expressed as the sum of the squared bias of its predictions, the variance of those predictions, and the variance of some error term ε. Since both squared bias and variance are non-negative, and ε, which captures randomness in the data, is beyond our control, we minimize MSE by minimizing the variance and bias of our model. I have found the image in Fig. 1 to be particularly good at illustrating what the two terms mean.
We say our model is biased if it systematically under or over predicts the target variable. In machine learning, this is often the result either of the statistical assumptions made by our model of choice or of bias in the training data. Take a look at this article for an example of bias where Google’s Cloud Natural Language API learned through text on the internet that the word “homosexual” carries an inherent negative connotation.
Variance, on the other hand, in some sense captures the generalizability of the model. Put more precisely, it is a measure of how much our prediction would change if we trained it on different data. High variance typicaly means that we are overfitting to our training data, finding patterns and complexity that are a product of randomness as opposed to some real trend. Generally, a more complex or flexible model will tend to have high variance due to overfitting but lower bias because, averaged over several predictions, our model more accurately predicts the target variable. On the other hand, an underfit or oversimplified model, while having lower variance, will likely be more biased since it lacks the tools to fully capture trends in the data.
What we would like, ideally, is low bias-low variance. To see how to acheive this, let’s first look at a typical bias squared-variance curve.
Fig. 2 illustrates the general trend I described above of decreasing bias and increasing variance as our model gets more complex. Our goal is to choose a model that minimizes the sum of the two as illustrated by the dotted line. To see how a Random Forest does this particularly well, let’s start with a simple decision tree.
Let’s go back to the taxi fare prediction task. Given certain features of a particular taxi ride, a decision tree starts off by simply predicting the average taxi fare in the training dataset ($11.33) as shown in the leftmost box in Fig. 3. It then goes through the list of all features and their values to find a binary split that gives us the maximum improvement in MSE. This is typically calculated by predicting the mean of each of the two new subsets and computing their respective MSEs weighted by the number of observations in each.
In this case the best split happens to be whether the ride distance was less than or equal to 0.083 (units of degrees latitude/longitude = 5.727 miles). When it is less than 5.727 miles, the tree predicts $9.28 — the mean fare of those rides with distance less than this — and through the same procedure reaches a prediction of $35.09 for those longer than our threshold. This makes sense. Long rides are more expensive.
As illustrated by the figure, it then splits each branch into new branches on the same criterion of maximal improvement in MSE, continuing recursively until each leaf (group of samples) has only one training observation in it. Decision Trees have extremely low bias because they maximally overfit to the training data. Each “prediction” it makes on the validation set would in essence be the fare of some taxi ride in our training data that ended up in the same final leaf node as the ride whose fare we are predicting. This overfitting, however, also results in unacceptably high variance and consequently poor predictions on unseen data.
While an individual tree is overfit to the training data and is likely to have large error, bagging (Bootstrap Aggregating) uses the insight that a suitably large number of uncorrelated errors average out to zero to solve this problem. Bagging chooses multiple random samples of observations from the training data, with replacement, constructing a tree from each one. Since each tree learns from different data, they are fairly uncorrelated from one another. Plotting the R2 of our model as we increase the number of “bagged” trees ( scikit-learn calls these trees estimators) illustrates the power of this technique.
(array([ 9. , 8.1, 8.1, 11.5, 6.1, 6.9, 6.5, 8.1, 10.5, 6.5]), 8.13)
Think of each tree in our forest as learning some unique insights about what contributes to the fare of a New York City taxi from the subset of data it models. Averaging together each of their predictions then gives us a stronger, more stable model able to predict the fare of a taxi ride it hasn’t previously been exposed to with better accuracy.
Random Forests, however, are more than just bagged trees and use a number of interesting techniques to further decrease correlation between trees and reduce overfitting. A quick look at the documentation for scikit-learn’s implementation of the RandomForestRegressor shows us the hyperparameters we can pass in:
class sklearn.ensemble.RandomForestRegressor(n_estimators=10, criterion=’mse’, max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features=’auto’, max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, bootstrap=True, oob_score=False, n_jobs=1, random_state=None, verbose=0, warm_start=False
There’s over a dozen of them but here I take a closer look what n_estimators, max_depth, min_samples_leaf, and max_features do and why each of them could potentially decrease the error of your model.
n_estimators is simply the number of trees. The more uncorrelated trees in our forest, the closer their individual errors get to averaging out. However, more is not always better and here are some considerations to keep in mind:
More trees = more computation. Beyond a certain point, the tradeoff may not be worth it.On a related note, increasing n_estimators gives diminishing returns as evidenced by Fig. 5. Increasing from 370 trees to 400, for example, isn’t even guaranteed to decrease your validation MSE.No number of uncorrelated trees will get rid of error caused by the assumptions made by your model or bias resulting from unrepresentative training data.
More trees = more computation. Beyond a certain point, the tradeoff may not be worth it.
On a related note, increasing n_estimators gives diminishing returns as evidenced by Fig. 5. Increasing from 370 trees to 400, for example, isn’t even guaranteed to decrease your validation MSE.
No number of uncorrelated trees will get rid of error caused by the assumptions made by your model or bias resulting from unrepresentative training data.
max_depth is the how many splits deep you want each tree to go. max_depth = 50, for example, would limit trees to at most 50 splits down any given branch. This has the consequence that our Random Forest can no more fit the training data as closely, and is consequently more stable. It has lower variance, giving our model lower error. Remember that even though severely constraining max_depth could increase the bias of each tree given that they may not be able to capture certain patterns in the data before hitting their limit, we need not worry about this. A suitable choice of n_estimators, coupled with bagging, ensures that the bias of the forest as a whole doesn’t increase in the process.
max_depth is a hyperparameter that I typically leave untouched simply because what I really care about is how many observations are at the end of a branch before I forbid the tree from splitting further. This is a better predictor of how overfit the Random Forest is.
min_samples_leaf allows us to do exactly what I described above. min_samples_leaf = 10, for instance, tells each tree to stop splitting if doing so would result in the end node of any resulting branch having less than 10 leaves. To better understand why this is useful, think about how a Decision Tree makes predictions, which I outline again within the context of our taxi fare prediction problem. Once done training, it predicts the fare of a taxi ride by passing features of that ride through the tree and finding the end node to which this ride is closest in tree space.
If this is a leaf node, which would be the case if min_samples_leaf = 1 (the default), the forest is predicting the actual fare of the particular ride in the training set to which this ride happened to be closest. It is almost a certainty that splits toward the ends of the branches aren’t capturing actual patterns about the fare of taxi rides in New York City, but just what happened to correspond to a higher or lower fare in the training data. Passing in some larger min_samples_leaf means that we now predict the average of some group of samples to which the ride in question is closest in tree space. This technique generalizes noticeably better.
I typically trymin_samples_leaf = [1, 3, 5, 10, 20, 50], stopping once increasing min_samples_leaf doesn’t improve the metric I am interested in.
max_features tells each tree how many features to check when looking for the best split to make. A subtlety here is that passing in max_features = 15 doesn’t mean that each tree picks some subset of 15 features to model. Rather, an individual tree chooses a different random sample of 15 features for each split. Like min_samples_leaf, this doesn’t allow a tree to fit too closely to the data. More importantly, the trees in the Random Forest are now even less correlated with one another since they weren’t even trained on the same data. There has been some practical machine learning research showing that forests of less accurate, less correlated trees perform better than forests of more accurate, more correlated trees.
A common approach to hyperparameter tuning in machine learning is to use a technique implemented in scikit-learn called RandomizedSearchCV. This takes as required arguments the model itself and the parameter space we are interested in.
class sklearn.model_selection.RandomizedSearchCV(estimator, param_distributions, n_iter=10, scoring=None, fit_params=None, n_jobs=1, iid=True, refit=True, cv=None, verbose=0, pre_dispatch=‘2*n_jobs’, random_state=None, error_score=’raise’, return_train_score=’warn’)
It randomly tries n_iter combinations of these parameters and returns the best hyperparameters of those sampled and the corresponding score. To illustrate the effect of changing individual parameters, however, I show here how my RandomForestRegressor performed for some manually chosen combinations. First let’s see how well a Random Forest with n_estimators = 100 with no other arguments passed in performs:
[4.262844864358172, 4.098490006842908, 0.8090730776697076, 0.8239641822866088]
n_jobs = -1 just tells scikit-learn to use all available cores on the computer. Also, print_score() is a function from the fast.ai library that returns training error, validation error, training R2, and validation R2. Our baseline then is a validation R2 of ~0.824. Here’s what playing with max_features does:
[4.289944262409593, 3.9900355584905385, 0.8066378726809564, 0.8331574522424692]
[4.322218978148121, 4.136388496420818, 0.8037174696184352, 0.820693545036434]
While using max_features = 'log2' times the number of features improved performance somewhat, max_features = 'sqrt' did the opposite. What works best is likely to vary from case to case, making some form of trial and error the simplest and most popular option. Feel free to play around with some other hyperparameters by yourself. For the sake of brevity, I won’t do that here. Finally, after choosing my hyperparameters, I trained one RandomForestRegressor using a larger number of estimators to further improve R2:
[4.013807675575337, 3.8493455368979235, 0.830729516598271, 0.8447158691316341]
To sum up, the Random Forest employs a number of techniques to reduce variance in predictions while maintaining (to some extent) the low variance that was characteristic of the lone Decision Tree. It does this primarily by averaging together a number of very weakly correlated (if not completely uncorrelated) trees. Hyperparameters like max_features and min_samples_leaf are among the techniques useful in reducing this correlation between trees, but they often come at the cost of some increase in bias, since each tree now has less data to work with.
Our goal, then, is to choose a set of hyperparameters that nagivates this tradeoff between bias and variance so as to minimize error (or maximize goodness-of-fit) on some new set of data (the validation set) that we believe is representative of what the model might encounter when solving the real world problem it was designed for (the test set).
|
[
{
"code": null,
"e": 724,
"s": 172,
"text": "The Random Forest is an extremely popular machine learning algorithm. Often, with not too much pre-processing, one can throw together a quick and dirty model with no hyperparameter tuning and acheive results that aren’t awful. As an example, I put together a RandomForestRegressor in Python using scikit-learn for the New York City Taxi Fare Prediction playground competition on Kaggle recently, passing in no arguments to the model constructor and using 1/100 for the training data (554238 of ~55M rows), for a validation R2 of ~0.8. Try it yourself!"
},
{
"code": null,
"e": 902,
"s": 724,
"text": "NOTE: This snippet assumes you split the data into training and validation sets with your features and target variable separated. You can see the full code on my GitHub profile."
},
{
"code": null,
"e": 1075,
"s": 902,
"text": "Part of what makes this algorithm so clever is how it handles something called the bias-variance tradeoff. I explore this aspect of Random Forests in the following 5 steps:"
},
{
"code": null,
"e": 1215,
"s": 1075,
"text": "Bias and VarianceDecision TreesBagging, Bootstrapping, and Random ForestsHyperparameter TuningRandom Forests and the Bias-Variance Tradeoff"
},
{
"code": null,
"e": 1233,
"s": 1215,
"text": "Bias and Variance"
},
{
"code": null,
"e": 1248,
"s": 1233,
"text": "Decision Trees"
},
{
"code": null,
"e": 1291,
"s": 1248,
"text": "Bagging, Bootstrapping, and Random Forests"
},
{
"code": null,
"e": 1313,
"s": 1291,
"text": "Hyperparameter Tuning"
},
{
"code": null,
"e": 1359,
"s": 1313,
"text": "Random Forests and the Bias-Variance Tradeoff"
},
{
"code": null,
"e": 1841,
"s": 1359,
"text": "The Mean Squared Error (MSE) of a statistical model can be expressed as the sum of the squared bias of its predictions, the variance of those predictions, and the variance of some error term ε. Since both squared bias and variance are non-negative, and ε, which captures randomness in the data, is beyond our control, we minimize MSE by minimizing the variance and bias of our model. I have found the image in Fig. 1 to be particularly good at illustrating what the two terms mean."
},
{
"code": null,
"e": 2277,
"s": 1841,
"text": "We say our model is biased if it systematically under or over predicts the target variable. In machine learning, this is often the result either of the statistical assumptions made by our model of choice or of bias in the training data. Take a look at this article for an example of bias where Google’s Cloud Natural Language API learned through text on the internet that the word “homosexual” carries an inherent negative connotation."
},
{
"code": null,
"e": 3031,
"s": 2277,
"text": "Variance, on the other hand, in some sense captures the generalizability of the model. Put more precisely, it is a measure of how much our prediction would change if we trained it on different data. High variance typicaly means that we are overfitting to our training data, finding patterns and complexity that are a product of randomness as opposed to some real trend. Generally, a more complex or flexible model will tend to have high variance due to overfitting but lower bias because, averaged over several predictions, our model more accurately predicts the target variable. On the other hand, an underfit or oversimplified model, while having lower variance, will likely be more biased since it lacks the tools to fully capture trends in the data."
},
{
"code": null,
"e": 3173,
"s": 3031,
"text": "What we would like, ideally, is low bias-low variance. To see how to acheive this, let’s first look at a typical bias squared-variance curve."
},
{
"code": null,
"e": 3499,
"s": 3173,
"text": "Fig. 2 illustrates the general trend I described above of decreasing bias and increasing variance as our model gets more complex. Our goal is to choose a model that minimizes the sum of the two as illustrated by the dotted line. To see how a Random Forest does this particularly well, let’s start with a simple decision tree."
},
{
"code": null,
"e": 4039,
"s": 3499,
"text": "Let’s go back to the taxi fare prediction task. Given certain features of a particular taxi ride, a decision tree starts off by simply predicting the average taxi fare in the training dataset ($11.33) as shown in the leftmost box in Fig. 3. It then goes through the list of all features and their values to find a binary split that gives us the maximum improvement in MSE. This is typically calculated by predicting the mean of each of the two new subsets and computing their respective MSEs weighted by the number of observations in each."
},
{
"code": null,
"e": 4460,
"s": 4039,
"text": "In this case the best split happens to be whether the ride distance was less than or equal to 0.083 (units of degrees latitude/longitude = 5.727 miles). When it is less than 5.727 miles, the tree predicts $9.28 — the mean fare of those rides with distance less than this — and through the same procedure reaches a prediction of $35.09 for those longer than our threshold. This makes sense. Long rides are more expensive."
},
{
"code": null,
"e": 5100,
"s": 4460,
"text": "As illustrated by the figure, it then splits each branch into new branches on the same criterion of maximal improvement in MSE, continuing recursively until each leaf (group of samples) has only one training observation in it. Decision Trees have extremely low bias because they maximally overfit to the training data. Each “prediction” it makes on the validation set would in essence be the fare of some taxi ride in our training data that ended up in the same final leaf node as the ride whose fare we are predicting. This overfitting, however, also results in unacceptably high variance and consequently poor predictions on unseen data."
},
{
"code": null,
"e": 5719,
"s": 5100,
"text": "While an individual tree is overfit to the training data and is likely to have large error, bagging (Bootstrap Aggregating) uses the insight that a suitably large number of uncorrelated errors average out to zero to solve this problem. Bagging chooses multiple random samples of observations from the training data, with replacement, constructing a tree from each one. Since each tree learns from different data, they are fairly uncorrelated from one another. Plotting the R2 of our model as we increase the number of “bagged” trees ( scikit-learn calls these trees estimators) illustrates the power of this technique."
},
{
"code": null,
"e": 5795,
"s": 5719,
"text": "(array([ 9. , 8.1, 8.1, 11.5, 6.1, 6.9, 6.5, 8.1, 10.5, 6.5]), 8.13)"
},
{
"code": null,
"e": 6143,
"s": 5795,
"text": "Think of each tree in our forest as learning some unique insights about what contributes to the fare of a New York City taxi from the subset of data it models. Averaging together each of their predictions then gives us a stronger, more stable model able to predict the fare of a taxi ride it hasn’t previously been exposed to with better accuracy."
},
{
"code": null,
"e": 6455,
"s": 6143,
"text": "Random Forests, however, are more than just bagged trees and use a number of interesting techniques to further decrease correlation between trees and reduce overfitting. A quick look at the documentation for scikit-learn’s implementation of the RandomForestRegressor shows us the hyperparameters we can pass in:"
},
{
"code": null,
"e": 6805,
"s": 6455,
"text": "class sklearn.ensemble.RandomForestRegressor(n_estimators=10, criterion=’mse’, max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features=’auto’, max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, bootstrap=True, oob_score=False, n_jobs=1, random_state=None, verbose=0, warm_start=False"
},
{
"code": null,
"e": 7005,
"s": 6805,
"text": "There’s over a dozen of them but here I take a closer look what n_estimators, max_depth, min_samples_leaf, and max_features do and why each of them could potentially decrease the error of your model."
},
{
"code": null,
"e": 7234,
"s": 7005,
"text": "n_estimators is simply the number of trees. The more uncorrelated trees in our forest, the closer their individual errors get to averaging out. However, more is not always better and here are some considerations to keep in mind:"
},
{
"code": null,
"e": 7670,
"s": 7234,
"text": "More trees = more computation. Beyond a certain point, the tradeoff may not be worth it.On a related note, increasing n_estimators gives diminishing returns as evidenced by Fig. 5. Increasing from 370 trees to 400, for example, isn’t even guaranteed to decrease your validation MSE.No number of uncorrelated trees will get rid of error caused by the assumptions made by your model or bias resulting from unrepresentative training data."
},
{
"code": null,
"e": 7759,
"s": 7670,
"text": "More trees = more computation. Beyond a certain point, the tradeoff may not be worth it."
},
{
"code": null,
"e": 7954,
"s": 7759,
"text": "On a related note, increasing n_estimators gives diminishing returns as evidenced by Fig. 5. Increasing from 370 trees to 400, for example, isn’t even guaranteed to decrease your validation MSE."
},
{
"code": null,
"e": 8108,
"s": 7954,
"text": "No number of uncorrelated trees will get rid of error caused by the assumptions made by your model or bias resulting from unrepresentative training data."
},
{
"code": null,
"e": 8805,
"s": 8108,
"text": "max_depth is the how many splits deep you want each tree to go. max_depth = 50, for example, would limit trees to at most 50 splits down any given branch. This has the consequence that our Random Forest can no more fit the training data as closely, and is consequently more stable. It has lower variance, giving our model lower error. Remember that even though severely constraining max_depth could increase the bias of each tree given that they may not be able to capture certain patterns in the data before hitting their limit, we need not worry about this. A suitable choice of n_estimators, coupled with bagging, ensures that the bias of the forest as a whole doesn’t increase in the process."
},
{
"code": null,
"e": 9073,
"s": 8805,
"text": "max_depth is a hyperparameter that I typically leave untouched simply because what I really care about is how many observations are at the end of a branch before I forbid the tree from splitting further. This is a better predictor of how overfit the Random Forest is."
},
{
"code": null,
"e": 9648,
"s": 9073,
"text": "min_samples_leaf allows us to do exactly what I described above. min_samples_leaf = 10, for instance, tells each tree to stop splitting if doing so would result in the end node of any resulting branch having less than 10 leaves. To better understand why this is useful, think about how a Decision Tree makes predictions, which I outline again within the context of our taxi fare prediction problem. Once done training, it predicts the fare of a taxi ride by passing features of that ride through the tree and finding the end node to which this ride is closest in tree space."
},
{
"code": null,
"e": 10301,
"s": 9648,
"text": "If this is a leaf node, which would be the case if min_samples_leaf = 1 (the default), the forest is predicting the actual fare of the particular ride in the training set to which this ride happened to be closest. It is almost a certainty that splits toward the ends of the branches aren’t capturing actual patterns about the fare of taxi rides in New York City, but just what happened to correspond to a higher or lower fare in the training data. Passing in some larger min_samples_leaf means that we now predict the average of some group of samples to which the ride in question is closest in tree space. This technique generalizes noticeably better."
},
{
"code": null,
"e": 10447,
"s": 10301,
"text": "I typically trymin_samples_leaf = [1, 3, 5, 10, 20, 50], stopping once increasing min_samples_leaf doesn’t improve the metric I am interested in."
},
{
"code": null,
"e": 11172,
"s": 10447,
"text": "max_features tells each tree how many features to check when looking for the best split to make. A subtlety here is that passing in max_features = 15 doesn’t mean that each tree picks some subset of 15 features to model. Rather, an individual tree chooses a different random sample of 15 features for each split. Like min_samples_leaf, this doesn’t allow a tree to fit too closely to the data. More importantly, the trees in the Random Forest are now even less correlated with one another since they weren’t even trained on the same data. There has been some practical machine learning research showing that forests of less accurate, less correlated trees perform better than forests of more accurate, more correlated trees."
},
{
"code": null,
"e": 11408,
"s": 11172,
"text": "A common approach to hyperparameter tuning in machine learning is to use a technique implemented in scikit-learn called RandomizedSearchCV. This takes as required arguments the model itself and the parameter space we are interested in."
},
{
"code": null,
"e": 11675,
"s": 11408,
"text": "class sklearn.model_selection.RandomizedSearchCV(estimator, param_distributions, n_iter=10, scoring=None, fit_params=None, n_jobs=1, iid=True, refit=True, cv=None, verbose=0, pre_dispatch=‘2*n_jobs’, random_state=None, error_score=’raise’, return_train_score=’warn’)"
},
{
"code": null,
"e": 12084,
"s": 11675,
"text": "It randomly tries n_iter combinations of these parameters and returns the best hyperparameters of those sampled and the corresponding score. To illustrate the effect of changing individual parameters, however, I show here how my RandomForestRegressor performed for some manually chosen combinations. First let’s see how well a Random Forest with n_estimators = 100 with no other arguments passed in performs:"
},
{
"code": null,
"e": 12163,
"s": 12084,
"text": "[4.262844864358172, 4.098490006842908, 0.8090730776697076, 0.8239641822866088]"
},
{
"code": null,
"e": 12473,
"s": 12163,
"text": "n_jobs = -1 just tells scikit-learn to use all available cores on the computer. Also, print_score() is a function from the fast.ai library that returns training error, validation error, training R2, and validation R2. Our baseline then is a validation R2 of ~0.824. Here’s what playing with max_features does:"
},
{
"code": null,
"e": 12553,
"s": 12473,
"text": "[4.289944262409593, 3.9900355584905385, 0.8066378726809564, 0.8331574522424692]"
},
{
"code": null,
"e": 12631,
"s": 12553,
"text": "[4.322218978148121, 4.136388496420818, 0.8037174696184352, 0.820693545036434]"
},
{
"code": null,
"e": 13148,
"s": 12631,
"text": "While using max_features = 'log2' times the number of features improved performance somewhat, max_features = 'sqrt' did the opposite. What works best is likely to vary from case to case, making some form of trial and error the simplest and most popular option. Feel free to play around with some other hyperparameters by yourself. For the sake of brevity, I won’t do that here. Finally, after choosing my hyperparameters, I trained one RandomForestRegressor using a larger number of estimators to further improve R2:"
},
{
"code": null,
"e": 13227,
"s": 13148,
"text": "[4.013807675575337, 3.8493455368979235, 0.830729516598271, 0.8447158691316341]"
},
{
"code": null,
"e": 13781,
"s": 13227,
"text": "To sum up, the Random Forest employs a number of techniques to reduce variance in predictions while maintaining (to some extent) the low variance that was characteristic of the lone Decision Tree. It does this primarily by averaging together a number of very weakly correlated (if not completely uncorrelated) trees. Hyperparameters like max_features and min_samples_leaf are among the techniques useful in reducing this correlation between trees, but they often come at the cost of some increase in bias, since each tree now has less data to work with."
}
] |
Set Button on Image with CSS
|
You can try to run the following code to set button on an image:
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
.box {
position: relative;
width: 100%;
max-width: 250px;
}
.box img {
width: 100%;
height: auto;
}
.box .btn {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
</head>
<body>
<div class = "box">
<img src = "https://www.tutorialspoint.com/videotutorials/images/current_affairs_home.jpg" alt = "Current Affairs">
<button class = "btn">Button</button>
</div>
</body>
</html>
|
[
{
"code": null,
"e": 1127,
"s": 1062,
"text": "You can try to run the following code to set button on an image:"
},
{
"code": null,
"e": 1137,
"s": 1127,
"text": "Live Demo"
},
{
"code": null,
"e": 1801,
"s": 1137,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n .box {\n position: relative;\n width: 100%;\n max-width: 250px;\n }\n .box img {\n width: 100%;\n height: auto;\n }\n .box .btn {\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n }\n </style>\n </head>\n <body>\n <div class = \"box\">\n <img src = \"https://www.tutorialspoint.com/videotutorials/images/current_affairs_home.jpg\" alt = \"Current Affairs\">\n <button class = \"btn\">Button</button>\n </div>\n </body>\n</html>"
}
] |
How to Save Data to the Firebase Realtime Database in Android?
|
31 Dec, 2020
Firebase is one of the famous backend platforms which is used by so many developers to provide backend support to their applications and websites. It is the product of Google which provides services such as database, storage, user authentication, and many more. In this article, we will create a simple app in which we will be adding our Data to Firebase Realtime Database. Note that we are going to implement this project using the Java language.
Firebase Realtime Database is a NoSQL cloud database that is used to store and sync the data. The data from the database can be synced at a time across all the clients such as android, web as well as IOS. The data in the database is stored in the JSON format and it updates in real-time with every connected client.
The main advantage of using the Firebase Realtime database is that the data is updated in a real-time manner and you don’t have to make any requests for the data updates or changes. The database uses data synchronization every time when data changes and these changes will reflect the connected user within milliseconds.
While using Firebase Realtime Database your apps remain responsive even if the device loses its connectivity to the database. Once the user has established the connection he will receive the changes made in the data from the database.
The data stored in the Firebase database can be easily accessible through the web portal of Firebase. You can manage your database from PC as well as mobile devices. You can manage the rules of the database which gives permissions to read and write operations to the database.
In this article, we are going to build a simple application in which we will be getting the data from the users with the help of some TextFields and store that data in the Firebase Realtime Database. Note that we are using Firebase Realtime Database and the app is written using JAVA language.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Connect your app to Firebase
After creating a new project navigate to the Tools option on the top bar. Inside that click on Firebase. After clicking on Firebase, you can get to see the right column mentioned below in the screenshot.
Inside that column Navigate to Firebase Realtime Database. Click on that option and you will get to see two options on Connect app to Firebase and Add Firebase Realtime Database to your app. Click on Connect now and your app will be connected to Firebase. After that click on the second option and now your App is connected to Firebase.
After connecting your app to Firebase you will get to see the below screen.
After that verify that dependency for Firebase Realtime database has been added to our Gradle file. Now navigate to the app > Gradle Scripts and inside that file check whether the below dependency is added or not. If the below dependency is not added in your build.gradle file. Add the below dependency in the dependencies section.
implementation ‘com.google.firebase:firebase-database:19.6.0’
After adding this dependency sync your project and now we are ready for creating our app. If you want to know more about connecting your app to Firebase. Refer to this article to get in detail about Adding Firebase to Android App.
Step 3: Working with AndroidManifest.xml file
For adding data to Firebase we should have to give permissions for accessing the internet. For adding these permissions navigate to the app > AndroidManifest.xml and inside that file add the below permissions to it.
XML
<uses-permission android:name="android.permission.INTERNET"/><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Step 4: Working with the activity_main.xml file
Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!--EditText for adding employee name--> <EditText android:id="@+id/idEdtEmployeeName" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_margin="10dp" android:hint="Enter Employee Name" android:importantForAutofill="no" android:inputType="textPersonName" /> <!--EditText for adding employee phone--> <EditText android:id="@+id/idEdtEmployeePhoneNumber" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idEdtEmployeeName" android:layout_margin="10dp" android:hint="Enter employee phone number" android:importantForAutofill="no" android:inputType="phone" /> <!--EditText for adding employee address--> <EditText android:id="@+id/idEdtEmployeeAddress" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idEdtEmployeePhoneNumber" android:layout_margin="10dp" android:hint="Enter employee address" android:inputType="textPostalAddress" /> <!--Button for adding data to Firebase--> <Button android:id="@+id/idBtnSendData" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idEdtEmployeeAddress" android:layout_margin="10dp" android:text="Add employee details" android:textAllCaps="false" /> </RelativeLayout>
Step 5: Create a new Java class for storing our data
For sending multiple data to the Firebase Realtime database we have to create an Object class and send that whole object class to Firebase. For creating an object class navigate to the app > java > your app’s package name > Right-click on it and Click on New > Java Class > Give a name to your class. In my case, it is EmployeeInfo, and add below code to it.
Java
public class EmployeeInfo { // string variable for // storing employee name. private String employeeName; // string variable for storing // employee contact number private String employeeContactNumber; // string variable for storing // employee address. private String employeeAddress; // an empty constructor is // required when using // Firebase Realtime Database. public EmployeeInfo() { } // created getter and setter methods // for all our variables. public String getEmployeeName() { return employeeName; } public void setEmployeeName(String employeeName) { this.employeeName = employeeName; } public String getEmployeeContactNumber() { return employeeContactNumber; } public void setEmployeeContactNumber(String employeeContactNumber) { this.employeeContactNumber = employeeContactNumber; } public String getEmployeeAddress() { return employeeAddress; } public void setEmployeeAddress(String employeeAddress) { this.employeeAddress = employeeAddress; }}
Step 6: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.os.Bundle;import android.text.TextUtils;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.appcompat.app.AppCompatActivity; import com.google.firebase.database.DataSnapshot;import com.google.firebase.database.DatabaseError;import com.google.firebase.database.DatabaseReference;import com.google.firebase.database.FirebaseDatabase;import com.google.firebase.database.ValueEventListener; public class MainActivity extends AppCompatActivity { // creating variables for // EditText and buttons. private EditText employeeNameEdt, employeePhoneEdt, employeeAddressEdt; private Button sendDatabtn; // creating a variable for our // Firebase Database. FirebaseDatabase firebaseDatabase; // creating a variable for our Database // Reference for Firebase. DatabaseReference databaseReference; // creating a variable for // our object class EmployeeInfo employeeInfo; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing our edittext and button employeeNameEdt = findViewById(R.id.idEdtEmployeeName); employeePhoneEdt = findViewById(R.id.idEdtEmployeePhoneNumber); employeeAddressEdt = findViewById(R.id.idEdtEmployeeAddress); // below line is used to get the // instance of our FIrebase database. firebaseDatabase = FirebaseDatabase.getInstance(); // below line is used to get reference for our database. databaseReference = firebaseDatabase.getReference("EmployeeInfo"); // initializing our object // class variable. employeeInfo = new EmployeeInfo(); sendDatabtn = findViewById(R.id.idBtnSendData); // adding on click listener for our button. sendDatabtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // getting text from our edittext fields. String name = employeeNameEdt.getText().toString(); String phone = employeePhoneEdt.getText().toString(); String address = employeeAddressEdt.getText().toString(); // below line is for checking weather the // edittext fields are empty or not. if (TextUtils.isEmpty(name) && TextUtils.isEmpty(phone) && TextUtils.isEmpty(address)) { // if the text fields are empty // then show the below message. Toast.makeText(MainActivity.this, "Please add some data.", Toast.LENGTH_SHORT).show(); } else { // else call the method to add // data to our database. addDatatoFirebase(name, phone, address); } } }); } private void addDatatoFirebase(String name, String phone, String address) { // below 3 lines of code is used to set // data in our object class. employeeInfo.setEmployeeName(name); employeeInfo.setEmployeeContactNumber(phone); employeeInfo.setEmployeeAddress(address); // we are use add value event listener method // which is called with database reference. databaseReference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { // inside the method of on Data change we are setting // our object class to our database reference. // data base reference will sends data to firebase. databaseReference.setValue(employeeInfo); // after adding this data we are showing toast message. Toast.makeText(MainActivity.this, "data added", Toast.LENGTH_SHORT).show(); } @Override public void onCancelled(@NonNull DatabaseError error) { // if the data is not added or it is cancelled then // we are displaying a failure toast message. Toast.makeText(MainActivity.this, "Fail to add data " + error, Toast.LENGTH_SHORT).show(); } }); }}
After adding this code go to this link for Firebase. After clicking on this link you will get to see the below page and on this page Click on Go to Console option in the top right corner.
After clicking on this screen you will get to see the below screen with your all project inside that select your project.
Inside that screen click n Realtime Database in the left window.
After clicking on this option you will get to see the screen on the right side. On this page click on the Rules option which is present in the top bar. You will get to see the below screen.
Inside this screen click on the Rules tab you will get to see the above screen and change the rules to true as shown in the screenshot. The rules are changed to true because we are not providing authentication inside our app and we have to write data to our database. That’s why we are specifying it to true. After changing your rules click on the publish rules button. Click on that option and your rules will be published. Now come back to the Data tab of your database.
Below is the video for our app for adding data to the Firebase Realtime Database.
Run the app and make sure to connect your device to the internet. After that add some data in your text fields and click on the Insert data button. The data will be added to our Firebase Database. Below is the screenshot we will get to see after adding data to Firebase Database from the app.
android
Technical Scripter 2020
Android
Java
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n31 Dec, 2020"
},
{
"code": null,
"e": 503,
"s": 54,
"text": "Firebase is one of the famous backend platforms which is used by so many developers to provide backend support to their applications and websites. It is the product of Google which provides services such as database, storage, user authentication, and many more. In this article, we will create a simple app in which we will be adding our Data to Firebase Realtime Database. Note that we are going to implement this project using the Java language. "
},
{
"code": null,
"e": 821,
"s": 503,
"text": "Firebase Realtime Database is a NoSQL cloud database that is used to store and sync the data. The data from the database can be synced at a time across all the clients such as android, web as well as IOS. The data in the database is stored in the JSON format and it updates in real-time with every connected client. "
},
{
"code": null,
"e": 1142,
"s": 821,
"text": "The main advantage of using the Firebase Realtime database is that the data is updated in a real-time manner and you don’t have to make any requests for the data updates or changes. The database uses data synchronization every time when data changes and these changes will reflect the connected user within milliseconds."
},
{
"code": null,
"e": 1377,
"s": 1142,
"text": "While using Firebase Realtime Database your apps remain responsive even if the device loses its connectivity to the database. Once the user has established the connection he will receive the changes made in the data from the database."
},
{
"code": null,
"e": 1654,
"s": 1377,
"text": "The data stored in the Firebase database can be easily accessible through the web portal of Firebase. You can manage your database from PC as well as mobile devices. You can manage the rules of the database which gives permissions to read and write operations to the database."
},
{
"code": null,
"e": 1949,
"s": 1654,
"text": "In this article, we are going to build a simple application in which we will be getting the data from the users with the help of some TextFields and store that data in the Firebase Realtime Database. Note that we are using Firebase Realtime Database and the app is written using JAVA language. "
},
{
"code": null,
"e": 1978,
"s": 1949,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 2140,
"s": 1978,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language."
},
{
"code": null,
"e": 2177,
"s": 2140,
"text": "Step 2: Connect your app to Firebase"
},
{
"code": null,
"e": 2381,
"s": 2177,
"text": "After creating a new project navigate to the Tools option on the top bar. Inside that click on Firebase. After clicking on Firebase, you can get to see the right column mentioned below in the screenshot."
},
{
"code": null,
"e": 2719,
"s": 2381,
"text": "Inside that column Navigate to Firebase Realtime Database. Click on that option and you will get to see two options on Connect app to Firebase and Add Firebase Realtime Database to your app. Click on Connect now and your app will be connected to Firebase. After that click on the second option and now your App is connected to Firebase. "
},
{
"code": null,
"e": 2796,
"s": 2719,
"text": "After connecting your app to Firebase you will get to see the below screen. "
},
{
"code": null,
"e": 3128,
"s": 2796,
"text": "After that verify that dependency for Firebase Realtime database has been added to our Gradle file. Now navigate to the app > Gradle Scripts and inside that file check whether the below dependency is added or not. If the below dependency is not added in your build.gradle file. Add the below dependency in the dependencies section."
},
{
"code": null,
"e": 3190,
"s": 3128,
"text": "implementation ‘com.google.firebase:firebase-database:19.6.0’"
},
{
"code": null,
"e": 3422,
"s": 3190,
"text": "After adding this dependency sync your project and now we are ready for creating our app. If you want to know more about connecting your app to Firebase. Refer to this article to get in detail about Adding Firebase to Android App. "
},
{
"code": null,
"e": 3468,
"s": 3422,
"text": "Step 3: Working with AndroidManifest.xml file"
},
{
"code": null,
"e": 3685,
"s": 3468,
"text": "For adding data to Firebase we should have to give permissions for accessing the internet. For adding these permissions navigate to the app > AndroidManifest.xml and inside that file add the below permissions to it. "
},
{
"code": null,
"e": 3689,
"s": 3685,
"text": "XML"
},
{
"code": "<uses-permission android:name=\"android.permission.INTERNET\"/><uses-permission android:name=\"android.permission.ACCESS_NETWORK_STATE\"/>",
"e": 3824,
"s": 3689,
"text": null
},
{
"code": null,
"e": 3872,
"s": 3824,
"text": "Step 4: Working with the activity_main.xml file"
},
{
"code": null,
"e": 3988,
"s": 3872,
"text": "Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file."
},
{
"code": null,
"e": 3992,
"s": 3988,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!--EditText for adding employee name--> <EditText android:id=\"@+id/idEdtEmployeeName\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_centerHorizontal=\"true\" android:layout_margin=\"10dp\" android:hint=\"Enter Employee Name\" android:importantForAutofill=\"no\" android:inputType=\"textPersonName\" /> <!--EditText for adding employee phone--> <EditText android:id=\"@+id/idEdtEmployeePhoneNumber\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idEdtEmployeeName\" android:layout_margin=\"10dp\" android:hint=\"Enter employee phone number\" android:importantForAutofill=\"no\" android:inputType=\"phone\" /> <!--EditText for adding employee address--> <EditText android:id=\"@+id/idEdtEmployeeAddress\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idEdtEmployeePhoneNumber\" android:layout_margin=\"10dp\" android:hint=\"Enter employee address\" android:inputType=\"textPostalAddress\" /> <!--Button for adding data to Firebase--> <Button android:id=\"@+id/idBtnSendData\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idEdtEmployeeAddress\" android:layout_margin=\"10dp\" android:text=\"Add employee details\" android:textAllCaps=\"false\" /> </RelativeLayout>",
"e": 5841,
"s": 3992,
"text": null
},
{
"code": null,
"e": 5894,
"s": 5841,
"text": "Step 5: Create a new Java class for storing our data"
},
{
"code": null,
"e": 6254,
"s": 5894,
"text": "For sending multiple data to the Firebase Realtime database we have to create an Object class and send that whole object class to Firebase. For creating an object class navigate to the app > java > your app’s package name > Right-click on it and Click on New > Java Class > Give a name to your class. In my case, it is EmployeeInfo, and add below code to it. "
},
{
"code": null,
"e": 6259,
"s": 6254,
"text": "Java"
},
{
"code": "public class EmployeeInfo { // string variable for // storing employee name. private String employeeName; // string variable for storing // employee contact number private String employeeContactNumber; // string variable for storing // employee address. private String employeeAddress; // an empty constructor is // required when using // Firebase Realtime Database. public EmployeeInfo() { } // created getter and setter methods // for all our variables. public String getEmployeeName() { return employeeName; } public void setEmployeeName(String employeeName) { this.employeeName = employeeName; } public String getEmployeeContactNumber() { return employeeContactNumber; } public void setEmployeeContactNumber(String employeeContactNumber) { this.employeeContactNumber = employeeContactNumber; } public String getEmployeeAddress() { return employeeAddress; } public void setEmployeeAddress(String employeeAddress) { this.employeeAddress = employeeAddress; }}",
"e": 7382,
"s": 6259,
"text": null
},
{
"code": null,
"e": 7430,
"s": 7382,
"text": "Step 6: Working with the MainActivity.java file"
},
{
"code": null,
"e": 7620,
"s": 7430,
"text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 7625,
"s": 7620,
"text": "Java"
},
{
"code": "import android.os.Bundle;import android.text.TextUtils;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.appcompat.app.AppCompatActivity; import com.google.firebase.database.DataSnapshot;import com.google.firebase.database.DatabaseError;import com.google.firebase.database.DatabaseReference;import com.google.firebase.database.FirebaseDatabase;import com.google.firebase.database.ValueEventListener; public class MainActivity extends AppCompatActivity { // creating variables for // EditText and buttons. private EditText employeeNameEdt, employeePhoneEdt, employeeAddressEdt; private Button sendDatabtn; // creating a variable for our // Firebase Database. FirebaseDatabase firebaseDatabase; // creating a variable for our Database // Reference for Firebase. DatabaseReference databaseReference; // creating a variable for // our object class EmployeeInfo employeeInfo; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing our edittext and button employeeNameEdt = findViewById(R.id.idEdtEmployeeName); employeePhoneEdt = findViewById(R.id.idEdtEmployeePhoneNumber); employeeAddressEdt = findViewById(R.id.idEdtEmployeeAddress); // below line is used to get the // instance of our FIrebase database. firebaseDatabase = FirebaseDatabase.getInstance(); // below line is used to get reference for our database. databaseReference = firebaseDatabase.getReference(\"EmployeeInfo\"); // initializing our object // class variable. employeeInfo = new EmployeeInfo(); sendDatabtn = findViewById(R.id.idBtnSendData); // adding on click listener for our button. sendDatabtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // getting text from our edittext fields. String name = employeeNameEdt.getText().toString(); String phone = employeePhoneEdt.getText().toString(); String address = employeeAddressEdt.getText().toString(); // below line is for checking weather the // edittext fields are empty or not. if (TextUtils.isEmpty(name) && TextUtils.isEmpty(phone) && TextUtils.isEmpty(address)) { // if the text fields are empty // then show the below message. Toast.makeText(MainActivity.this, \"Please add some data.\", Toast.LENGTH_SHORT).show(); } else { // else call the method to add // data to our database. addDatatoFirebase(name, phone, address); } } }); } private void addDatatoFirebase(String name, String phone, String address) { // below 3 lines of code is used to set // data in our object class. employeeInfo.setEmployeeName(name); employeeInfo.setEmployeeContactNumber(phone); employeeInfo.setEmployeeAddress(address); // we are use add value event listener method // which is called with database reference. databaseReference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { // inside the method of on Data change we are setting // our object class to our database reference. // data base reference will sends data to firebase. databaseReference.setValue(employeeInfo); // after adding this data we are showing toast message. Toast.makeText(MainActivity.this, \"data added\", Toast.LENGTH_SHORT).show(); } @Override public void onCancelled(@NonNull DatabaseError error) { // if the data is not added or it is cancelled then // we are displaying a failure toast message. Toast.makeText(MainActivity.this, \"Fail to add data \" + error, Toast.LENGTH_SHORT).show(); } }); }}",
"e": 12100,
"s": 7625,
"text": null
},
{
"code": null,
"e": 12289,
"s": 12100,
"text": "After adding this code go to this link for Firebase. After clicking on this link you will get to see the below page and on this page Click on Go to Console option in the top right corner. "
},
{
"code": null,
"e": 12412,
"s": 12289,
"text": "After clicking on this screen you will get to see the below screen with your all project inside that select your project. "
},
{
"code": null,
"e": 12478,
"s": 12412,
"text": "Inside that screen click n Realtime Database in the left window. "
},
{
"code": null,
"e": 12669,
"s": 12478,
"text": "After clicking on this option you will get to see the screen on the right side. On this page click on the Rules option which is present in the top bar. You will get to see the below screen. "
},
{
"code": null,
"e": 13142,
"s": 12669,
"text": "Inside this screen click on the Rules tab you will get to see the above screen and change the rules to true as shown in the screenshot. The rules are changed to true because we are not providing authentication inside our app and we have to write data to our database. That’s why we are specifying it to true. After changing your rules click on the publish rules button. Click on that option and your rules will be published. Now come back to the Data tab of your database."
},
{
"code": null,
"e": 13225,
"s": 13142,
"text": "Below is the video for our app for adding data to the Firebase Realtime Database. "
},
{
"code": null,
"e": 13518,
"s": 13225,
"text": "Run the app and make sure to connect your device to the internet. After that add some data in your text fields and click on the Insert data button. The data will be added to our Firebase Database. Below is the screenshot we will get to see after adding data to Firebase Database from the app."
},
{
"code": null,
"e": 13526,
"s": 13518,
"text": "android"
},
{
"code": null,
"e": 13550,
"s": 13526,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 13558,
"s": 13550,
"text": "Android"
},
{
"code": null,
"e": 13563,
"s": 13558,
"text": "Java"
},
{
"code": null,
"e": 13582,
"s": 13563,
"text": "Technical Scripter"
},
{
"code": null,
"e": 13587,
"s": 13582,
"text": "Java"
},
{
"code": null,
"e": 13595,
"s": 13587,
"text": "Android"
}
] |
UPI Payment Integration in Android
|
14 Dec, 2021
If you are selling any product or providing any service in your android application, then you should have integrated a feature in your android application where you can allow users to make payment through your application. In this article, we will take a look at the implementation of payment gateway integration in Android. In this article, we will be using the Easy UPI Payment gateway library for adding this feature.
We will be creating a simple application in which we will display multiple edit text fields in which we will be allowing users to enter the details for making a payment. After clicking on make payment button we will display a dialog box to our users for making payment through different apps which are installed in users device. Below is the video in which we will get to see what we are going to build in this article.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Adding a dependency for easy payment gateway in android
Navigate to the app > Gradle Scripts > build.gradle(:app) and add the below dependency in the dependencies section.
implementation ‘com.shreyaspatil:EasyUpiPayment:2.0’
After adding this dependency now sync your project and now we will move towards adding internet permissions.
Step 3: Adding internet permissions in AndroidManifest.xml.
Navigate to app > AndroidManifest.xml and add the below code to it.
XML
<uses-permission android:name="android.permission.INTERNET" />
Step 4: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <!--edit text for entering amount to be paid--> <EditText android:id="@+id/idEdtAmount" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="8dp" android:layout_marginTop="15dp" android:layout_marginEnd="8dp" android:hint="Enter Amount to be paid" android:inputType="numberDecimal" /> <!--edit text for entering the upi id to which we have to make payment--> <EditText android:id="@+id/idEdtUpi" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idEdtAmount" android:layout_marginStart="8dp" android:layout_marginTop="15dp" android:layout_marginEnd="8dp" android:hint="Enter your UPI Id" android:inputType="text" /> <!--edit text for adding the name of the user whom we have to make payment--> <EditText android:id="@+id/idEdtName" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idEdtUpi" android:layout_marginStart="8dp" android:layout_marginTop="15dp" android:layout_marginEnd="8dp" android:hint="Enter your Name" android:inputType="text" /> <!--edit text for adding the description for the payment which we are making--> <EditText android:id="@+id/idEdtDescription" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idEdtName" android:layout_marginStart="8dp" android:layout_marginTop="15dp" android:layout_marginEnd="8dp" android:hint="Enter Payment Description" android:inputType="text" /> <!--button for making a payment--> <Button android:id="@+id/idBtnMakePayment" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idEdtDescription" android:layout_margin="12dp" android:text="Make Payment" android:textAllCaps="false" /> <!--text view for displaying transaction status--> <TextView android:id="@+id/idTVTransactionDetails" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idBtnMakePayment" android:layout_marginTop="30dp" android:text="Transaction Details" android:textAlignment="center" android:textColor="@color/purple_700" android:visibility="gone" /> </RelativeLayout>
Step 5: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.os.Bundle;import android.text.TextUtils;import android.util.Log;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.shreyaspatil.EasyUpiPayment.EasyUpiPayment;import com.shreyaspatil.EasyUpiPayment.listener.PaymentStatusListener;import com.shreyaspatil.EasyUpiPayment.model.TransactionDetails; import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date;import java.util.Locale; public class MainActivity extends AppCompatActivity implements PaymentStatusListener { // initializing variables for our edit text and button. private EditText amountEdt, upiEdt, nameEdt, descEdt; private TextView transactionDetailsTV; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing all our variables. amountEdt = findViewById(R.id.idEdtAmount); upiEdt = findViewById(R.id.idEdtUpi); nameEdt = findViewById(R.id.idEdtName); descEdt = findViewById(R.id.idEdtDescription); Button makePaymentBtn = findViewById(R.id.idBtnMakePayment); transactionDetailsTV = findViewById(R.id.idTVTransactionDetails); // on below line we are getting date and then we are setting this date as transaction id. Date c = Calendar.getInstance().getTime(); SimpleDateFormat df = new SimpleDateFormat("ddMMyyyyHHmmss", Locale.getDefault()); String transcId = df.format(c); // on below line we are adding click listener for our payment button. makePaymentBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // on below line we are getting data from our edit text. String amount = amountEdt.getText().toString(); String upi = upiEdt.getText().toString(); String name = nameEdt.getText().toString(); String desc = descEdt.getText().toString(); // on below line we are validating our text field. if (TextUtils.isEmpty(amount) && TextUtils.isEmpty(upi) && TextUtils.isEmpty(name) && TextUtils.isEmpty(desc)) { Toast.makeText(MainActivity.this, "Please enter all the details..", Toast.LENGTH_SHORT).show(); } else { // if the edit text is not empty then // we are calling method to make payment. makePayment(amount, upi, name, desc, transcId); } } }); } private void makePayment(String amount, String upi, String name, String desc, String transactionId) { // on below line we are calling an easy payment method and passing // all parameters to it such as upi id,name, description and others. final EasyUpiPayment easyUpiPayment = new EasyUpiPayment.Builder() .with(this) // on below line we are adding upi id. .setPayeeVpa(upi) // on below line we are setting name to which we are making oayment. .setPayeeName(name) // on below line we are passing transaction id. .setTransactionId(transactionId) // on below line we are passing transaction ref id. .setTransactionRefId(transactionId) // on below line we are adding description to payment. .setDescription(desc) // on below line we are passing amount which is being paid. .setAmount(amount) // on below line we are calling a build method to build this ui. .build(); // on below line we are calling a start // payment method to start a payment. easyUpiPayment.startPayment(); // on below line we are calling a set payment // status listener method to call other payment methods. easyUpiPayment.setPaymentStatusListener(this); } @Override public void onTransactionCompleted(TransactionDetails transactionDetails) { // on below line we are getting details about transaction when completed. String transcDetails = transactionDetails.getStatus().toString() + "\n" + "Transaction ID : " + transactionDetails.getTransactionId(); transactionDetailsTV.setVisibility(View.VISIBLE); // on below line we are setting details to our text view. transactionDetailsTV.setText(transcDetails); } @Override public void onTransactionSuccess() { // this method is called when transaction is successful and we are displaying a toast message. Toast.makeText(this, "Transaction successfully completed..", Toast.LENGTH_SHORT).show(); } @Override public void onTransactionSubmitted() { // this method is called when transaction is done // but it may be successful or failure. Log.e("TAG", "TRANSACTION SUBMIT"); } @Override public void onTransactionFailed() { // this method is called when transaction is failure. Toast.makeText(this, "Failed to complete transaction", Toast.LENGTH_SHORT).show(); } @Override public void onTransactionCancelled() { // this method is called when transaction is cancelled. Toast.makeText(this, "Transaction cancelled..", Toast.LENGTH_SHORT).show(); } @Override public void onAppNotFound() { // this method is called when the users device is not having any app installed for making payment. Toast.makeText(this, "No app found for making transaction..", Toast.LENGTH_SHORT).show(); }}
Now run your app and see the output of the app.
Note: Make sure to run your app on a real device and you should be having an app for making payments. And put the amount in decimal.
Output:
gulshankumarar231
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n14 Dec, 2021"
},
{
"code": null,
"e": 476,
"s": 54,
"text": "If you are selling any product or providing any service in your android application, then you should have integrated a feature in your android application where you can allow users to make payment through your application. In this article, we will take a look at the implementation of payment gateway integration in Android. In this article, we will be using the Easy UPI Payment gateway library for adding this feature. "
},
{
"code": null,
"e": 897,
"s": 476,
"text": "We will be creating a simple application in which we will display multiple edit text fields in which we will be allowing users to enter the details for making a payment. After clicking on make payment button we will display a dialog box to our users for making payment through different apps which are installed in users device. Below is the video in which we will get to see what we are going to build in this article. "
},
{
"code": null,
"e": 926,
"s": 897,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 1088,
"s": 926,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language."
},
{
"code": null,
"e": 1153,
"s": 1088,
"text": "Step 2: Adding a dependency for easy payment gateway in android "
},
{
"code": null,
"e": 1270,
"s": 1153,
"text": "Navigate to the app > Gradle Scripts > build.gradle(:app) and add the below dependency in the dependencies section. "
},
{
"code": null,
"e": 1323,
"s": 1270,
"text": "implementation ‘com.shreyaspatil:EasyUpiPayment:2.0’"
},
{
"code": null,
"e": 1433,
"s": 1323,
"text": "After adding this dependency now sync your project and now we will move towards adding internet permissions. "
},
{
"code": null,
"e": 1494,
"s": 1433,
"text": "Step 3: Adding internet permissions in AndroidManifest.xml. "
},
{
"code": null,
"e": 1563,
"s": 1494,
"text": "Navigate to app > AndroidManifest.xml and add the below code to it. "
},
{
"code": null,
"e": 1567,
"s": 1563,
"text": "XML"
},
{
"code": "<uses-permission android:name=\"android.permission.INTERNET\" />",
"e": 1630,
"s": 1567,
"text": null
},
{
"code": null,
"e": 1678,
"s": 1630,
"text": "Step 4: Working with the activity_main.xml file"
},
{
"code": null,
"e": 1821,
"s": 1678,
"text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. "
},
{
"code": null,
"e": 1825,
"s": 1821,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <!--edit text for entering amount to be paid--> <EditText android:id=\"@+id/idEdtAmount\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"8dp\" android:layout_marginTop=\"15dp\" android:layout_marginEnd=\"8dp\" android:hint=\"Enter Amount to be paid\" android:inputType=\"numberDecimal\" /> <!--edit text for entering the upi id to which we have to make payment--> <EditText android:id=\"@+id/idEdtUpi\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idEdtAmount\" android:layout_marginStart=\"8dp\" android:layout_marginTop=\"15dp\" android:layout_marginEnd=\"8dp\" android:hint=\"Enter your UPI Id\" android:inputType=\"text\" /> <!--edit text for adding the name of the user whom we have to make payment--> <EditText android:id=\"@+id/idEdtName\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idEdtUpi\" android:layout_marginStart=\"8dp\" android:layout_marginTop=\"15dp\" android:layout_marginEnd=\"8dp\" android:hint=\"Enter your Name\" android:inputType=\"text\" /> <!--edit text for adding the description for the payment which we are making--> <EditText android:id=\"@+id/idEdtDescription\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idEdtName\" android:layout_marginStart=\"8dp\" android:layout_marginTop=\"15dp\" android:layout_marginEnd=\"8dp\" android:hint=\"Enter Payment Description\" android:inputType=\"text\" /> <!--button for making a payment--> <Button android:id=\"@+id/idBtnMakePayment\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idEdtDescription\" android:layout_margin=\"12dp\" android:text=\"Make Payment\" android:textAllCaps=\"false\" /> <!--text view for displaying transaction status--> <TextView android:id=\"@+id/idTVTransactionDetails\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idBtnMakePayment\" android:layout_marginTop=\"30dp\" android:text=\"Transaction Details\" android:textAlignment=\"center\" android:textColor=\"@color/purple_700\" android:visibility=\"gone\" /> </RelativeLayout>",
"e": 4743,
"s": 1825,
"text": null
},
{
"code": null,
"e": 4791,
"s": 4743,
"text": "Step 5: Working with the MainActivity.java file"
},
{
"code": null,
"e": 4981,
"s": 4791,
"text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 4986,
"s": 4981,
"text": "Java"
},
{
"code": "import android.os.Bundle;import android.text.TextUtils;import android.util.Log;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.shreyaspatil.EasyUpiPayment.EasyUpiPayment;import com.shreyaspatil.EasyUpiPayment.listener.PaymentStatusListener;import com.shreyaspatil.EasyUpiPayment.model.TransactionDetails; import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date;import java.util.Locale; public class MainActivity extends AppCompatActivity implements PaymentStatusListener { // initializing variables for our edit text and button. private EditText amountEdt, upiEdt, nameEdt, descEdt; private TextView transactionDetailsTV; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing all our variables. amountEdt = findViewById(R.id.idEdtAmount); upiEdt = findViewById(R.id.idEdtUpi); nameEdt = findViewById(R.id.idEdtName); descEdt = findViewById(R.id.idEdtDescription); Button makePaymentBtn = findViewById(R.id.idBtnMakePayment); transactionDetailsTV = findViewById(R.id.idTVTransactionDetails); // on below line we are getting date and then we are setting this date as transaction id. Date c = Calendar.getInstance().getTime(); SimpleDateFormat df = new SimpleDateFormat(\"ddMMyyyyHHmmss\", Locale.getDefault()); String transcId = df.format(c); // on below line we are adding click listener for our payment button. makePaymentBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // on below line we are getting data from our edit text. String amount = amountEdt.getText().toString(); String upi = upiEdt.getText().toString(); String name = nameEdt.getText().toString(); String desc = descEdt.getText().toString(); // on below line we are validating our text field. if (TextUtils.isEmpty(amount) && TextUtils.isEmpty(upi) && TextUtils.isEmpty(name) && TextUtils.isEmpty(desc)) { Toast.makeText(MainActivity.this, \"Please enter all the details..\", Toast.LENGTH_SHORT).show(); } else { // if the edit text is not empty then // we are calling method to make payment. makePayment(amount, upi, name, desc, transcId); } } }); } private void makePayment(String amount, String upi, String name, String desc, String transactionId) { // on below line we are calling an easy payment method and passing // all parameters to it such as upi id,name, description and others. final EasyUpiPayment easyUpiPayment = new EasyUpiPayment.Builder() .with(this) // on below line we are adding upi id. .setPayeeVpa(upi) // on below line we are setting name to which we are making oayment. .setPayeeName(name) // on below line we are passing transaction id. .setTransactionId(transactionId) // on below line we are passing transaction ref id. .setTransactionRefId(transactionId) // on below line we are adding description to payment. .setDescription(desc) // on below line we are passing amount which is being paid. .setAmount(amount) // on below line we are calling a build method to build this ui. .build(); // on below line we are calling a start // payment method to start a payment. easyUpiPayment.startPayment(); // on below line we are calling a set payment // status listener method to call other payment methods. easyUpiPayment.setPaymentStatusListener(this); } @Override public void onTransactionCompleted(TransactionDetails transactionDetails) { // on below line we are getting details about transaction when completed. String transcDetails = transactionDetails.getStatus().toString() + \"\\n\" + \"Transaction ID : \" + transactionDetails.getTransactionId(); transactionDetailsTV.setVisibility(View.VISIBLE); // on below line we are setting details to our text view. transactionDetailsTV.setText(transcDetails); } @Override public void onTransactionSuccess() { // this method is called when transaction is successful and we are displaying a toast message. Toast.makeText(this, \"Transaction successfully completed..\", Toast.LENGTH_SHORT).show(); } @Override public void onTransactionSubmitted() { // this method is called when transaction is done // but it may be successful or failure. Log.e(\"TAG\", \"TRANSACTION SUBMIT\"); } @Override public void onTransactionFailed() { // this method is called when transaction is failure. Toast.makeText(this, \"Failed to complete transaction\", Toast.LENGTH_SHORT).show(); } @Override public void onTransactionCancelled() { // this method is called when transaction is cancelled. Toast.makeText(this, \"Transaction cancelled..\", Toast.LENGTH_SHORT).show(); } @Override public void onAppNotFound() { // this method is called when the users device is not having any app installed for making payment. Toast.makeText(this, \"No app found for making transaction..\", Toast.LENGTH_SHORT).show(); }}",
"e": 10801,
"s": 4986,
"text": null
},
{
"code": null,
"e": 10850,
"s": 10801,
"text": "Now run your app and see the output of the app. "
},
{
"code": null,
"e": 10983,
"s": 10850,
"text": "Note: Make sure to run your app on a real device and you should be having an app for making payments. And put the amount in decimal."
},
{
"code": null,
"e": 10991,
"s": 10983,
"text": "Output:"
},
{
"code": null,
"e": 11009,
"s": 10991,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 11017,
"s": 11009,
"text": "Android"
},
{
"code": null,
"e": 11022,
"s": 11017,
"text": "Java"
},
{
"code": null,
"e": 11027,
"s": 11022,
"text": "Java"
},
{
"code": null,
"e": 11035,
"s": 11027,
"text": "Android"
}
] |
SVG stroke-dasharray Attribute
|
31 Mar, 2022
The stroke-dasharray attribute is a presentation attribute defining the pattern of dashes used to paint the outline of the shape.
Syntax:
stroke-dasharray="number pattern"
Attribute Values:
dasharray: The pattern stroke that will have.
We will use the stoke-dasharray attribute for setting the pattern of the stroke.
Example 1: In this example we will use the stroke-dasharray attribute for setting the pattern of line.
<!DOCTYPE html> <html> <body> <svg viewBox="0 0 50 20" xmlns="http://www.w3.org/2000/svg"> <line x1="0" y1="1" x2="30" y2="1" stroke="green" /> <line x1="0" y1="3" x2="30" y2="3" stroke="green" stroke-dasharray="4 1 2 3" /> </svg></body> </html>
Output:
Example 2: In this example we will use the stroke-dasharray attribute for setting the pattern of circle
<!DOCTYPE html> <html> <body> <svg viewBox="0 0 50 21" xmlns="http://www.w3.org/2000/svg"> <circle x="12" y="3" r="5" cx="10" cy="10" stroke="green"/> <circle x="12" y="3" r="5" cx="25" cy="10" stroke="green" stroke-dasharray="4 1 2 3" /> </svg></body> </html>
Output:
HTML-SVG
SVG-Attribute
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
REST API (Introduction)
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet)
HTTP headers | Content-Type
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 Mar, 2022"
},
{
"code": null,
"e": 158,
"s": 28,
"text": "The stroke-dasharray attribute is a presentation attribute defining the pattern of dashes used to paint the outline of the shape."
},
{
"code": null,
"e": 166,
"s": 158,
"text": "Syntax:"
},
{
"code": null,
"e": 200,
"s": 166,
"text": "stroke-dasharray=\"number pattern\""
},
{
"code": null,
"e": 218,
"s": 200,
"text": "Attribute Values:"
},
{
"code": null,
"e": 264,
"s": 218,
"text": "dasharray: The pattern stroke that will have."
},
{
"code": null,
"e": 345,
"s": 264,
"text": "We will use the stoke-dasharray attribute for setting the pattern of the stroke."
},
{
"code": null,
"e": 448,
"s": 345,
"text": "Example 1: In this example we will use the stroke-dasharray attribute for setting the pattern of line."
},
{
"code": "<!DOCTYPE html> <html> <body> <svg viewBox=\"0 0 50 20\" xmlns=\"http://www.w3.org/2000/svg\"> <line x1=\"0\" y1=\"1\" x2=\"30\" y2=\"1\" stroke=\"green\" /> <line x1=\"0\" y1=\"3\" x2=\"30\" y2=\"3\" stroke=\"green\" stroke-dasharray=\"4 1 2 3\" /> </svg></body> </html>",
"e": 739,
"s": 448,
"text": null
},
{
"code": null,
"e": 747,
"s": 739,
"text": "Output:"
},
{
"code": null,
"e": 851,
"s": 747,
"text": "Example 2: In this example we will use the stroke-dasharray attribute for setting the pattern of circle"
},
{
"code": "<!DOCTYPE html> <html> <body> <svg viewBox=\"0 0 50 21\" xmlns=\"http://www.w3.org/2000/svg\"> <circle x=\"12\" y=\"3\" r=\"5\" cx=\"10\" cy=\"10\" stroke=\"green\"/> <circle x=\"12\" y=\"3\" r=\"5\" cx=\"25\" cy=\"10\" stroke=\"green\" stroke-dasharray=\"4 1 2 3\" /> </svg></body> </html>",
"e": 1189,
"s": 851,
"text": null
},
{
"code": null,
"e": 1197,
"s": 1189,
"text": "Output:"
},
{
"code": null,
"e": 1206,
"s": 1197,
"text": "HTML-SVG"
},
{
"code": null,
"e": 1220,
"s": 1206,
"text": "SVG-Attribute"
},
{
"code": null,
"e": 1225,
"s": 1220,
"text": "HTML"
},
{
"code": null,
"e": 1242,
"s": 1225,
"text": "Web Technologies"
},
{
"code": null,
"e": 1247,
"s": 1242,
"text": "HTML"
},
{
"code": null,
"e": 1345,
"s": 1247,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1393,
"s": 1345,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 1417,
"s": 1393,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 1467,
"s": 1417,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 1504,
"s": 1467,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 1532,
"s": 1504,
"text": "HTTP headers | Content-Type"
},
{
"code": null,
"e": 1565,
"s": 1532,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 1626,
"s": 1565,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1669,
"s": 1626,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 1741,
"s": 1669,
"text": "Differences between Functional Components and Class Components in React"
}
] |
deleteLater() method in PyQt5
|
26 Mar, 2020
While designing an application it could potentially consume a lot of space/memory if care is not taken when closing widgets. The QObject-based classes are designed to be (optionally) linked together in a hierarchy. When a top-level object is deleted, Qt will automatically delete all its child objects as well. However, when closing widgets, automatic deletion will only happen if the Qt.WA_DeleteOnClose attribute is set (which, by default, it usually isn’t).
In PyQt5, there are two aspects to object ownership: the Python part, and the Qt part. Often, removing the last Python reference to an object won’t be enough to fully clean up, because there could still be a reference held on the Qt side. In general, Qt tends not to implicitly delete objects. So if your application creates and removes lots of Widgets, you may need to take steps to delete them explicitly if memory usage is a concern.
deleteLater() method allows us to explicitly delete the reference of the widget.
Syntax : widget.deleteLater()
Argument : It takes no argument.
Action performed : It deletes/remove the reference of the widget from the memory.
Code :
# importing the required libraries from PyQt5.QtWidgets import * from PyQt5 import QtCorefrom PyQt5 import QtGuiimport sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle("Memory") # setting the geometry of window self.setGeometry(0, 0, 400, 300) # creating a label widget self.label_1 = QLabel("Label", self) # moving position self.label_1.move(100, 100) # setting up border self.label_1.setStyleSheet("border: 1px solid black;") # delete reference self.label_1.deleteLater() # show all the widgets self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
It will delete the reference associated with the label widget from memory.Output :
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Mar, 2020"
},
{
"code": null,
"e": 489,
"s": 28,
"text": "While designing an application it could potentially consume a lot of space/memory if care is not taken when closing widgets. The QObject-based classes are designed to be (optionally) linked together in a hierarchy. When a top-level object is deleted, Qt will automatically delete all its child objects as well. However, when closing widgets, automatic deletion will only happen if the Qt.WA_DeleteOnClose attribute is set (which, by default, it usually isn’t)."
},
{
"code": null,
"e": 926,
"s": 489,
"text": "In PyQt5, there are two aspects to object ownership: the Python part, and the Qt part. Often, removing the last Python reference to an object won’t be enough to fully clean up, because there could still be a reference held on the Qt side. In general, Qt tends not to implicitly delete objects. So if your application creates and removes lots of Widgets, you may need to take steps to delete them explicitly if memory usage is a concern."
},
{
"code": null,
"e": 1007,
"s": 926,
"text": "deleteLater() method allows us to explicitly delete the reference of the widget."
},
{
"code": null,
"e": 1037,
"s": 1007,
"text": "Syntax : widget.deleteLater()"
},
{
"code": null,
"e": 1070,
"s": 1037,
"text": "Argument : It takes no argument."
},
{
"code": null,
"e": 1152,
"s": 1070,
"text": "Action performed : It deletes/remove the reference of the widget from the memory."
},
{
"code": null,
"e": 1159,
"s": 1152,
"text": "Code :"
},
{
"code": "# importing the required libraries from PyQt5.QtWidgets import * from PyQt5 import QtCorefrom PyQt5 import QtGuiimport sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle(\"Memory\") # setting the geometry of window self.setGeometry(0, 0, 400, 300) # creating a label widget self.label_1 = QLabel(\"Label\", self) # moving position self.label_1.move(100, 100) # setting up border self.label_1.setStyleSheet(\"border: 1px solid black;\") # delete reference self.label_1.deleteLater() # show all the widgets self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 1997,
"s": 1159,
"text": null
},
{
"code": null,
"e": 2080,
"s": 1997,
"text": "It will delete the reference associated with the label widget from memory.Output :"
},
{
"code": null,
"e": 2091,
"s": 2080,
"text": "Python-gui"
},
{
"code": null,
"e": 2103,
"s": 2091,
"text": "Python-PyQt"
},
{
"code": null,
"e": 2110,
"s": 2103,
"text": "Python"
}
] |
Graph Plotting in Python | Set 3
|
09 Feb, 2018
Graph Plotting in Python | Set 1Graph Plotting in Python | Set 2
Matplotlib is a pretty extensive library which supports Animations of graphs as well. The animation tools center around the matplotlib.animation base class, which provides a framework around which the animation functionality is built. The main interfaces are TimedAnimation and FuncAnimation and out of the two, FuncAnimation is the most convenient one to use.
Installation:
Matplotlib: Refer to Graph Plotting in Python | Set 1
Numpy: You can install numpy module using following pip command:pip install numpy
pip install numpy
FFMPEG: It is required only for saving the animation as a video. The executable can be downloaded from here.
Implementation:
# importing required modulesimport matplotlib.pyplot as pltimport matplotlib.animation as animationimport numpy as np # create a figure, axis and plot elementfig = plt.figure()ax = plt.axes(xlim=(-50, 50), ylim=(-50, 50))line, = ax.plot([], [], lw=2) # initialization functiondef init(): # creating an empty plot/frame line.set_data([], []) return line, # lists to store x and y axis pointsxdata, ydata = [], [] # animation functiondef animate(i): # t is a parameter t = 0.1*i # x, y values to be plotted x = t*np.sin(t) y = t*np.cos(t) # appending new points to x, y axes points list xdata.append(x) ydata.append(y) # set/update the x and y axes data line.set_data(xdata, ydata) # return line object return line, # setting a title for the plotplt.title('A growing coil!')# hiding the axis detailsplt.axis('off') # call the animator anim = animation.FuncAnimation(fig, animate, init_func=init, frames=500, interval=20, blit=True) # save the animation as mp4 video fileanim.save('animated_coil.mp4', writer = 'ffmpeg', fps = 30) # show the plotplt.show()
Here is how the output animation looks like:basic animation - YouTubeIndian Pythonista27.9K subscribersbasic animationWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 0:17•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=4-Tzxj3EIIQ" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Now, let us try to understand the code in pieces:
fig = plt.figure()
ax = plt.axes(xlim=(-50, 50), ylim=(-50, 50))
line, = ax.plot([], [], lw=2)Here, we first create a figure, i.e a top level container for all our subplots.Then we create an axes element ax which acts as a subplot. The range/limit for x and y axis are also defined while creating the axes element.Finally, we create the plot element, named as line . Initially, the x and y axis points have been defined as empty lists and line-width (lw) has been set as 2.
fig = plt.figure()
ax = plt.axes(xlim=(-50, 50), ylim=(-50, 50))
line, = ax.plot([], [], lw=2)
Here, we first create a figure, i.e a top level container for all our subplots.Then we create an axes element ax which acts as a subplot. The range/limit for x and y axis are also defined while creating the axes element.Finally, we create the plot element, named as line . Initially, the x and y axis points have been defined as empty lists and line-width (lw) has been set as 2.
def init():
line.set_data([], [])
return line,Now, we declare a initialization function, init . This function is called by animator to create the first frame.
def init():
line.set_data([], [])
return line,
Now, we declare a initialization function, init . This function is called by animator to create the first frame.
def animate(i):
# t is a parameter
t = 0.1*i
# x, y values to be plotted
x = t*np.sin(t)
y = t*np.cos(t)
# appending new points to x, y axes points list
xdata.append(x)
ydata.append(y)
# set/update the x and y axes data
line.set_data(xdata, ydata)
# return line object
return line,This is the most important function of above program. animate() function is called again and again by the animator to create each frame. The number of times this function will be called is determined by number of frames, which is passed as frames argument to animator.animate() function takes the index of ith frame as argument.t = 0.1*iHere, we cleverly use the index of current frame as a parameter!x = t*np.sin(t)
y = t*np.cos(t)Now, since we have the parameter t, we can easily plot any parametric equation. For example, here, we are plotting a spiral using its parametric equation.line.set_data(xdata, ydata)
return line,Finally, we use set_data() function to set x and y data and then return plot object, line .
def animate(i):
# t is a parameter
t = 0.1*i
# x, y values to be plotted
x = t*np.sin(t)
y = t*np.cos(t)
# appending new points to x, y axes points list
xdata.append(x)
ydata.append(y)
# set/update the x and y axes data
line.set_data(xdata, ydata)
# return line object
return line,
This is the most important function of above program. animate() function is called again and again by the animator to create each frame. The number of times this function will be called is determined by number of frames, which is passed as frames argument to animator.animate() function takes the index of ith frame as argument.
t = 0.1*i
Here, we cleverly use the index of current frame as a parameter!
x = t*np.sin(t)
y = t*np.cos(t)
Now, since we have the parameter t, we can easily plot any parametric equation. For example, here, we are plotting a spiral using its parametric equation.
line.set_data(xdata, ydata)
return line,
Finally, we use set_data() function to set x and y data and then return plot object, line .
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=500, interval=20, blit=True)Now, we create the FuncAnimation object, anim . It takes various arguments explained below:fig : figure to be plotted.animate : the function to be called repeatedly for each frame.init_func : function used to draw a clear frame. It is called once before the first frame.frames : number of frames. (Note: frames can also be an iterable or generator.)interval : duration between frames ( in milliseconds)blit : setting blit=True means that only those parts will be drawn, which have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=500, interval=20, blit=True)
Now, we create the FuncAnimation object, anim . It takes various arguments explained below:fig : figure to be plotted.animate : the function to be called repeatedly for each frame.init_func : function used to draw a clear frame. It is called once before the first frame.frames : number of frames. (Note: frames can also be an iterable or generator.)interval : duration between frames ( in milliseconds)blit : setting blit=True means that only those parts will be drawn, which have changed.
anim.save('animated_coil.mp4', writer = 'ffmpeg', fps = 30)Now, we save the animator object as a video file using save() function. You will need a movie writer for saving the animation video. In this example, we have used FFMPEG movie writer. So, writer is set as ‘ffmpeg’.fps stands for frame per second.
anim.save('animated_coil.mp4', writer = 'ffmpeg', fps = 30)
Now, we save the animator object as a video file using save() function. You will need a movie writer for saving the animation video. In this example, we have used FFMPEG movie writer. So, writer is set as ‘ffmpeg’.fps stands for frame per second.
Example 2
This example shows how one can make a rotating curve by applying some simple mathematics!
# importing required modulesimport matplotlib.pyplot as pltimport matplotlib.animation as animationimport numpy as np # create a figure, axis and plot elementfig = plt.figure()ax = plt.axes(xlim=(-25, 25), ylim=(-25, 25))line, = ax.plot([], [], lw=2) # initialization functiondef init(): # creating an empty plot/frame line.set_data([], []) return line, # set of points for a star (could be any curve)p = np.arange(0, 4*np.pi, 0.1)x = 12*np.cos(p) + 8*np.cos(1.5*p)y = 12*np.sin(p) - 8*np.sin(1.5*p) # animation functiondef animate(i): # t is a parameter t = 0.1*i # x, y values to be plotted X = x*np.cos(t) - y*np.sin(t) Y = y*np.cos(t) + x*np.sin(t) # set/update the x and y axes data line.set_data(X, Y) # return line object return line, # setting a title for the plotplt.title('A rotating star!')# hiding the axis detailsplt.axis('off') # call the animator anim = animation.FuncAnimation(fig, animate, init_func=init, frames=100, interval=100, blit=True) # save the animation as mp4 video fileanim.save('basic_animation.mp4', writer = 'ffmpeg', fps = 10) # show the plotplt.show()
Here is how the output of above program looks like:basic animation - YouTubeIndian Pythonista28K subscribersbasic animationWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 0:10•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=IuwWUvBkKzQ" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Here, we have used some simple mathematics to rotate a given curve.
The star shape is obtained by putting k = 2.5 and 0<t<4*pi in the parametric equation given below:The same has been applied here:p = np.arange(0, 4*np.pi, 0.1)
x = 12*np.cos(p) + 8*np.cos(1.5*p)
y = 12*np.sin(p) - 8*np.sin(1.5*p)
The same has been applied here:
p = np.arange(0, 4*np.pi, 0.1)
x = 12*np.cos(p) + 8*np.cos(1.5*p)
y = 12*np.sin(p) - 8*np.sin(1.5*p)
Now, in each frame, we rotate the star curve using concept of rotation in complex numbers. Let x, y be two ordinates. Then after rotation by angle theta, the new ordinates are:The same has been applied here:X = x*np.cos(t) - y*np.sin(t)
Y = y*np.cos(t) + x*np.sin(t)
The same has been applied here:
X = x*np.cos(t) - y*np.sin(t)
Y = y*np.cos(t) + x*np.sin(t)
All in all, animations are a great tool to create amazing stuff and many more things can be created using them.
So, this was how animated plots can be generated and saved using Matplotlib.
This article is contributed by Nikhil Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Python
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, 2018"
},
{
"code": null,
"e": 118,
"s": 53,
"text": "Graph Plotting in Python | Set 1Graph Plotting in Python | Set 2"
},
{
"code": null,
"e": 479,
"s": 118,
"text": "Matplotlib is a pretty extensive library which supports Animations of graphs as well. The animation tools center around the matplotlib.animation base class, which provides a framework around which the animation functionality is built. The main interfaces are TimedAnimation and FuncAnimation and out of the two, FuncAnimation is the most convenient one to use."
},
{
"code": null,
"e": 493,
"s": 479,
"text": "Installation:"
},
{
"code": null,
"e": 547,
"s": 493,
"text": "Matplotlib: Refer to Graph Plotting in Python | Set 1"
},
{
"code": null,
"e": 629,
"s": 547,
"text": "Numpy: You can install numpy module using following pip command:pip install numpy"
},
{
"code": null,
"e": 647,
"s": 629,
"text": "pip install numpy"
},
{
"code": null,
"e": 756,
"s": 647,
"text": "FFMPEG: It is required only for saving the animation as a video. The executable can be downloaded from here."
},
{
"code": null,
"e": 772,
"s": 756,
"text": "Implementation:"
},
{
"code": "# importing required modulesimport matplotlib.pyplot as pltimport matplotlib.animation as animationimport numpy as np # create a figure, axis and plot elementfig = plt.figure()ax = plt.axes(xlim=(-50, 50), ylim=(-50, 50))line, = ax.plot([], [], lw=2) # initialization functiondef init(): # creating an empty plot/frame line.set_data([], []) return line, # lists to store x and y axis pointsxdata, ydata = [], [] # animation functiondef animate(i): # t is a parameter t = 0.1*i # x, y values to be plotted x = t*np.sin(t) y = t*np.cos(t) # appending new points to x, y axes points list xdata.append(x) ydata.append(y) # set/update the x and y axes data line.set_data(xdata, ydata) # return line object return line, # setting a title for the plotplt.title('A growing coil!')# hiding the axis detailsplt.axis('off') # call the animator anim = animation.FuncAnimation(fig, animate, init_func=init, frames=500, interval=20, blit=True) # save the animation as mp4 video fileanim.save('animated_coil.mp4', writer = 'ffmpeg', fps = 30) # show the plotplt.show()",
"e": 1940,
"s": 772,
"text": null
},
{
"code": null,
"e": 2854,
"s": 1940,
"text": "Here is how the output animation looks like:basic animation - YouTubeIndian Pythonista27.9K subscribersbasic animationWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 0:17•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=4-Tzxj3EIIQ\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Now, let us try to understand the code in pieces:"
},
{
"code": null,
"e": 3328,
"s": 2854,
"text": "fig = plt.figure()\nax = plt.axes(xlim=(-50, 50), ylim=(-50, 50))\nline, = ax.plot([], [], lw=2)Here, we first create a figure, i.e a top level container for all our subplots.Then we create an axes element ax which acts as a subplot. The range/limit for x and y axis are also defined while creating the axes element.Finally, we create the plot element, named as line . Initially, the x and y axis points have been defined as empty lists and line-width (lw) has been set as 2."
},
{
"code": null,
"e": 3423,
"s": 3328,
"text": "fig = plt.figure()\nax = plt.axes(xlim=(-50, 50), ylim=(-50, 50))\nline, = ax.plot([], [], lw=2)"
},
{
"code": null,
"e": 3803,
"s": 3423,
"text": "Here, we first create a figure, i.e a top level container for all our subplots.Then we create an axes element ax which acts as a subplot. The range/limit for x and y axis are also defined while creating the axes element.Finally, we create the plot element, named as line . Initially, the x and y axis points have been defined as empty lists and line-width (lw) has been set as 2."
},
{
"code": null,
"e": 3970,
"s": 3803,
"text": "def init():\n line.set_data([], [])\n return line,Now, we declare a initialization function, init . This function is called by animator to create the first frame."
},
{
"code": null,
"e": 4025,
"s": 3970,
"text": "def init():\n line.set_data([], [])\n return line,"
},
{
"code": null,
"e": 4138,
"s": 4025,
"text": "Now, we declare a initialization function, init . This function is called by animator to create the first frame."
},
{
"code": null,
"e": 5205,
"s": 4138,
"text": "def animate(i):\n # t is a parameter\n t = 0.1*i\n \n # x, y values to be plotted\n x = t*np.sin(t)\n y = t*np.cos(t)\n \n # appending new points to x, y axes points list\n xdata.append(x)\n ydata.append(y)\n \n # set/update the x and y axes data\n line.set_data(xdata, ydata)\n \n # return line object\n return line,This is the most important function of above program. animate() function is called again and again by the animator to create each frame. The number of times this function will be called is determined by number of frames, which is passed as frames argument to animator.animate() function takes the index of ith frame as argument.t = 0.1*iHere, we cleverly use the index of current frame as a parameter!x = t*np.sin(t)\ny = t*np.cos(t)Now, since we have the parameter t, we can easily plot any parametric equation. For example, here, we are plotting a spiral using its parametric equation.line.set_data(xdata, ydata)\nreturn line,Finally, we use set_data() function to set x and y data and then return plot object, line ."
},
{
"code": null,
"e": 5555,
"s": 5205,
"text": "def animate(i):\n # t is a parameter\n t = 0.1*i\n \n # x, y values to be plotted\n x = t*np.sin(t)\n y = t*np.cos(t)\n \n # appending new points to x, y axes points list\n xdata.append(x)\n ydata.append(y)\n \n # set/update the x and y axes data\n line.set_data(xdata, ydata)\n \n # return line object\n return line,"
},
{
"code": null,
"e": 5884,
"s": 5555,
"text": "This is the most important function of above program. animate() function is called again and again by the animator to create each frame. The number of times this function will be called is determined by number of frames, which is passed as frames argument to animator.animate() function takes the index of ith frame as argument."
},
{
"code": null,
"e": 5894,
"s": 5884,
"text": "t = 0.1*i"
},
{
"code": null,
"e": 5959,
"s": 5894,
"text": "Here, we cleverly use the index of current frame as a parameter!"
},
{
"code": null,
"e": 5991,
"s": 5959,
"text": "x = t*np.sin(t)\ny = t*np.cos(t)"
},
{
"code": null,
"e": 6146,
"s": 5991,
"text": "Now, since we have the parameter t, we can easily plot any parametric equation. For example, here, we are plotting a spiral using its parametric equation."
},
{
"code": null,
"e": 6187,
"s": 6146,
"text": "line.set_data(xdata, ydata)\nreturn line,"
},
{
"code": null,
"e": 6279,
"s": 6187,
"text": "Finally, we use set_data() function to set x and y data and then return plot object, line ."
},
{
"code": null,
"e": 6896,
"s": 6279,
"text": "anim = animation.FuncAnimation(fig, animate, init_func=init,\n frames=500, interval=20, blit=True)Now, we create the FuncAnimation object, anim . It takes various arguments explained below:fig : figure to be plotted.animate : the function to be called repeatedly for each frame.init_func : function used to draw a clear frame. It is called once before the first frame.frames : number of frames. (Note: frames can also be an iterable or generator.)interval : duration between frames ( in milliseconds)blit : setting blit=True means that only those parts will be drawn, which have changed."
},
{
"code": null,
"e": 7024,
"s": 6896,
"text": "anim = animation.FuncAnimation(fig, animate, init_func=init,\n frames=500, interval=20, blit=True)"
},
{
"code": null,
"e": 7514,
"s": 7024,
"text": "Now, we create the FuncAnimation object, anim . It takes various arguments explained below:fig : figure to be plotted.animate : the function to be called repeatedly for each frame.init_func : function used to draw a clear frame. It is called once before the first frame.frames : number of frames. (Note: frames can also be an iterable or generator.)interval : duration between frames ( in milliseconds)blit : setting blit=True means that only those parts will be drawn, which have changed."
},
{
"code": null,
"e": 7820,
"s": 7514,
"text": "anim.save('animated_coil.mp4', writer = 'ffmpeg', fps = 30)Now, we save the animator object as a video file using save() function. You will need a movie writer for saving the animation video. In this example, we have used FFMPEG movie writer. So, writer is set as ‘ffmpeg’.fps stands for frame per second."
},
{
"code": null,
"e": 7880,
"s": 7820,
"text": "anim.save('animated_coil.mp4', writer = 'ffmpeg', fps = 30)"
},
{
"code": null,
"e": 8127,
"s": 7880,
"text": "Now, we save the animator object as a video file using save() function. You will need a movie writer for saving the animation video. In this example, we have used FFMPEG movie writer. So, writer is set as ‘ffmpeg’.fps stands for frame per second."
},
{
"code": null,
"e": 8137,
"s": 8127,
"text": "Example 2"
},
{
"code": null,
"e": 8227,
"s": 8137,
"text": "This example shows how one can make a rotating curve by applying some simple mathematics!"
},
{
"code": "# importing required modulesimport matplotlib.pyplot as pltimport matplotlib.animation as animationimport numpy as np # create a figure, axis and plot elementfig = plt.figure()ax = plt.axes(xlim=(-25, 25), ylim=(-25, 25))line, = ax.plot([], [], lw=2) # initialization functiondef init(): # creating an empty plot/frame line.set_data([], []) return line, # set of points for a star (could be any curve)p = np.arange(0, 4*np.pi, 0.1)x = 12*np.cos(p) + 8*np.cos(1.5*p)y = 12*np.sin(p) - 8*np.sin(1.5*p) # animation functiondef animate(i): # t is a parameter t = 0.1*i # x, y values to be plotted X = x*np.cos(t) - y*np.sin(t) Y = y*np.cos(t) + x*np.sin(t) # set/update the x and y axes data line.set_data(X, Y) # return line object return line, # setting a title for the plotplt.title('A rotating star!')# hiding the axis detailsplt.axis('off') # call the animator anim = animation.FuncAnimation(fig, animate, init_func=init, frames=100, interval=100, blit=True) # save the animation as mp4 video fileanim.save('basic_animation.mp4', writer = 'ffmpeg', fps = 10) # show the plotplt.show()",
"e": 9412,
"s": 8227,
"text": null
},
{
"code": null,
"e": 10349,
"s": 9412,
"text": "Here is how the output of above program looks like:basic animation - YouTubeIndian Pythonista28K subscribersbasic animationWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 0:10•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=IuwWUvBkKzQ\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Here, we have used some simple mathematics to rotate a given curve."
},
{
"code": null,
"e": 10579,
"s": 10349,
"text": "The star shape is obtained by putting k = 2.5 and 0<t<4*pi in the parametric equation given below:The same has been applied here:p = np.arange(0, 4*np.pi, 0.1)\nx = 12*np.cos(p) + 8*np.cos(1.5*p)\ny = 12*np.sin(p) - 8*np.sin(1.5*p)"
},
{
"code": null,
"e": 10611,
"s": 10579,
"text": "The same has been applied here:"
},
{
"code": null,
"e": 10712,
"s": 10611,
"text": "p = np.arange(0, 4*np.pi, 0.1)\nx = 12*np.cos(p) + 8*np.cos(1.5*p)\ny = 12*np.sin(p) - 8*np.sin(1.5*p)"
},
{
"code": null,
"e": 10979,
"s": 10712,
"text": "Now, in each frame, we rotate the star curve using concept of rotation in complex numbers. Let x, y be two ordinates. Then after rotation by angle theta, the new ordinates are:The same has been applied here:X = x*np.cos(t) - y*np.sin(t)\nY = y*np.cos(t) + x*np.sin(t)"
},
{
"code": null,
"e": 11011,
"s": 10979,
"text": "The same has been applied here:"
},
{
"code": null,
"e": 11071,
"s": 11011,
"text": "X = x*np.cos(t) - y*np.sin(t)\nY = y*np.cos(t) + x*np.sin(t)"
},
{
"code": null,
"e": 11183,
"s": 11071,
"text": "All in all, animations are a great tool to create amazing stuff and many more things can be created using them."
},
{
"code": null,
"e": 11260,
"s": 11183,
"text": "So, this was how animated plots can be generated and saved using Matplotlib."
},
{
"code": null,
"e": 11560,
"s": 11260,
"text": "This article is contributed by Nikhil Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 11685,
"s": 11560,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 11692,
"s": 11685,
"text": "Python"
}
] |
maketrans() and translate() functions in Python
|
15 Oct, 2020
In the world of programming, seldom there is a need to replace all the words/characters at once in the whole file python offers this functionality using functions translate() and its helper functions maketrans(). Both functions are discussed in this article.
maketrans() function is used to construct the transition table i.e specify the list of characters that need to be replaced in the whole string or the characters that need to be deleted from the string
Syntax : maketrans(str1, str2, str3)
Parameters :str1 : Specifies the list of characters that need to be replaced.str2 : Specifies the list of characters with which the characters need to be replaced.str3 : Specifies the list of characters that needs to be deleted.
Returns : Returns the translation table which specifies the conversions that can be used by translate()
To translate the characters in the string translate() is used to make the translations. This function uses the translation mapping specified using the maketrans().
Syntax : translate(table, delstr)
Parameters :table : Translate mapping specified to perform translations.delstr : The delete string can be specified as optional argument is not mentioned in table.
Returns : Returns the argument string after performing the translations using the translation table.
Code #1 : Code to translate using translate() and maketrans().
# Python3 code to demonstrate # translations using # maketrans() and translate() # specify to translate charsstr1 = "wy" # specify to replace withstr2 = "gf" # delete charsstr3 = "u" # target string trg = "weeksyourweeks" # using maketrans() to # construct translate# tabletable = trg.maketrans(str1, str2, str3) # Printing original string print ("The string before translating is : ", end ="")print (trg) # using translate() to make translations.print ("The string after translating is : ", end ="")print (trg.translate(table))
Output :
The string before translating is : weeksyourweeks
The string after translating is : geeksforgeeks
Translation can also be achieved by specifying the translation dictionary and passing as an object which acts as a mapping. In this case, there is no need for maketrans() to perform translations.
Code #2 : Code to translate without maketrans().
# Python3 code to demonstrate # translations without# maketrans() # specifying the mapping # using ASCII table = { 119 : 103, 121 : 102, 117 : None } # target string trg = "weeksyourweeks" # Printing original string print ("The string before translating is : ", end ="")print (trg) # using translate() to make translations.print ("The string after translating is : ", end ="")print (trg.translate(table))
Output :
The string before translating is : weeksyourweeks
The string after translating is : geeksforgeeks
Application :There are many are times where mistakes can occur while coding or developing, these functions provide an easy and quick way to replace and rectify them and would potentially save a lot of time.
Akanksha_Rai
nidhi_biet
python-string
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n15 Oct, 2020"
},
{
"code": null,
"e": 311,
"s": 52,
"text": "In the world of programming, seldom there is a need to replace all the words/characters at once in the whole file python offers this functionality using functions translate() and its helper functions maketrans(). Both functions are discussed in this article."
},
{
"code": null,
"e": 512,
"s": 311,
"text": "maketrans() function is used to construct the transition table i.e specify the list of characters that need to be replaced in the whole string or the characters that need to be deleted from the string"
},
{
"code": null,
"e": 549,
"s": 512,
"text": "Syntax : maketrans(str1, str2, str3)"
},
{
"code": null,
"e": 778,
"s": 549,
"text": "Parameters :str1 : Specifies the list of characters that need to be replaced.str2 : Specifies the list of characters with which the characters need to be replaced.str3 : Specifies the list of characters that needs to be deleted."
},
{
"code": null,
"e": 882,
"s": 778,
"text": "Returns : Returns the translation table which specifies the conversions that can be used by translate()"
},
{
"code": null,
"e": 1046,
"s": 882,
"text": "To translate the characters in the string translate() is used to make the translations. This function uses the translation mapping specified using the maketrans()."
},
{
"code": null,
"e": 1080,
"s": 1046,
"text": "Syntax : translate(table, delstr)"
},
{
"code": null,
"e": 1244,
"s": 1080,
"text": "Parameters :table : Translate mapping specified to perform translations.delstr : The delete string can be specified as optional argument is not mentioned in table."
},
{
"code": null,
"e": 1345,
"s": 1244,
"text": "Returns : Returns the argument string after performing the translations using the translation table."
},
{
"code": null,
"e": 1409,
"s": 1345,
"text": " Code #1 : Code to translate using translate() and maketrans()."
},
{
"code": "# Python3 code to demonstrate # translations using # maketrans() and translate() # specify to translate charsstr1 = \"wy\" # specify to replace withstr2 = \"gf\" # delete charsstr3 = \"u\" # target string trg = \"weeksyourweeks\" # using maketrans() to # construct translate# tabletable = trg.maketrans(str1, str2, str3) # Printing original string print (\"The string before translating is : \", end =\"\")print (trg) # using translate() to make translations.print (\"The string after translating is : \", end =\"\")print (trg.translate(table))",
"e": 1945,
"s": 1409,
"text": null
},
{
"code": null,
"e": 1954,
"s": 1945,
"text": "Output :"
},
{
"code": null,
"e": 2053,
"s": 1954,
"text": "The string before translating is : weeksyourweeks\nThe string after translating is : geeksforgeeks\n"
},
{
"code": null,
"e": 2251,
"s": 2055,
"text": "Translation can also be achieved by specifying the translation dictionary and passing as an object which acts as a mapping. In this case, there is no need for maketrans() to perform translations."
},
{
"code": null,
"e": 2301,
"s": 2251,
"text": " Code #2 : Code to translate without maketrans()."
},
{
"code": "# Python3 code to demonstrate # translations without# maketrans() # specifying the mapping # using ASCII table = { 119 : 103, 121 : 102, 117 : None } # target string trg = \"weeksyourweeks\" # Printing original string print (\"The string before translating is : \", end =\"\")print (trg) # using translate() to make translations.print (\"The string after translating is : \", end =\"\")print (trg.translate(table))",
"e": 2711,
"s": 2301,
"text": null
},
{
"code": null,
"e": 2720,
"s": 2711,
"text": "Output :"
},
{
"code": null,
"e": 2819,
"s": 2720,
"text": "The string before translating is : weeksyourweeks\nThe string after translating is : geeksforgeeks\n"
},
{
"code": null,
"e": 3028,
"s": 2821,
"text": "Application :There are many are times where mistakes can occur while coding or developing, these functions provide an easy and quick way to replace and rectify them and would potentially save a lot of time."
},
{
"code": null,
"e": 3041,
"s": 3028,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 3052,
"s": 3041,
"text": "nidhi_biet"
},
{
"code": null,
"e": 3066,
"s": 3052,
"text": "python-string"
},
{
"code": null,
"e": 3073,
"s": 3066,
"text": "Python"
}
] |
Namechk – Osint tool for Usernames
|
23 Aug, 2021
Namechk is an osint tool that is based on namechk.com and is used for checking usernames on more than 100 websites, forums, and social networks. What if there is a tool that can tell whether a username you want is available or not on multiple platforms or not. Yes, you read it right, Namechk can do this with ease and relieve you of the work going to individual platforms to check username is available or not.
Can be used to search available username.
Can be used to search available username on specifics websites.
Also can search available username in a list.
Can search usernames which are used on specific websites.
Easy to use and install.
User-friendly.
Step 1: First clone the tool from the GitHub repository. Then change the directory to Namechk.
git clone https://github.com/GONZOsint/Namechk.git
cd Namechk
ls
Step 2: Now give executable permission to namechk.sh.After giving executable permission, run the tool.
chmod+x namechk.sh
./namechk.sh
To see what options and arguments namechk provides, type the following command.
./namechk.sh -h
Let’s check whether the username “nkjasdjh” is available or not. For this, we will use -au flag.
./namechk.sh nkjasdjh -au
Use the -fu flag to see on which platform a username has been used.
./namechk.sh tally315 -fu
We can see that username tally315 is found on several websites like Facebook, Youtube, Twitter, Instagram, and many more.
Use -fu -co flags to check used usernames on specific websites.
./namechk.sh tally3 -fu -co followed by website name.
We can see that username tally is used on Facebook. Use -au -co flags to check whether a username is available on a specific website.
./namechk.sh havoc0635 -au -co followed by website name
We can see in the above image that the username havoc0635 isn’t available on Instagram. Use -l -fu flags to search usernames written in a text file whether they are used or not.
Create text file by,
touch user1.txt
Then use any editor like nano etc, to write in the text file and use the cat command followed by a filename to show the contents of the file.
nano user1.txt
cat user1.txt
We can see there are two usernames in the user1.txt file which are mark, tally3. Use the following command to see whether they have been used on any platforms or not.
./namechk.sh -l -fu followed by filename
We can see that the usernames mentioned in user1.txt are used on Facebook, Youtube, Twitter, blogger, etc.
In conclusion, namechk can prove to be a useful tool for not only osint investigators but also for normal people who wish to find out whether a username is available or not on multiple platforms instead of visiting individual platforms and typing in to see it’s available or not, Namechk removes all this stressful work and do the work for you.
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
Introduction to Linux Operating System
SED command in Linux | Set 2
nohup Command in Linux with Examples
mv command in Linux with examples
Array Basics in Shell Scripting | Set 1
chmod command in Linux with examples
Basic Operators in Shell Scripting
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Aug, 2021"
},
{
"code": null,
"e": 440,
"s": 28,
"text": "Namechk is an osint tool that is based on namechk.com and is used for checking usernames on more than 100 websites, forums, and social networks. What if there is a tool that can tell whether a username you want is available or not on multiple platforms or not. Yes, you read it right, Namechk can do this with ease and relieve you of the work going to individual platforms to check username is available or not."
},
{
"code": null,
"e": 482,
"s": 440,
"text": "Can be used to search available username."
},
{
"code": null,
"e": 546,
"s": 482,
"text": "Can be used to search available username on specifics websites."
},
{
"code": null,
"e": 592,
"s": 546,
"text": "Also can search available username in a list."
},
{
"code": null,
"e": 650,
"s": 592,
"text": "Can search usernames which are used on specific websites."
},
{
"code": null,
"e": 675,
"s": 650,
"text": "Easy to use and install."
},
{
"code": null,
"e": 690,
"s": 675,
"text": "User-friendly."
},
{
"code": null,
"e": 785,
"s": 690,
"text": "Step 1: First clone the tool from the GitHub repository. Then change the directory to Namechk."
},
{
"code": null,
"e": 850,
"s": 785,
"text": "git clone https://github.com/GONZOsint/Namechk.git\ncd Namechk\nls"
},
{
"code": null,
"e": 953,
"s": 850,
"text": "Step 2: Now give executable permission to namechk.sh.After giving executable permission, run the tool."
},
{
"code": null,
"e": 985,
"s": 953,
"text": "chmod+x namechk.sh\n./namechk.sh"
},
{
"code": null,
"e": 1065,
"s": 985,
"text": "To see what options and arguments namechk provides, type the following command."
},
{
"code": null,
"e": 1081,
"s": 1065,
"text": "./namechk.sh -h"
},
{
"code": null,
"e": 1178,
"s": 1081,
"text": "Let’s check whether the username “nkjasdjh” is available or not. For this, we will use -au flag."
},
{
"code": null,
"e": 1204,
"s": 1178,
"text": "./namechk.sh nkjasdjh -au"
},
{
"code": null,
"e": 1273,
"s": 1204,
"text": "Use the -fu flag to see on which platform a username has been used. "
},
{
"code": null,
"e": 1299,
"s": 1273,
"text": "./namechk.sh tally315 -fu"
},
{
"code": null,
"e": 1421,
"s": 1299,
"text": "We can see that username tally315 is found on several websites like Facebook, Youtube, Twitter, Instagram, and many more."
},
{
"code": null,
"e": 1485,
"s": 1421,
"text": "Use -fu -co flags to check used usernames on specific websites."
},
{
"code": null,
"e": 1539,
"s": 1485,
"text": "./namechk.sh tally3 -fu -co followed by website name."
},
{
"code": null,
"e": 1673,
"s": 1539,
"text": "We can see that username tally is used on Facebook. Use -au -co flags to check whether a username is available on a specific website."
},
{
"code": null,
"e": 1729,
"s": 1673,
"text": "./namechk.sh havoc0635 -au -co followed by website name"
},
{
"code": null,
"e": 1907,
"s": 1729,
"text": "We can see in the above image that the username havoc0635 isn’t available on Instagram. Use -l -fu flags to search usernames written in a text file whether they are used or not."
},
{
"code": null,
"e": 1928,
"s": 1907,
"text": "Create text file by,"
},
{
"code": null,
"e": 1944,
"s": 1928,
"text": "touch user1.txt"
},
{
"code": null,
"e": 2086,
"s": 1944,
"text": "Then use any editor like nano etc, to write in the text file and use the cat command followed by a filename to show the contents of the file."
},
{
"code": null,
"e": 2115,
"s": 2086,
"text": "nano user1.txt\ncat user1.txt"
},
{
"code": null,
"e": 2282,
"s": 2115,
"text": "We can see there are two usernames in the user1.txt file which are mark, tally3. Use the following command to see whether they have been used on any platforms or not."
},
{
"code": null,
"e": 2323,
"s": 2282,
"text": "./namechk.sh -l -fu followed by filename"
},
{
"code": null,
"e": 2430,
"s": 2323,
"text": "We can see that the usernames mentioned in user1.txt are used on Facebook, Youtube, Twitter, blogger, etc."
},
{
"code": null,
"e": 2775,
"s": 2430,
"text": "In conclusion, namechk can prove to be a useful tool for not only osint investigators but also for normal people who wish to find out whether a username is available or not on multiple platforms instead of visiting individual platforms and typing in to see it’s available or not, Namechk removes all this stressful work and do the work for you."
},
{
"code": null,
"e": 2786,
"s": 2775,
"text": "Kali-Linux"
},
{
"code": null,
"e": 2798,
"s": 2786,
"text": "Linux-Tools"
},
{
"code": null,
"e": 2809,
"s": 2798,
"text": "Linux-Unix"
},
{
"code": null,
"e": 2907,
"s": 2809,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2933,
"s": 2907,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 2968,
"s": 2933,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 3005,
"s": 2968,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 3044,
"s": 3005,
"text": "Introduction to Linux Operating System"
},
{
"code": null,
"e": 3073,
"s": 3044,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 3110,
"s": 3073,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 3144,
"s": 3110,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 3184,
"s": 3144,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 3221,
"s": 3184,
"text": "chmod command in Linux with examples"
}
] |
Random Forest Regression in Python
|
16 May, 2022
Every decision tree has high variance, but when we combine all of them together in parallel then the resultant variance is low as each decision tree gets perfectly trained on that particular sample data, and hence the output doesn’t depend on one decision tree but on multiple decision trees. In the case of a classification problem, the final output is taken by using the majority voting classifier. In the case of a regression problem, the final output is the mean of all the outputs. This part is called Aggregation.
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Random Forest is an ensemble technique capable of performing both regression and classification tasks with the use of multiple decision trees and a technique called Bootstrap and Aggregation, commonly known as bagging. The basic idea behind this is to combine multiple decision trees in determining the final output rather than relying on individual decision trees. Random Forest has multiple decision trees as base learning models. We randomly perform row sampling and feature sampling from the dataset forming sample datasets for every model. This part is called Bootstrap.
We need to approach the Random Forest regression technique like any other machine learning technique
Design a specific question or data and get the source to determine the required data.
Make sure the data is in an accessible format else convert it to the required format.
Specify all noticeable anomalies and missing data points that may be required to achieve the required data.
Create a machine learning model
Set the baseline model that you want to achieve
Train the data machine learning model.
Provide an insight into the model with test data
Now compare the performance metrics of both the test data and the predicted data from the model.
If it doesn’t satisfy your expectations, you can try improving your model accordingly or dating your data, or using another data modeling technique.
At this stage, you interpret the data you have gained and report accordingly.
You will be using a similar sample technique in the below example.
Below is a step-by-step sample implementation of Random Forest Regression.
Implementation:
Step 1: Import the required libraries.
python
# Importing the librariesimport numpy as npimport matplotlib.pyplot as pltimport pandas as pd
Step 2: Import and print the dataset
python
data = pd.read_csv('Salaries.csv')print(data)
Step 3: Select all rows and column 1 from dataset to x and all rows and column 2 as y
# the coding was not shown which is like that
x= df.iloc [:, : -1] # ” : ” means it will select all rows, “: -1 ” means that it will ignore last columny= df.iloc [:, -1 :] # ” : ” means it will select all rows, “-1 : ” means that it will ignore all columns except the last one
# the “iloc()” function enables us to select a particular cell of the dataset, that is, it helps us select a value that belongs to a particular row or column from a set of values of a data frame or dataset.
Step 4: Fit Random forest regressor to the dataset
python
# Fitting Random Forest Regression to the dataset# import the regressorfrom sklearn.ensemble import RandomForestRegressor # create regressor objectregressor = RandomForestRegressor(n_estimators = 100, random_state = 0) # fit the regressor with x and y dataregressor.fit(x, y)
Output:
Step 5: Predicting a new result
python
Y_pred = regressor.predict(np.array([6.5]).reshape(1, 1)) # test the output by changing values
Step 6: Visualising the result
python
# Visualising the Random Forest Regression results # arrange for creating a range of values# from min value of x to max# value of x with a difference of 0.01# between two consecutive valuesX_grid = np.arrange(min(x), max(x), 0.01) # reshape for reshaping the data into a len(X_grid)*1 array,# i.e. to make a column out of the X_grid value X_grid = X_grid.reshape((len(X_grid), 1)) # Scatter plot for original dataplt.scatter(x, y, color = 'blue') # plot predicted dataplt.plot(X_grid, regressor.predict(X_grid), color = 'green')plt.title('Random Forest Regression')plt.xlabel('Position level')plt.ylabel('Salary')plt.show()
Output:
deepaymt
devanshigupta1304
rkbhola5
abdulraheemshahzadbsse2018a
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n16 May, 2022"
},
{
"code": null,
"e": 575,
"s": 54,
"text": "Every decision tree has high variance, but when we combine all of them together in parallel then the resultant variance is low as each decision tree gets perfectly trained on that particular sample data, and hence the output doesn’t depend on one decision tree but on multiple decision trees. In the case of a classification problem, the final output is taken by using the majority voting classifier. In the case of a regression problem, the final output is the mean of all the outputs. This part is called Aggregation. "
},
{
"code": null,
"e": 584,
"s": 575,
"text": "Chapters"
},
{
"code": null,
"e": 611,
"s": 584,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 661,
"s": 611,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 684,
"s": 661,
"text": "captions off, selected"
},
{
"code": null,
"e": 692,
"s": 684,
"text": "English"
},
{
"code": null,
"e": 716,
"s": 692,
"text": "This is a modal window."
},
{
"code": null,
"e": 785,
"s": 716,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 807,
"s": 785,
"text": "End of dialog window."
},
{
"code": null,
"e": 1383,
"s": 807,
"text": "Random Forest is an ensemble technique capable of performing both regression and classification tasks with the use of multiple decision trees and a technique called Bootstrap and Aggregation, commonly known as bagging. The basic idea behind this is to combine multiple decision trees in determining the final output rather than relying on individual decision trees. Random Forest has multiple decision trees as base learning models. We randomly perform row sampling and feature sampling from the dataset forming sample datasets for every model. This part is called Bootstrap."
},
{
"code": null,
"e": 1485,
"s": 1383,
"text": "We need to approach the Random Forest regression technique like any other machine learning technique "
},
{
"code": null,
"e": 1571,
"s": 1485,
"text": "Design a specific question or data and get the source to determine the required data."
},
{
"code": null,
"e": 1657,
"s": 1571,
"text": "Make sure the data is in an accessible format else convert it to the required format."
},
{
"code": null,
"e": 1765,
"s": 1657,
"text": "Specify all noticeable anomalies and missing data points that may be required to achieve the required data."
},
{
"code": null,
"e": 1797,
"s": 1765,
"text": "Create a machine learning model"
},
{
"code": null,
"e": 1845,
"s": 1797,
"text": "Set the baseline model that you want to achieve"
},
{
"code": null,
"e": 1884,
"s": 1845,
"text": "Train the data machine learning model."
},
{
"code": null,
"e": 1933,
"s": 1884,
"text": "Provide an insight into the model with test data"
},
{
"code": null,
"e": 2030,
"s": 1933,
"text": "Now compare the performance metrics of both the test data and the predicted data from the model."
},
{
"code": null,
"e": 2179,
"s": 2030,
"text": "If it doesn’t satisfy your expectations, you can try improving your model accordingly or dating your data, or using another data modeling technique."
},
{
"code": null,
"e": 2258,
"s": 2179,
"text": "At this stage, you interpret the data you have gained and report accordingly. "
},
{
"code": null,
"e": 2326,
"s": 2258,
"text": "You will be using a similar sample technique in the below example. "
},
{
"code": null,
"e": 2401,
"s": 2326,
"text": "Below is a step-by-step sample implementation of Random Forest Regression."
},
{
"code": null,
"e": 2417,
"s": 2401,
"text": "Implementation:"
},
{
"code": null,
"e": 2457,
"s": 2417,
"text": "Step 1: Import the required libraries. "
},
{
"code": null,
"e": 2464,
"s": 2457,
"text": "python"
},
{
"code": "# Importing the librariesimport numpy as npimport matplotlib.pyplot as pltimport pandas as pd",
"e": 2558,
"s": 2464,
"text": null
},
{
"code": null,
"e": 2596,
"s": 2558,
"text": "Step 2: Import and print the dataset "
},
{
"code": null,
"e": 2603,
"s": 2596,
"text": "python"
},
{
"code": "data = pd.read_csv('Salaries.csv')print(data)",
"e": 2649,
"s": 2603,
"text": null
},
{
"code": null,
"e": 2736,
"s": 2649,
"text": "Step 3: Select all rows and column 1 from dataset to x and all rows and column 2 as y "
},
{
"code": null,
"e": 2782,
"s": 2736,
"text": "# the coding was not shown which is like that"
},
{
"code": null,
"e": 3019,
"s": 2782,
"text": "x= df.iloc [:, : -1] # ” : ” means it will select all rows, “: -1 ” means that it will ignore last columny= df.iloc [:, -1 :] # ” : ” means it will select all rows, “-1 : ” means that it will ignore all columns except the last one"
},
{
"code": null,
"e": 3226,
"s": 3019,
"text": "# the “iloc()” function enables us to select a particular cell of the dataset, that is, it helps us select a value that belongs to a particular row or column from a set of values of a data frame or dataset."
},
{
"code": null,
"e": 3278,
"s": 3226,
"text": "Step 4: Fit Random forest regressor to the dataset "
},
{
"code": null,
"e": 3285,
"s": 3278,
"text": "python"
},
{
"code": "# Fitting Random Forest Regression to the dataset# import the regressorfrom sklearn.ensemble import RandomForestRegressor # create regressor objectregressor = RandomForestRegressor(n_estimators = 100, random_state = 0) # fit the regressor with x and y dataregressor.fit(x, y) ",
"e": 3563,
"s": 3285,
"text": null
},
{
"code": null,
"e": 3571,
"s": 3563,
"text": "Output:"
},
{
"code": null,
"e": 3604,
"s": 3571,
"text": "Step 5: Predicting a new result "
},
{
"code": null,
"e": 3611,
"s": 3604,
"text": "python"
},
{
"code": "Y_pred = regressor.predict(np.array([6.5]).reshape(1, 1)) # test the output by changing values",
"e": 3707,
"s": 3611,
"text": null
},
{
"code": null,
"e": 3738,
"s": 3707,
"text": "Step 6: Visualising the result"
},
{
"code": null,
"e": 3745,
"s": 3738,
"text": "python"
},
{
"code": "# Visualising the Random Forest Regression results # arrange for creating a range of values# from min value of x to max# value of x with a difference of 0.01# between two consecutive valuesX_grid = np.arrange(min(x), max(x), 0.01) # reshape for reshaping the data into a len(X_grid)*1 array,# i.e. to make a column out of the X_grid value X_grid = X_grid.reshape((len(X_grid), 1)) # Scatter plot for original dataplt.scatter(x, y, color = 'blue') # plot predicted dataplt.plot(X_grid, regressor.predict(X_grid), color = 'green')plt.title('Random Forest Regression')plt.xlabel('Position level')plt.ylabel('Salary')plt.show()",
"e": 4394,
"s": 3745,
"text": null
},
{
"code": null,
"e": 4403,
"s": 4394,
"text": "Output: "
},
{
"code": null,
"e": 4412,
"s": 4403,
"text": "deepaymt"
},
{
"code": null,
"e": 4430,
"s": 4412,
"text": "devanshigupta1304"
},
{
"code": null,
"e": 4439,
"s": 4430,
"text": "rkbhola5"
},
{
"code": null,
"e": 4467,
"s": 4439,
"text": "abdulraheemshahzadbsse2018a"
},
{
"code": null,
"e": 4484,
"s": 4467,
"text": "Machine Learning"
},
{
"code": null,
"e": 4491,
"s": 4484,
"text": "Python"
},
{
"code": null,
"e": 4508,
"s": 4491,
"text": "Machine Learning"
}
] |
Python | How to Concatenate tuples to nested tuples
|
21 Nov, 2019
Sometimes, while working with tuples, we can have a problem in which we need to convert individual records into a nested collection yet remaining as separate element. Usual addition of tuples, generally adds the contents and hence flattens the resultant container, this is usually undesired. Let’s discuss certain ways in which this problem is solved.
Method #1 : Using + operator + ", " operator during initializationIn this method, we perform the usual addition of tuple elements, but while initializing tuples, we add a comma after the tuple so that they don’t get flattened while addition.
# Python3 code to demonstrate working of# Concatenating tuples to nested tuples# using + operator + ", " operator during initialization # initialize tuplestest_tup1 = (3, 4),test_tup2 = (5, 6), # printing original tuplesprint("The original tuple 1 : " + str(test_tup1))print("The original tuple 2 : " + str(test_tup2)) # Concatenating tuples to nested tuples# using + operator + ", " operator during initializationres = test_tup1 + test_tup2 # printing resultprint("Tuples after Concatenating : " + str(res))
The original tuple 1 : ((3, 4), )
The original tuple 2 : ((5, 6), )
Tuples after Concatenating : ((3, 4), (5, 6))
Method #2 : Using “, ” operator during concatenationThis task can be performed by applying “, ” operator during concatenation as well. It can perform the safe concatenation.
# Python3 code to demonstrate working of# Concatenating tuples to nested tuples# Using ", " operator during concatenation # initialize tuplestest_tup1 = (3, 4)test_tup2 = (5, 6) # printing original tuplesprint("The original tuple 1 : " + str(test_tup1))print("The original tuple 2 : " + str(test_tup2)) # Concatenating tuples to nested tuples# Using ", " operator during concatenationres = ((test_tup1, ) + (test_tup2, )) # printing resultprint("Tuples after Concatenating : " + str(res))
The original tuple 1 : ((3, 4), )
The original tuple 2 : ((5, 6), )
Tuples after Concatenating : ((3, 4), (5, 6))
shubham_singh
Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n21 Nov, 2019"
},
{
"code": null,
"e": 406,
"s": 54,
"text": "Sometimes, while working with tuples, we can have a problem in which we need to convert individual records into a nested collection yet remaining as separate element. Usual addition of tuples, generally adds the contents and hence flattens the resultant container, this is usually undesired. Let’s discuss certain ways in which this problem is solved."
},
{
"code": null,
"e": 648,
"s": 406,
"text": "Method #1 : Using + operator + \", \" operator during initializationIn this method, we perform the usual addition of tuple elements, but while initializing tuples, we add a comma after the tuple so that they don’t get flattened while addition."
},
{
"code": "# Python3 code to demonstrate working of# Concatenating tuples to nested tuples# using + operator + \", \" operator during initialization # initialize tuplestest_tup1 = (3, 4),test_tup2 = (5, 6), # printing original tuplesprint(\"The original tuple 1 : \" + str(test_tup1))print(\"The original tuple 2 : \" + str(test_tup2)) # Concatenating tuples to nested tuples# using + operator + \", \" operator during initializationres = test_tup1 + test_tup2 # printing resultprint(\"Tuples after Concatenating : \" + str(res))",
"e": 1161,
"s": 648,
"text": null
},
{
"code": null,
"e": 1276,
"s": 1161,
"text": "The original tuple 1 : ((3, 4), )\nThe original tuple 2 : ((5, 6), )\nTuples after Concatenating : ((3, 4), (5, 6))\n"
},
{
"code": null,
"e": 1452,
"s": 1278,
"text": "Method #2 : Using “, ” operator during concatenationThis task can be performed by applying “, ” operator during concatenation as well. It can perform the safe concatenation."
},
{
"code": "# Python3 code to demonstrate working of# Concatenating tuples to nested tuples# Using \", \" operator during concatenation # initialize tuplestest_tup1 = (3, 4)test_tup2 = (5, 6) # printing original tuplesprint(\"The original tuple 1 : \" + str(test_tup1))print(\"The original tuple 2 : \" + str(test_tup2)) # Concatenating tuples to nested tuples# Using \", \" operator during concatenationres = ((test_tup1, ) + (test_tup2, )) # printing resultprint(\"Tuples after Concatenating : \" + str(res))",
"e": 1945,
"s": 1452,
"text": null
},
{
"code": null,
"e": 2060,
"s": 1945,
"text": "The original tuple 1 : ((3, 4), )\nThe original tuple 2 : ((5, 6), )\nTuples after Concatenating : ((3, 4), (5, 6))\n"
},
{
"code": null,
"e": 2074,
"s": 2060,
"text": "shubham_singh"
},
{
"code": null,
"e": 2096,
"s": 2074,
"text": "Python tuple-programs"
},
{
"code": null,
"e": 2103,
"s": 2096,
"text": "Python"
},
{
"code": null,
"e": 2119,
"s": 2103,
"text": "Python Programs"
}
] |
MATLAB | Display histogram of a grayscale Image
|
26 Jan, 2019
An image histogram is chart representation of the distribution of intensities in an Indexed image or grayscale image. It shows how many times each intensity value in image occurs.
Code #1: Display histogram of an image using MATLAB library function.
% Read an Image in MATLAB Environmentimg=imread('apple.jpg'); % Convert image to grayscale image# if read image is an RGB imageimg=rgb2gray(img); % Show histogram of image# using imhist() functionimhist(img);
Code #2: Display Histogram of an Image without using MATLAB Library function.
Approach :
Read the source image file into image matrix
Convert it to grayscale, if it is an RGB image
Iterate over image matrix and count the frequency of every possible value of intensity
plot the counted frequency
% Read source image file img = imread('apple.jpg'); % Convert image to grayscale image img=rgb2gray(img); % get the dimension of the image [x, y] = size(img); % Create a frequency array of size 256frequency = 1 : 256; count = 0; % Iterate over grayscale image matrix % for every possible intensity value% and count them for i = 1 : 256 for j = 1 : x for k = 1 : y % if image pixel value at location (j, k) is i-1 % then increment count if img(j, k) == i-1 count = count + 1; end end end % update ith position of frequency array with count frequency(i) = count; % reset count count = 0; end n = 0 : 255; % Display Histogramstem(n, frequency); grid on;ylabel('Number of pixels with such intensity levels -->');xlabel('Intensity Levels -->');title('HISTOGRAM OF THE IMAGE');
Input:
Output:
Image-Processing
MATLAB
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n26 Jan, 2019"
},
{
"code": null,
"e": 234,
"s": 54,
"text": "An image histogram is chart representation of the distribution of intensities in an Indexed image or grayscale image. It shows how many times each intensity value in image occurs."
},
{
"code": null,
"e": 304,
"s": 234,
"text": "Code #1: Display histogram of an image using MATLAB library function."
},
{
"code": "% Read an Image in MATLAB Environmentimg=imread('apple.jpg'); % Convert image to grayscale image# if read image is an RGB imageimg=rgb2gray(img); % Show histogram of image# using imhist() functionimhist(img);",
"e": 515,
"s": 304,
"text": null
},
{
"code": null,
"e": 594,
"s": 515,
"text": " Code #2: Display Histogram of an Image without using MATLAB Library function."
},
{
"code": null,
"e": 605,
"s": 594,
"text": "Approach :"
},
{
"code": null,
"e": 650,
"s": 605,
"text": "Read the source image file into image matrix"
},
{
"code": null,
"e": 697,
"s": 650,
"text": "Convert it to grayscale, if it is an RGB image"
},
{
"code": null,
"e": 784,
"s": 697,
"text": "Iterate over image matrix and count the frequency of every possible value of intensity"
},
{
"code": null,
"e": 811,
"s": 784,
"text": "plot the counted frequency"
},
{
"code": "% Read source image file img = imread('apple.jpg'); % Convert image to grayscale image img=rgb2gray(img); % get the dimension of the image [x, y] = size(img); % Create a frequency array of size 256frequency = 1 : 256; count = 0; % Iterate over grayscale image matrix % for every possible intensity value% and count them for i = 1 : 256 for j = 1 : x for k = 1 : y % if image pixel value at location (j, k) is i-1 % then increment count if img(j, k) == i-1 count = count + 1; end end end % update ith position of frequency array with count frequency(i) = count; % reset count count = 0; end n = 0 : 255; % Display Histogramstem(n, frequency); grid on;ylabel('Number of pixels with such intensity levels -->');xlabel('Intensity Levels -->');title('HISTOGRAM OF THE IMAGE');",
"e": 1699,
"s": 811,
"text": null
},
{
"code": null,
"e": 1706,
"s": 1699,
"text": "Input:"
},
{
"code": null,
"e": 1714,
"s": 1706,
"text": "Output:"
},
{
"code": null,
"e": 1731,
"s": 1714,
"text": "Image-Processing"
},
{
"code": null,
"e": 1738,
"s": 1731,
"text": "MATLAB"
},
{
"code": null,
"e": 1764,
"s": 1738,
"text": "Advanced Computer Subject"
}
] |
Flutter – Social Media Authentication Buttons
|
15 Feb, 2021
Customizing an application for a better user experience requires data storage of each individual user based on their preferences and interests. But profiling each and every user can be tedious. This is where social media authentication comes into play. These authentication systems not only reduce the hectic process of creating a profile on the app but also secures users from unnecessary data leaks. This also reduces the storage need for the application and the server on which operates.
In this article, we will look into the process of adding social media authentication button in a Flutter application through a simple app. To build the same follow the below steps:
Add the dependency to pubspec.yaml file.
Import the dependency to the main.dart file
Use a StatelessWidget to structure the app
Directly add buttons to the application of the body through the dependency.
For the sake of simplicity we will not be adding and actions to the button. Now, let’s look into the steps in detail.
The below image shows the process of adding the flutter_auth_buttons dependency to the pubspec.yaml file.
The below line of code can be added at the top of the main.dart file to import the dependency:
import 'package:flutter_auth_buttons/flutter_auth_buttons.dart';
At this stage use the StatelessWidget to extend it to an app body with an appbar as shown below:
Dart
class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { const padding = 25.0; return MaterialApp( title: 'Social Media Authentication', home: Scaffold( appBar: AppBar( title: Text("GeeksForGeeks"), backgroundColor: Colors.green, ), backgroundColor: Color.fromARGB(0xFF, 0xF0, 0xF0, 0xF0), body: SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: ), ], ), ), ), ); }}
Inside the children of the StatelessWidget use a List to add authenticating buttons for Google, Facebook, MicroSoft, Apple and, Twitter by directly importing them from the package as shown below:
Dart
children: <Widget>[ SizedBox(height: padding), AppleSignInButton( onPressed: () {}, style: AppleButtonStyle.black), SizedBox(height: padding), GoogleSignInButton(onPressed: () {}, darkMode: true), SizedBox(height: padding), FacebookSignInButton(onPressed: () {}), SizedBox(height: padding), TwitterSignInButton(onPressed: () {}), SizedBox(height: padding), MicrosoftSignInButton(onPressed: () {}, darkMode: true), ],
Complete Source Code:
Dart
import 'package:flutter/material.dart';import 'package:flutter_auth_buttons/flutter_auth_buttons.dart'; void main() async { runApp(new MyApp());} class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { const padding = 25.0; return MaterialApp( title: 'Social Media Authentication', home: Scaffold( appBar: AppBar( title: Text("GeeksForGeeks"), backgroundColor: Colors.green, ), backgroundColor: Color.fromARGB(0xFF, 0xF0, 0xF0, 0xF0), body: SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ Column( children: <Widget>[ SizedBox(height: padding), AppleSignInButton( onPressed: () {}, style: AppleButtonStyle.black), SizedBox(height: padding), GoogleSignInButton(onPressed: () {}, darkMode: true), SizedBox(height: padding), FacebookSignInButton(onPressed: () {}), SizedBox(height: padding), TwitterSignInButton(onPressed: () {}), SizedBox(height: padding), MicrosoftSignInButton(onPressed: () {}, darkMode: true), ], ), ], ), ), ), ); }}
Output:
android
Flutter
Flutter UI-components
Flutter-widgets
Dart
Flutter
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 - Search Bar
Flutter - FutureBuilder Widget
Flutter - Dialogs
Flutter - Custom Bottom Navigation Bar
Flutter Tutorial
Flutter - Search Bar
Flutter - FutureBuilder Widget
Flutter - Dialogs
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Feb, 2021"
},
{
"code": null,
"e": 520,
"s": 28,
"text": "Customizing an application for a better user experience requires data storage of each individual user based on their preferences and interests. But profiling each and every user can be tedious. This is where social media authentication comes into play. These authentication systems not only reduce the hectic process of creating a profile on the app but also secures users from unnecessary data leaks. This also reduces the storage need for the application and the server on which operates."
},
{
"code": null,
"e": 701,
"s": 520,
"text": "In this article, we will look into the process of adding social media authentication button in a Flutter application through a simple app. To build the same follow the below steps:"
},
{
"code": null,
"e": 742,
"s": 701,
"text": "Add the dependency to pubspec.yaml file."
},
{
"code": null,
"e": 786,
"s": 742,
"text": "Import the dependency to the main.dart file"
},
{
"code": null,
"e": 829,
"s": 786,
"text": "Use a StatelessWidget to structure the app"
},
{
"code": null,
"e": 905,
"s": 829,
"text": "Directly add buttons to the application of the body through the dependency."
},
{
"code": null,
"e": 1023,
"s": 905,
"text": "For the sake of simplicity we will not be adding and actions to the button. Now, let’s look into the steps in detail."
},
{
"code": null,
"e": 1129,
"s": 1023,
"text": "The below image shows the process of adding the flutter_auth_buttons dependency to the pubspec.yaml file."
},
{
"code": null,
"e": 1224,
"s": 1129,
"text": "The below line of code can be added at the top of the main.dart file to import the dependency:"
},
{
"code": null,
"e": 1290,
"s": 1224,
"text": "import 'package:flutter_auth_buttons/flutter_auth_buttons.dart';\n"
},
{
"code": null,
"e": 1387,
"s": 1290,
"text": "At this stage use the StatelessWidget to extend it to an app body with an appbar as shown below:"
},
{
"code": null,
"e": 1392,
"s": 1387,
"text": "Dart"
},
{
"code": "class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { const padding = 25.0; return MaterialApp( title: 'Social Media Authentication', home: Scaffold( appBar: AppBar( title: Text(\"GeeksForGeeks\"), backgroundColor: Colors.green, ), backgroundColor: Color.fromARGB(0xFF, 0xF0, 0xF0, 0xF0), body: SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: ), ], ), ), ), ); }}",
"e": 1979,
"s": 1392,
"text": null
},
{
"code": null,
"e": 2175,
"s": 1979,
"text": "Inside the children of the StatelessWidget use a List to add authenticating buttons for Google, Facebook, MicroSoft, Apple and, Twitter by directly importing them from the package as shown below:"
},
{
"code": null,
"e": 2180,
"s": 2175,
"text": "Dart"
},
{
"code": "children: <Widget>[ SizedBox(height: padding), AppleSignInButton( onPressed: () {}, style: AppleButtonStyle.black), SizedBox(height: padding), GoogleSignInButton(onPressed: () {}, darkMode: true), SizedBox(height: padding), FacebookSignInButton(onPressed: () {}), SizedBox(height: padding), TwitterSignInButton(onPressed: () {}), SizedBox(height: padding), MicrosoftSignInButton(onPressed: () {}, darkMode: true), ],",
"e": 2791,
"s": 2180,
"text": null
},
{
"code": null,
"e": 2813,
"s": 2791,
"text": "Complete Source Code:"
},
{
"code": null,
"e": 2818,
"s": 2813,
"text": "Dart"
},
{
"code": "import 'package:flutter/material.dart';import 'package:flutter_auth_buttons/flutter_auth_buttons.dart'; void main() async { runApp(new MyApp());} class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { const padding = 25.0; return MaterialApp( title: 'Social Media Authentication', home: Scaffold( appBar: AppBar( title: Text(\"GeeksForGeeks\"), backgroundColor: Colors.green, ), backgroundColor: Color.fromARGB(0xFF, 0xF0, 0xF0, 0xF0), body: SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ Column( children: <Widget>[ SizedBox(height: padding), AppleSignInButton( onPressed: () {}, style: AppleButtonStyle.black), SizedBox(height: padding), GoogleSignInButton(onPressed: () {}, darkMode: true), SizedBox(height: padding), FacebookSignInButton(onPressed: () {}), SizedBox(height: padding), TwitterSignInButton(onPressed: () {}), SizedBox(height: padding), MicrosoftSignInButton(onPressed: () {}, darkMode: true), ], ), ], ), ), ), ); }}",
"e": 4223,
"s": 2818,
"text": null
},
{
"code": null,
"e": 4231,
"s": 4223,
"text": "Output:"
},
{
"code": null,
"e": 4239,
"s": 4231,
"text": "android"
},
{
"code": null,
"e": 4247,
"s": 4239,
"text": "Flutter"
},
{
"code": null,
"e": 4269,
"s": 4247,
"text": "Flutter UI-components"
},
{
"code": null,
"e": 4285,
"s": 4269,
"text": "Flutter-widgets"
},
{
"code": null,
"e": 4290,
"s": 4285,
"text": "Dart"
},
{
"code": null,
"e": 4298,
"s": 4290,
"text": "Flutter"
},
{
"code": null,
"e": 4396,
"s": 4298,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4435,
"s": 4396,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 4461,
"s": 4435,
"text": "ListView Class in Flutter"
},
{
"code": null,
"e": 4482,
"s": 4461,
"text": "Flutter - Search Bar"
},
{
"code": null,
"e": 4513,
"s": 4482,
"text": "Flutter - FutureBuilder Widget"
},
{
"code": null,
"e": 4531,
"s": 4513,
"text": "Flutter - Dialogs"
},
{
"code": null,
"e": 4570,
"s": 4531,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 4587,
"s": 4570,
"text": "Flutter Tutorial"
},
{
"code": null,
"e": 4608,
"s": 4587,
"text": "Flutter - Search Bar"
},
{
"code": null,
"e": 4639,
"s": 4608,
"text": "Flutter - FutureBuilder Widget"
}
] |
How to find the index value of specified string in Golang?
|
26 Aug, 2019
In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding.In Go strings, you can find the first index value of the specified string from the original string using the following function. These functions are defined under strings package so, you have to import strings package in your program for accessing these functions:
1. Index: This function is used to find the index value of the first instance of the given string from the original string. If the given string is not available in the original string, then this method will return -1.
Syntax:
func Index(str, sbstr string) int
Here, str is the original string and sbstr is a string whose we want to find index value. Let us discuss this concept with the help of an example:
Example:
// Go program to illustrate how to find// the index value of the given stringpackage main import ( "fmt" "strings") // Main functionfunc main() { // Creating and initializing the strings str1 := "Welcome to the online portal of GeeksforGeeks" str2 := "My dog name is Dollar" str3 := "I like to play Ludo" // Displaying strings fmt.Println("String 1: ", str1) fmt.Println("String 2: ", str2) fmt.Println("String 3: ", str3) // Finding the index value of the given strings // Using Index() function res1 := strings.Index(str1, "Geeks") res2 := strings.Index(str2, "do") res3 := strings.Index(str3, "chess") res4 := strings.Index("GeeksforGeeks, geeks", "ks") // Displaying the result fmt.Println("\nIndex values:") fmt.Println("Result 1: ", res1) fmt.Println("Result 2: ", res2) fmt.Println("Result 3: ", res3) fmt.Println("Result 4: ", res4) }
Output:
String 1: Welcome to the online portal of GeeksforGeeks
String 2: My dog name is Dollar
String 3: I like to play Ludo
Index values:
Result 1: 32
Result 2: 3
Result 3: -1
Result 4: 3
2. IndexAny: This method returns the index of the first instance of any Unicode code point from chars in the original string. If the Unicode code point from chars is not available in the original string, then this method will return -1.
Syntax:
func IndexAny(str, charstr string) int
Here, str is the original string and charstr is a Unicode code point from chars whose we want to find index value.
Example:
// Go program to illustrate how to find// the index value of the given stringpackage main import ( "fmt" "strings") // Main functionfunc main() { // Creating and initializing the strings str1 := "Welcome to the online portal of GeeksforGeeks" str2 := "My dog name is Dollar" str3 := "I like to play Ludo" // Displaying strings fmt.Println("String 1: ", str1) fmt.Println("String 2: ", str2) fmt.Println("String 3: ", str3) // Finding the index value // of the given strings // Using IndexAny() function res1 := strings.IndexAny(str1, "G") res2 := strings.IndexAny(str2, "do") res3 := strings.IndexAny(str3, "lqxa") res4 := strings.IndexAny("GeeksforGeeks, geeks", "uywq") // Displaying the result fmt.Println("\nIndex values:") fmt.Println("Result 1: ", res1) fmt.Println("Result 2: ", res2) fmt.Println("Result 3: ", res3) fmt.Println("Result 4: ", res4) }
Output:
String 1: Welcome to the online portal of GeeksforGeeks
String 2: My dog name is Dollar
String 3: I like to play Ludo
Index values:
Result 1: 32
Result 2: 3
Result 3: 2
Result 4: -1
3. IndexByte: This function returns the index of the first instance of the given byte in the original string. If the given byte is not available in the original string, then this method will return -1.
Syntax:
func IndexByte(str string, b byte) int
Here, str is the original string and b is a byte, whose we want to find the index value. Let us discuss this concept with the help of an example:
Example:
// Go program to illustrate how to find// the index value of the given bytespackage main import ( "fmt" "strings") // Main functionfunc main() { // Creating and initializing the strings str1 := "Welcome to the online portal of GeeksforGeeks" str2 := "My dog name is Dollar" str3 := "I like to play Ludo" // Displaying strings fmt.Println("String 1: ", str1) fmt.Println("String 2: ", str2) fmt.Println("String 3: ", str3) // Finding the index value of the given bytes // Using IndexByte() function res1 := strings.IndexByte(str1, 'c') res2 := strings.IndexByte(str2, 'o') res3 := strings.IndexByte(str3, 'q') res4 := strings.IndexByte("GeeksforGeeks, geeks", 'G') // Displaying the result fmt.Println("\nIndex values:") fmt.Println("Result 1: ", res1) fmt.Println("Result 2: ", res2) fmt.Println("Result 3: ", res3) fmt.Println("Result 4: ", res4) }
Output:
String 1: Welcome to the online portal of GeeksforGeeks
String 2: My dog name is Dollar
String 3: I like to play Ludo
Index values:
Result 1: 3
Result 2: 4
Result 3: -1
Result 4: 0
Golang
Golang-String
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Aug, 2019"
},
{
"code": null,
"e": 515,
"s": 28,
"text": "In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding.In Go strings, you can find the first index value of the specified string from the original string using the following function. These functions are defined under strings package so, you have to import strings package in your program for accessing these functions:"
},
{
"code": null,
"e": 733,
"s": 515,
"text": "1. Index: This function is used to find the index value of the first instance of the given string from the original string. If the given string is not available in the original string, then this method will return -1."
},
{
"code": null,
"e": 741,
"s": 733,
"text": "Syntax:"
},
{
"code": null,
"e": 775,
"s": 741,
"text": "func Index(str, sbstr string) int"
},
{
"code": null,
"e": 922,
"s": 775,
"text": "Here, str is the original string and sbstr is a string whose we want to find index value. Let us discuss this concept with the help of an example:"
},
{
"code": null,
"e": 931,
"s": 922,
"text": "Example:"
},
{
"code": "// Go program to illustrate how to find// the index value of the given stringpackage main import ( \"fmt\" \"strings\") // Main functionfunc main() { // Creating and initializing the strings str1 := \"Welcome to the online portal of GeeksforGeeks\" str2 := \"My dog name is Dollar\" str3 := \"I like to play Ludo\" // Displaying strings fmt.Println(\"String 1: \", str1) fmt.Println(\"String 2: \", str2) fmt.Println(\"String 3: \", str3) // Finding the index value of the given strings // Using Index() function res1 := strings.Index(str1, \"Geeks\") res2 := strings.Index(str2, \"do\") res3 := strings.Index(str3, \"chess\") res4 := strings.Index(\"GeeksforGeeks, geeks\", \"ks\") // Displaying the result fmt.Println(\"\\nIndex values:\") fmt.Println(\"Result 1: \", res1) fmt.Println(\"Result 2: \", res2) fmt.Println(\"Result 3: \", res3) fmt.Println(\"Result 4: \", res4) }",
"e": 1851,
"s": 931,
"text": null
},
{
"code": null,
"e": 1859,
"s": 1851,
"text": "Output:"
},
{
"code": null,
"e": 2050,
"s": 1859,
"text": "String 1: Welcome to the online portal of GeeksforGeeks\nString 2: My dog name is Dollar\nString 3: I like to play Ludo\n\nIndex values:\nResult 1: 32\nResult 2: 3\nResult 3: -1\nResult 4: 3\n"
},
{
"code": null,
"e": 2287,
"s": 2050,
"text": "2. IndexAny: This method returns the index of the first instance of any Unicode code point from chars in the original string. If the Unicode code point from chars is not available in the original string, then this method will return -1."
},
{
"code": null,
"e": 2295,
"s": 2287,
"text": "Syntax:"
},
{
"code": null,
"e": 2334,
"s": 2295,
"text": "func IndexAny(str, charstr string) int"
},
{
"code": null,
"e": 2449,
"s": 2334,
"text": "Here, str is the original string and charstr is a Unicode code point from chars whose we want to find index value."
},
{
"code": null,
"e": 2458,
"s": 2449,
"text": "Example:"
},
{
"code": "// Go program to illustrate how to find// the index value of the given stringpackage main import ( \"fmt\" \"strings\") // Main functionfunc main() { // Creating and initializing the strings str1 := \"Welcome to the online portal of GeeksforGeeks\" str2 := \"My dog name is Dollar\" str3 := \"I like to play Ludo\" // Displaying strings fmt.Println(\"String 1: \", str1) fmt.Println(\"String 2: \", str2) fmt.Println(\"String 3: \", str3) // Finding the index value // of the given strings // Using IndexAny() function res1 := strings.IndexAny(str1, \"G\") res2 := strings.IndexAny(str2, \"do\") res3 := strings.IndexAny(str3, \"lqxa\") res4 := strings.IndexAny(\"GeeksforGeeks, geeks\", \"uywq\") // Displaying the result fmt.Println(\"\\nIndex values:\") fmt.Println(\"Result 1: \", res1) fmt.Println(\"Result 2: \", res2) fmt.Println(\"Result 3: \", res3) fmt.Println(\"Result 4: \", res4) }",
"e": 3397,
"s": 2458,
"text": null
},
{
"code": null,
"e": 3405,
"s": 3397,
"text": "Output:"
},
{
"code": null,
"e": 3596,
"s": 3405,
"text": "String 1: Welcome to the online portal of GeeksforGeeks\nString 2: My dog name is Dollar\nString 3: I like to play Ludo\n\nIndex values:\nResult 1: 32\nResult 2: 3\nResult 3: 2\nResult 4: -1\n"
},
{
"code": null,
"e": 3798,
"s": 3596,
"text": "3. IndexByte: This function returns the index of the first instance of the given byte in the original string. If the given byte is not available in the original string, then this method will return -1."
},
{
"code": null,
"e": 3806,
"s": 3798,
"text": "Syntax:"
},
{
"code": null,
"e": 3845,
"s": 3806,
"text": "func IndexByte(str string, b byte) int"
},
{
"code": null,
"e": 3991,
"s": 3845,
"text": "Here, str is the original string and b is a byte, whose we want to find the index value. Let us discuss this concept with the help of an example:"
},
{
"code": null,
"e": 4000,
"s": 3991,
"text": "Example:"
},
{
"code": "// Go program to illustrate how to find// the index value of the given bytespackage main import ( \"fmt\" \"strings\") // Main functionfunc main() { // Creating and initializing the strings str1 := \"Welcome to the online portal of GeeksforGeeks\" str2 := \"My dog name is Dollar\" str3 := \"I like to play Ludo\" // Displaying strings fmt.Println(\"String 1: \", str1) fmt.Println(\"String 2: \", str2) fmt.Println(\"String 3: \", str3) // Finding the index value of the given bytes // Using IndexByte() function res1 := strings.IndexByte(str1, 'c') res2 := strings.IndexByte(str2, 'o') res3 := strings.IndexByte(str3, 'q') res4 := strings.IndexByte(\"GeeksforGeeks, geeks\", 'G') // Displaying the result fmt.Println(\"\\nIndex values:\") fmt.Println(\"Result 1: \", res1) fmt.Println(\"Result 2: \", res2) fmt.Println(\"Result 3: \", res3) fmt.Println(\"Result 4: \", res4) }",
"e": 4927,
"s": 4000,
"text": null
},
{
"code": null,
"e": 4935,
"s": 4927,
"text": "Output:"
},
{
"code": null,
"e": 5125,
"s": 4935,
"text": "String 1: Welcome to the online portal of GeeksforGeeks\nString 2: My dog name is Dollar\nString 3: I like to play Ludo\n\nIndex values:\nResult 1: 3\nResult 2: 4\nResult 3: -1\nResult 4: 0\n"
},
{
"code": null,
"e": 5132,
"s": 5125,
"text": "Golang"
},
{
"code": null,
"e": 5146,
"s": 5132,
"text": "Golang-String"
},
{
"code": null,
"e": 5158,
"s": 5146,
"text": "Go Language"
}
] |
How to work with Julia on Jupyter Notebook?
|
14 Sep, 2021
Julia is a programming language that uses multiple dispatches as a feature where a method or a function can be dynamically dispatched based on the requirement. It is a high performance and a dynamic language which makes it user-interactive. It has a high-level syntax which makes it easy to learn and use for the beginner to expert level programmers. Julia is open-source, so anyone can use it for free.
Jupyter is an open-source project which provides an interactive environment for data science and scientific computations using many programming languages. It is web-based software and it is free for everyone to use. Jupyter notebooks are documents in which programmers can write live text or code in, and also implement visualizations.
Julia is a compiled language and is easy to write. Jupyter notebooks are used to implement programs and mathematical equations with Julia effectively with live data visualizations. By using the two of them, impressive tasks can be implemented even if the user has low programming knowledge.
The easiest way is to install it is through the application of Anaconda. The Anaconda distribution contains python, jupyter notebooks, and other packages for data science implementation. Click here and scroll down to download the latest appropriate version of Anaconda installation file for your operating system.
Detailed steps for installation and implementation of Jupyter notebook are provided in How to install Jupyter Notebook in Windows and Linux?
Step 1: First, Julia has to be installed on your computer, it can be downloaded from its official site julialang.org and can be installed by following steps in How to Install Julia on Windows and Linux?
Step 2: After the installation, click on the Julia application and the following command prompt will appear:
Step 3: Now, the communication between Julia and Jupyter has to be established, for this enter the following commands in the prompt and press enter:
using Pkg
Pkg.add("IJulia")
This tells Julia to use the package manager and then to adds the package IJulia which establishes the connection between Jupyter and Julia. Julia takes some time to install the IJulia package and the end of the process should appear like in the image shown below:
Step 4: We have established a connection between Julia and Jupyter and now a new Jupyter notebook can be created with Julia instead of Python. The option to select Julia will be present when the new notebook option is clicked as shown in the image below:
Step 5: Appropriate packages are also to be added to use Julia for required purposes. Commands to add some of the most commonly used packages are given below:
Pkg.add("DataFrames")
Pkg.add("CSV")
Pkg.add("Plots")
The packages mentioned above are to create and use data frames, read and write CSV files and use plots for visualization respectively.
Sample example code
Now that the setup has been completed, we can go ahead and implement our first code in Julia on the Jupyter notebook. Example of a most basic print statement is given below:
Julia
println("Geeksforgeeks is fantastic!")
Output:
Geeksforgeeks is fantastic!
Following image shows the execution of the example in Jupyter notebook:
After installing the necessary packages for your purposes, you can experience the high-performance Julia language in Jupyter notebook.
gokulyc
singghakshay
Picked
How To
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Sep, 2021"
},
{
"code": null,
"e": 432,
"s": 28,
"text": "Julia is a programming language that uses multiple dispatches as a feature where a method or a function can be dynamically dispatched based on the requirement. It is a high performance and a dynamic language which makes it user-interactive. It has a high-level syntax which makes it easy to learn and use for the beginner to expert level programmers. Julia is open-source, so anyone can use it for free."
},
{
"code": null,
"e": 768,
"s": 432,
"text": "Jupyter is an open-source project which provides an interactive environment for data science and scientific computations using many programming languages. It is web-based software and it is free for everyone to use. Jupyter notebooks are documents in which programmers can write live text or code in, and also implement visualizations."
},
{
"code": null,
"e": 1059,
"s": 768,
"text": "Julia is a compiled language and is easy to write. Jupyter notebooks are used to implement programs and mathematical equations with Julia effectively with live data visualizations. By using the two of them, impressive tasks can be implemented even if the user has low programming knowledge."
},
{
"code": null,
"e": 1373,
"s": 1059,
"text": "The easiest way is to install it is through the application of Anaconda. The Anaconda distribution contains python, jupyter notebooks, and other packages for data science implementation. Click here and scroll down to download the latest appropriate version of Anaconda installation file for your operating system."
},
{
"code": null,
"e": 1515,
"s": 1373,
"text": "Detailed steps for installation and implementation of Jupyter notebook are provided in How to install Jupyter Notebook in Windows and Linux? "
},
{
"code": null,
"e": 1718,
"s": 1515,
"text": "Step 1: First, Julia has to be installed on your computer, it can be downloaded from its official site julialang.org and can be installed by following steps in How to Install Julia on Windows and Linux?"
},
{
"code": null,
"e": 1829,
"s": 1718,
"text": "Step 2: After the installation, click on the Julia application and the following command prompt will appear: "
},
{
"code": null,
"e": 1979,
"s": 1829,
"text": "Step 3: Now, the communication between Julia and Jupyter has to be established, for this enter the following commands in the prompt and press enter: "
},
{
"code": null,
"e": 2007,
"s": 1979,
"text": "using Pkg\nPkg.add(\"IJulia\")"
},
{
"code": null,
"e": 2272,
"s": 2007,
"text": "This tells Julia to use the package manager and then to adds the package IJulia which establishes the connection between Jupyter and Julia. Julia takes some time to install the IJulia package and the end of the process should appear like in the image shown below: "
},
{
"code": null,
"e": 2528,
"s": 2272,
"text": "Step 4: We have established a connection between Julia and Jupyter and now a new Jupyter notebook can be created with Julia instead of Python. The option to select Julia will be present when the new notebook option is clicked as shown in the image below: "
},
{
"code": null,
"e": 2688,
"s": 2528,
"text": "Step 5: Appropriate packages are also to be added to use Julia for required purposes. Commands to add some of the most commonly used packages are given below: "
},
{
"code": null,
"e": 2742,
"s": 2688,
"text": "Pkg.add(\"DataFrames\")\nPkg.add(\"CSV\")\nPkg.add(\"Plots\")"
},
{
"code": null,
"e": 2877,
"s": 2742,
"text": "The packages mentioned above are to create and use data frames, read and write CSV files and use plots for visualization respectively."
},
{
"code": null,
"e": 2897,
"s": 2877,
"text": "Sample example code"
},
{
"code": null,
"e": 3072,
"s": 2897,
"text": "Now that the setup has been completed, we can go ahead and implement our first code in Julia on the Jupyter notebook. Example of a most basic print statement is given below: "
},
{
"code": null,
"e": 3078,
"s": 3072,
"text": "Julia"
},
{
"code": "println(\"Geeksforgeeks is fantastic!\")",
"e": 3117,
"s": 3078,
"text": null
},
{
"code": null,
"e": 3126,
"s": 3117,
"text": "Output: "
},
{
"code": null,
"e": 3154,
"s": 3126,
"text": "Geeksforgeeks is fantastic!"
},
{
"code": null,
"e": 3228,
"s": 3154,
"text": " Following image shows the execution of the example in Jupyter notebook: "
},
{
"code": null,
"e": 3363,
"s": 3228,
"text": "After installing the necessary packages for your purposes, you can experience the high-performance Julia language in Jupyter notebook."
},
{
"code": null,
"e": 3373,
"s": 3365,
"text": "gokulyc"
},
{
"code": null,
"e": 3386,
"s": 3373,
"text": "singghakshay"
},
{
"code": null,
"e": 3393,
"s": 3386,
"text": "Picked"
},
{
"code": null,
"e": 3400,
"s": 3393,
"text": "How To"
},
{
"code": null,
"e": 3406,
"s": 3400,
"text": "Julia"
}
] |
Rank of an element in a stream
|
01 Jul, 2021
Given a stream of integers, lookup the rank of a given integer x. Rank of an integer in-stream is “Total number of elements less than or equal to x (not including x)”.If an element is not found in the stream or is smallest in stream, return -1. Examples:
Input : arr[] = {10, 20, 15, 3, 4, 4, 1}
x = 4;
Output : Rank of 4 in stream is: 3
There are total three elements less than
or equal to x (and not including x)
Input : arr[] = {5, 1, 14, 4, 15, 9, 7, 20, 11},
x = 20;
Output : Rank of 20 in stream is: 8
A relatively easy way to implement this is to use an array that holds all the elements in sorted order. When a new element is inserted we would shift the elements. Then we perform binary search on the array to get the right-most index of x and return that index. getRank(x) would work in O(log n) but insertion would be costly.An efficient way is to use a Binary Search Tree. Each Node will hold the data value and size of its left subtree.We traverse the tree from root and compare the root values to x.
If root->data == x, return size of left subtree of root.If x < root->data, return getRank(root->left)If x > root->data, return getRank(root->right) + size of leftSubtree + 1.
If root->data == x, return size of left subtree of root.
If x < root->data, return getRank(root->left)
If x > root->data, return getRank(root->right) + size of leftSubtree + 1.
Below is the solution.
C++
Java
Python3
C#
Javascript
// CPP program to find rank of an// element in a stream.#include <bits/stdc++.h>using namespace std; struct Node { int data; Node *left, *right; int leftSize;}; Node* newNode(int data){ Node *temp = new Node; temp->data = data; temp->left = temp->right = NULL; temp->leftSize = 0; return temp;} // Inserting a new Node.Node* insert(Node*& root, int data){ if (!root) return newNode(data); // Updating size of left subtree. if (data <= root->data) { root->left = insert(root->left, data); root->leftSize++; } else root->right = insert(root->right, data); return root;} // Function to get Rank of a Node x.int getRank(Node* root, int x){ // Step 1. if (root->data == x) return root->leftSize; // Step 2. if (x < root->data) { if (!root->left) return -1; else return getRank(root->left, x); } // Step 3. else { if (!root->right) return -1; else { int rightSize = getRank(root->right, x); if(rightSize == -1 ) return -1; return root->leftSize + 1 + rightSize; } }} // Driver codeint main(){ int arr[] = { 5, 1, 4, 4, 5, 9, 7, 13, 3 }; int n = sizeof(arr) / sizeof(arr[0]); int x = 4; Node* root = NULL; for (int i = 0; i < n; i++) root = insert(root, arr[i]); cout << "Rank of " << x << " in stream is: " << getRank(root, x) << endl; x = 13; cout << "Rank of " << x << " in stream is: " << getRank(root, x) << endl; x = 8; cout << "Rank of " << x << " in stream is: " << getRank(root, x) << endl; return 0;}
// Java program to find rank of an// element in a stream.class GfG { static class Node { int data; Node left, right; int leftSize;} static Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.left = null; temp.right = null; temp.leftSize = 0; return temp;} // Inserting a new Node.static Node insert(Node root, int data){ if (root == null) return newNode(data); // Updating size of left subtree. if (data <= root.data) { root.left = insert(root.left, data); root.leftSize++; } else root.right = insert(root.right, data); return root;} // Function to get Rank of a Node x.static int getRank(Node root, int x){ // Step 1. if (root.data == x) return root.leftSize; // Step 2. if (x < root.data) { if (root.left == null) return -1; else return getRank(root.left, x); } // Step 3. else { if (root.right == null) return -1; else { int rightSize = getRank(root.right, x); if(rightSize == -1) return -1; return root.leftSize + 1 + rightSize; } }} // Driver codepublic static void main(String[] args){ int arr[] = { 5, 1, 4, 4, 5, 9, 7, 13, 3 }; int n = arr.length; int x = 4; Node root = null; for (int i = 0; i < n; i++) root = insert(root, arr[i]); System.out.println("Rank of " + x + " in stream is : "+getRank(root, x)); x = 13; System.out.println("Rank of " + x + " in stream is : "+getRank(root, x)); }}
# Python3 program to find rank of an# element in a stream. class newNode: def __init__(self, data): self.data = data self.left = self.right = None self.leftSize = 0 # Inserting a new Node.def insert(root, data): if root is None: return newNode(data) # Updating size of left subtree. if data <= root.data: root.left = insert(root.left, data) root.leftSize += 1 else: root.right = insert(root.right, data) return root # Function to get Rank of a Node x.def getRank(root, x): # Step 1. if root.data == x: return root.leftSize # Step 2. if x < root.data: if root.left is None: return -1 else: return getRank(root.left, x) # Step 3. else: if root.right is None: return -1 else: rightSize = getRank(root.right, x) if rightSize == -1: # x not found in right sub tree, i.e. not found in stream return -1 else: return root.leftSize + 1 + rightSize # Driver codeif __name__ == '__main__': arr = [5, 1, 4, 4, 5, 9, 7, 13, 3] n = len(arr) x = 4 root = None for i in range(n): root = insert(root, arr[i]) print("Rank of", x, "in stream is:", getRank(root, x)) x = 13 print("Rank of", x, "in stream is:", getRank(root, x)) x = 8 print("Rank of", x, "in stream is:", getRank(root, x)) # This code is contributed by PranchalK
// C# program to find rank of an// element in a stream.using System; class GFG{public class Node{ public int data; public Node left, right; public int leftSize;} static Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.left = null; temp.right = null; temp.leftSize = 0; return temp;} // Inserting a new Node.static Node insert(Node root, int data){ if (root == null) return newNode(data); // Updating size of left subtree. if (data <= root.data) { root.left = insert(root.left, data); root.leftSize++; } else root.right = insert(root.right, data); return root;} // Function to get Rank of a Node x.static int getRank(Node root, int x){ // Step 1. if (root.data == x) return root.leftSize; // Step 2. if (x < root.data) { if (root.left == null) return -1; else return getRank(root.left, x); } // Step 3. else { if (root.right == null) return -1; else { int rightSize = getRank(root.right, x); if(rightSize == -1) return -1; return root.leftSize + 1 + rightSize; } }} // Driver codepublic static void Main(String[] args){ int []arr = { 5, 1, 4, 4, 5, 9, 7, 13, 3 }; int n = arr.Length; int x = 4; Node root = null; for (int i = 0; i < n; i++) root = insert(root, arr[i]); Console.WriteLine("Rank of " + x + " in stream is : " + getRank(root, x)); x = 13; Console.WriteLine("Rank of " + x + " in stream is : " + getRank(root, x));}} // This code is contributed by PrinciRaj1992
<script> // JavaScript program to find rank of an// element in a stream. class Node{ constructor() { this.data = 0; this.left = null; this.right = null; this.leftSize = 0; }} function newNode(data){ var temp = new Node(); temp.data = data; temp.left = null; temp.right = null; temp.leftSize = 0; return temp;} // Inserting a new Node.function insert(root, data){ if (root == null) return newNode(data); // Updating size of left subtree. if (data <= root.data) { root.left = insert(root.left, data); root.leftSize++; } else root.right = insert(root.right, data); return root;} // Function to get Rank of a Node x.function getRank(root, x){ // Step 1. if (root.data == x) return root.leftSize; // Step 2. if (x < root.data) { if (root.left == null) return -1; else return getRank(root.left, x); } // Step 3. else { if (root.right == null) return -1; else { var rightSize = getRank(root.right, x); if(rightSize == -1) return -1; return root.leftSize + 1 + rightSize; } }} // Driver codevar arr = [5, 1, 4, 4, 5, 9, 7, 13, 3];var n = arr.length;var x = 4;var root = null;for (var i = 0; i < n; i++) root = insert(root, arr[i]);document.write("Rank of " + x + " in stream is : " + getRank(root, x) + "<br>");x = 13;document.write("Rank of " + x + " in stream is : " + getRank(root, x)+"<br>");x = 8;document.write("Rank of " + x + " in stream is : " + getRank(root, x)); </script>
Rank of 4 in stream is: 3
Rank of 13 in stream is: 8
Rank of 8 in stream is: -1
Another approach: Traverse the array from the beginning. While traversing, count the nodes which is equal to or less than the given key.Print the count(Rank).
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find rank of an// element in a stream.#include <bits/stdc++.h>using namespace std; // Driver codeint main(){ int a[] = {5, 1, 14, 4, 15, 9, 7, 20, 11}; int key = 20; int arraySize = sizeof(a)/sizeof(a[0]); int count = 0; for(int i = 0; i < arraySize; i++) { if(a[i] <= key) { count += 1; } } cout << "Rank of " << key << " in stream is: " << count-1 << endl; return 0;} // This code is contributed by// Ashwin Loganathan.
// Java program to find rank of an// element in a stream.class GFG{ // Driver codepublic static void main(String[] args){ int a[] = {5, 1, 14, 4, 15, 9, 7, 20, 11}; int key = 20; int arraySize = a.length; int count = 0; for(int i = 0; i < arraySize; i++) { if(a[i] <= key) { count += 1; } } System.out.println("Rank of " + key + " in stream is: " + (count - 1));}} // This code has been contributed by 29AjayKumar
# Python3 program to find rank of an# element in a stream. # Driver codeif __name__ == '__main__': a = [5, 1, 14, 4, 15, 9, 7, 20, 11] key = 20 arraySize = len(a) count = 0 for i in range(arraySize): if a[i] <= key: count += 1 print("Rank of", key, "in stream is:", count - 1) # This code is contributed by PranchalK
// C# program to find rank of an// element in a stream.using System; class GFG{// Driver codepublic static void Main(){ int []a = {5, 1, 14, 4, 15, 9, 7, 20, 11}; int key = 20; int arraySize = a.Length; int count = 0; for(int i = 0; i < arraySize; i++) { if(a[i] <= key) { count += 1; } } Console.WriteLine("Rank of " + key + " in stream is: " + (count - 1));}} // This code is contributed by// Akanksha Rai
<?php// PHP program to find rank of an// element in a stream. // Driver code$a = array(5, 1, 14, 4, 15, 9, 7, 20, 11);$key = 20;$arraySize = sizeof($a);$count = 0;for($i = 0; $i < $arraySize; $i++){ if($a[$i] <= $key) { $count += 1; }}echo "Rank of " . $key . " in stream is: " . ($count - 1) . "\n"; // This code is contributed by// Akanksha Rai?>
<script>// javascript program to find rank of an// element in a stream. // Driver code var a = [ 5, 1, 14, 4, 15, 9, 7, 20, 11 ]; var key = 20; var arraySize = a.length; var count = 0; for (i = 0; i < arraySize; i++) { if (a[i] <= key) { count += 1; } } document.write("Rank of " + key + " in stream is: " + (count - 1)); // This code contributed by umadevi9616</script>
Output:
Rank of 20 in stream is: 8
prerna saini
Ashwin Loganathan
PranchalKatiyar
Akanksha_Rai
29AjayKumar
princiraj1992
Nitish Jain
mathew dominic
wxy8955
umadevi9616
rutvik_56
Arrays
Binary Search Tree
Arrays
Binary Search Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n01 Jul, 2021"
},
{
"code": null,
"e": 311,
"s": 54,
"text": "Given a stream of integers, lookup the rank of a given integer x. Rank of an integer in-stream is “Total number of elements less than or equal to x (not including x)”.If an element is not found in the stream or is smallest in stream, return -1. Examples: "
},
{
"code": null,
"e": 592,
"s": 311,
"text": "Input : arr[] = {10, 20, 15, 3, 4, 4, 1}\n x = 4;\nOutput : Rank of 4 in stream is: 3\nThere are total three elements less than\nor equal to x (and not including x)\n\nInput : arr[] = {5, 1, 14, 4, 15, 9, 7, 20, 11}, \n x = 20;\nOutput : Rank of 20 in stream is: 8"
},
{
"code": null,
"e": 1101,
"s": 594,
"text": "A relatively easy way to implement this is to use an array that holds all the elements in sorted order. When a new element is inserted we would shift the elements. Then we perform binary search on the array to get the right-most index of x and return that index. getRank(x) would work in O(log n) but insertion would be costly.An efficient way is to use a Binary Search Tree. Each Node will hold the data value and size of its left subtree.We traverse the tree from root and compare the root values to x. "
},
{
"code": null,
"e": 1276,
"s": 1101,
"text": "If root->data == x, return size of left subtree of root.If x < root->data, return getRank(root->left)If x > root->data, return getRank(root->right) + size of leftSubtree + 1."
},
{
"code": null,
"e": 1333,
"s": 1276,
"text": "If root->data == x, return size of left subtree of root."
},
{
"code": null,
"e": 1379,
"s": 1333,
"text": "If x < root->data, return getRank(root->left)"
},
{
"code": null,
"e": 1453,
"s": 1379,
"text": "If x > root->data, return getRank(root->right) + size of leftSubtree + 1."
},
{
"code": null,
"e": 1478,
"s": 1453,
"text": "Below is the solution. "
},
{
"code": null,
"e": 1482,
"s": 1478,
"text": "C++"
},
{
"code": null,
"e": 1487,
"s": 1482,
"text": "Java"
},
{
"code": null,
"e": 1495,
"s": 1487,
"text": "Python3"
},
{
"code": null,
"e": 1498,
"s": 1495,
"text": "C#"
},
{
"code": null,
"e": 1509,
"s": 1498,
"text": "Javascript"
},
{
"code": "// CPP program to find rank of an// element in a stream.#include <bits/stdc++.h>using namespace std; struct Node { int data; Node *left, *right; int leftSize;}; Node* newNode(int data){ Node *temp = new Node; temp->data = data; temp->left = temp->right = NULL; temp->leftSize = 0; return temp;} // Inserting a new Node.Node* insert(Node*& root, int data){ if (!root) return newNode(data); // Updating size of left subtree. if (data <= root->data) { root->left = insert(root->left, data); root->leftSize++; } else root->right = insert(root->right, data); return root;} // Function to get Rank of a Node x.int getRank(Node* root, int x){ // Step 1. if (root->data == x) return root->leftSize; // Step 2. if (x < root->data) { if (!root->left) return -1; else return getRank(root->left, x); } // Step 3. else { if (!root->right) return -1; else { int rightSize = getRank(root->right, x); if(rightSize == -1 ) return -1; return root->leftSize + 1 + rightSize; } }} // Driver codeint main(){ int arr[] = { 5, 1, 4, 4, 5, 9, 7, 13, 3 }; int n = sizeof(arr) / sizeof(arr[0]); int x = 4; Node* root = NULL; for (int i = 0; i < n; i++) root = insert(root, arr[i]); cout << \"Rank of \" << x << \" in stream is: \" << getRank(root, x) << endl; x = 13; cout << \"Rank of \" << x << \" in stream is: \" << getRank(root, x) << endl; x = 8; cout << \"Rank of \" << x << \" in stream is: \" << getRank(root, x) << endl; return 0;}",
"e": 3189,
"s": 1509,
"text": null
},
{
"code": "// Java program to find rank of an// element in a stream.class GfG { static class Node { int data; Node left, right; int leftSize;} static Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.left = null; temp.right = null; temp.leftSize = 0; return temp;} // Inserting a new Node.static Node insert(Node root, int data){ if (root == null) return newNode(data); // Updating size of left subtree. if (data <= root.data) { root.left = insert(root.left, data); root.leftSize++; } else root.right = insert(root.right, data); return root;} // Function to get Rank of a Node x.static int getRank(Node root, int x){ // Step 1. if (root.data == x) return root.leftSize; // Step 2. if (x < root.data) { if (root.left == null) return -1; else return getRank(root.left, x); } // Step 3. else { if (root.right == null) return -1; else { int rightSize = getRank(root.right, x); if(rightSize == -1) return -1; return root.leftSize + 1 + rightSize; } }} // Driver codepublic static void main(String[] args){ int arr[] = { 5, 1, 4, 4, 5, 9, 7, 13, 3 }; int n = arr.length; int x = 4; Node root = null; for (int i = 0; i < n; i++) root = insert(root, arr[i]); System.out.println(\"Rank of \" + x + \" in stream is : \"+getRank(root, x)); x = 13; System.out.println(\"Rank of \" + x + \" in stream is : \"+getRank(root, x)); }}",
"e": 4750,
"s": 3189,
"text": null
},
{
"code": "# Python3 program to find rank of an# element in a stream. class newNode: def __init__(self, data): self.data = data self.left = self.right = None self.leftSize = 0 # Inserting a new Node.def insert(root, data): if root is None: return newNode(data) # Updating size of left subtree. if data <= root.data: root.left = insert(root.left, data) root.leftSize += 1 else: root.right = insert(root.right, data) return root # Function to get Rank of a Node x.def getRank(root, x): # Step 1. if root.data == x: return root.leftSize # Step 2. if x < root.data: if root.left is None: return -1 else: return getRank(root.left, x) # Step 3. else: if root.right is None: return -1 else: rightSize = getRank(root.right, x) if rightSize == -1: # x not found in right sub tree, i.e. not found in stream return -1 else: return root.leftSize + 1 + rightSize # Driver codeif __name__ == '__main__': arr = [5, 1, 4, 4, 5, 9, 7, 13, 3] n = len(arr) x = 4 root = None for i in range(n): root = insert(root, arr[i]) print(\"Rank of\", x, \"in stream is:\", getRank(root, x)) x = 13 print(\"Rank of\", x, \"in stream is:\", getRank(root, x)) x = 8 print(\"Rank of\", x, \"in stream is:\", getRank(root, x)) # This code is contributed by PranchalK",
"e": 6312,
"s": 4750,
"text": null
},
{
"code": "// C# program to find rank of an// element in a stream.using System; class GFG{public class Node{ public int data; public Node left, right; public int leftSize;} static Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.left = null; temp.right = null; temp.leftSize = 0; return temp;} // Inserting a new Node.static Node insert(Node root, int data){ if (root == null) return newNode(data); // Updating size of left subtree. if (data <= root.data) { root.left = insert(root.left, data); root.leftSize++; } else root.right = insert(root.right, data); return root;} // Function to get Rank of a Node x.static int getRank(Node root, int x){ // Step 1. if (root.data == x) return root.leftSize; // Step 2. if (x < root.data) { if (root.left == null) return -1; else return getRank(root.left, x); } // Step 3. else { if (root.right == null) return -1; else { int rightSize = getRank(root.right, x); if(rightSize == -1) return -1; return root.leftSize + 1 + rightSize; } }} // Driver codepublic static void Main(String[] args){ int []arr = { 5, 1, 4, 4, 5, 9, 7, 13, 3 }; int n = arr.Length; int x = 4; Node root = null; for (int i = 0; i < n; i++) root = insert(root, arr[i]); Console.WriteLine(\"Rank of \" + x + \" in stream is : \" + getRank(root, x)); x = 13; Console.WriteLine(\"Rank of \" + x + \" in stream is : \" + getRank(root, x));}} // This code is contributed by PrinciRaj1992",
"e": 8057,
"s": 6312,
"text": null
},
{
"code": "<script> // JavaScript program to find rank of an// element in a stream. class Node{ constructor() { this.data = 0; this.left = null; this.right = null; this.leftSize = 0; }} function newNode(data){ var temp = new Node(); temp.data = data; temp.left = null; temp.right = null; temp.leftSize = 0; return temp;} // Inserting a new Node.function insert(root, data){ if (root == null) return newNode(data); // Updating size of left subtree. if (data <= root.data) { root.left = insert(root.left, data); root.leftSize++; } else root.right = insert(root.right, data); return root;} // Function to get Rank of a Node x.function getRank(root, x){ // Step 1. if (root.data == x) return root.leftSize; // Step 2. if (x < root.data) { if (root.left == null) return -1; else return getRank(root.left, x); } // Step 3. else { if (root.right == null) return -1; else { var rightSize = getRank(root.right, x); if(rightSize == -1) return -1; return root.leftSize + 1 + rightSize; } }} // Driver codevar arr = [5, 1, 4, 4, 5, 9, 7, 13, 3];var n = arr.length;var x = 4;var root = null;for (var i = 0; i < n; i++) root = insert(root, arr[i]);document.write(\"Rank of \" + x + \" in stream is : \" + getRank(root, x) + \"<br>\");x = 13;document.write(\"Rank of \" + x + \" in stream is : \" + getRank(root, x)+\"<br>\");x = 8;document.write(\"Rank of \" + x + \" in stream is : \" + getRank(root, x)); </script>",
"e": 9798,
"s": 8057,
"text": null
},
{
"code": null,
"e": 9878,
"s": 9798,
"text": "Rank of 4 in stream is: 3\nRank of 13 in stream is: 8\nRank of 8 in stream is: -1"
},
{
"code": null,
"e": 10039,
"s": 9878,
"text": "Another approach: Traverse the array from the beginning. While traversing, count the nodes which is equal to or less than the given key.Print the count(Rank). "
},
{
"code": null,
"e": 10043,
"s": 10039,
"text": "C++"
},
{
"code": null,
"e": 10048,
"s": 10043,
"text": "Java"
},
{
"code": null,
"e": 10056,
"s": 10048,
"text": "Python3"
},
{
"code": null,
"e": 10059,
"s": 10056,
"text": "C#"
},
{
"code": null,
"e": 10063,
"s": 10059,
"text": "PHP"
},
{
"code": null,
"e": 10074,
"s": 10063,
"text": "Javascript"
},
{
"code": "// C++ program to find rank of an// element in a stream.#include <bits/stdc++.h>using namespace std; // Driver codeint main(){ int a[] = {5, 1, 14, 4, 15, 9, 7, 20, 11}; int key = 20; int arraySize = sizeof(a)/sizeof(a[0]); int count = 0; for(int i = 0; i < arraySize; i++) { if(a[i] <= key) { count += 1; } } cout << \"Rank of \" << key << \" in stream is: \" << count-1 << endl; return 0;} // This code is contributed by// Ashwin Loganathan.",
"e": 10584,
"s": 10074,
"text": null
},
{
"code": "// Java program to find rank of an// element in a stream.class GFG{ // Driver codepublic static void main(String[] args){ int a[] = {5, 1, 14, 4, 15, 9, 7, 20, 11}; int key = 20; int arraySize = a.length; int count = 0; for(int i = 0; i < arraySize; i++) { if(a[i] <= key) { count += 1; } } System.out.println(\"Rank of \" + key + \" in stream is: \" + (count - 1));}} // This code has been contributed by 29AjayKumar",
"e": 11073,
"s": 10584,
"text": null
},
{
"code": "# Python3 program to find rank of an# element in a stream. # Driver codeif __name__ == '__main__': a = [5, 1, 14, 4, 15, 9, 7, 20, 11] key = 20 arraySize = len(a) count = 0 for i in range(arraySize): if a[i] <= key: count += 1 print(\"Rank of\", key, \"in stream is:\", count - 1) # This code is contributed by PranchalK",
"e": 11459,
"s": 11073,
"text": null
},
{
"code": "// C# program to find rank of an// element in a stream.using System; class GFG{// Driver codepublic static void Main(){ int []a = {5, 1, 14, 4, 15, 9, 7, 20, 11}; int key = 20; int arraySize = a.Length; int count = 0; for(int i = 0; i < arraySize; i++) { if(a[i] <= key) { count += 1; } } Console.WriteLine(\"Rank of \" + key + \" in stream is: \" + (count - 1));}} // This code is contributed by// Akanksha Rai",
"e": 11971,
"s": 11459,
"text": null
},
{
"code": "<?php// PHP program to find rank of an// element in a stream. // Driver code$a = array(5, 1, 14, 4, 15, 9, 7, 20, 11);$key = 20;$arraySize = sizeof($a);$count = 0;for($i = 0; $i < $arraySize; $i++){ if($a[$i] <= $key) { $count += 1; }}echo \"Rank of \" . $key . \" in stream is: \" . ($count - 1) . \"\\n\"; // This code is contributed by// Akanksha Rai?>",
"e": 12341,
"s": 11971,
"text": null
},
{
"code": "<script>// javascript program to find rank of an// element in a stream. // Driver code var a = [ 5, 1, 14, 4, 15, 9, 7, 20, 11 ]; var key = 20; var arraySize = a.length; var count = 0; for (i = 0; i < arraySize; i++) { if (a[i] <= key) { count += 1; } } document.write(\"Rank of \" + key + \" in stream is: \" + (count - 1)); // This code contributed by umadevi9616</script>",
"e": 12806,
"s": 12341,
"text": null
},
{
"code": null,
"e": 12816,
"s": 12806,
"text": "Output: "
},
{
"code": null,
"e": 12843,
"s": 12816,
"text": "Rank of 20 in stream is: 8"
},
{
"code": null,
"e": 12858,
"s": 12845,
"text": "prerna saini"
},
{
"code": null,
"e": 12876,
"s": 12858,
"text": "Ashwin Loganathan"
},
{
"code": null,
"e": 12892,
"s": 12876,
"text": "PranchalKatiyar"
},
{
"code": null,
"e": 12905,
"s": 12892,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 12917,
"s": 12905,
"text": "29AjayKumar"
},
{
"code": null,
"e": 12931,
"s": 12917,
"text": "princiraj1992"
},
{
"code": null,
"e": 12943,
"s": 12931,
"text": "Nitish Jain"
},
{
"code": null,
"e": 12958,
"s": 12943,
"text": "mathew dominic"
},
{
"code": null,
"e": 12966,
"s": 12958,
"text": "wxy8955"
},
{
"code": null,
"e": 12978,
"s": 12966,
"text": "umadevi9616"
},
{
"code": null,
"e": 12988,
"s": 12978,
"text": "rutvik_56"
},
{
"code": null,
"e": 12995,
"s": 12988,
"text": "Arrays"
},
{
"code": null,
"e": 13014,
"s": 12995,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 13021,
"s": 13014,
"text": "Arrays"
},
{
"code": null,
"e": 13040,
"s": 13021,
"text": "Binary Search Tree"
}
] |
Binarytree Module in Python - GeeksforGeeks
|
25 Aug, 2021
A binary tree is a data structure in which every node or vertex has atmost two children. In Python, a binary tree can be represented in different ways with different data structures(dictionary, list) and class representation for a node. However, binarytree library helps to directly implement a binary tree. It also supports heap and binary search tree(BST). This module does not come pre-installed with Python’s standard utility module. To install it type the below command in the terminal.
pip install binarytree
The node class represents the structure of a particular node in the binary tree. The attributes of this class are values, left, right.
Syntax: binarytree.Node(value, left=None, right=None)Parameters: value: Contains the data for a node. This value must be number. left: Conatins the details of left node child. right: Contains details of the right node child.
Note: If left or right child node is not an instance of binarytree.Node class then binarytree.exceptions.NodeTypeError is raised and if the node value is not a number then binarytree.exceptions.NodeValueError is raised.Example:
Python3
from binarytree import Noderoot = Node(3)root.left = Node(6)root.right = Node(8) # Getting binary treeprint('Binary tree :', root) # Getting list of nodesprint('List of nodes :', list(root)) # Getting inorder of nodesprint('Inorder of nodes :', root.inorder) # Checking tree propertiesprint('Size of tree :', root.size)print('Height of tree :', root.height) # Get all properties at onceprint('Properties of tree : \n', root.properties)
Output:
Binary tree : 3 / \ 6 8List of nodes : [Node(3), Node(6), Node(8)]Inorder of nodes : [Node(6), Node(3), Node(8)]Size of tree : 3Height of tree : 1Properties of tree : {‘height’: 1, ‘size’: 3, ‘is_max_heap’: False, ‘is_min_heap’: True, ‘is_perfect’: True, ‘is_strict’: True, ‘is_complete’: True, ‘leaf_count’: 2, ‘min_node_value’: 3, ‘max_node_value’: 8, ‘min_leaf_depth’: 1, ‘max_leaf_depth’: 1, ‘is_bst’: False, ‘is_balanced’: True, ‘is_symmetric’: False}
Instead of using the Node method repeatedly, we can use build() method to convert a list of values into a binary tree. Here, a given list contains the nodes of tree such that the element at index i has its left child at index 2*i+1, the right child at index 2*i+2 and parent at (i – 1)//2. The elements at index j for j>len(list)//2 are leaf nodes. None indicates the absence of a node at that index. We can also get the list of nodes back after building a binary tree using values attribute.
Syntax: binarytree.build(values)Parameters: values: List representation of the binary tree.Returns: root of the binary tree.
Example:
Python3
# Creating binary tree# from given listfrom binarytree import build # List of nodesnodes =[3, 6, 8, 2, 11, None, 13] # Building the binary treebinary_tree = build(nodes)print('Binary tree from list :\n', binary_tree) # Getting list of nodes from# binarytreeprint('\nList from binary tree :', binary_tree.values)
Output:
Binary tree from list :
___3
/ \
6 8
/ \ \
2 11 13
List from binary tree : [3, 6, 8, 2, 11, None, 13]
tree() generates a random binary tree and returns its root node.
Syntax: binarytree.tree(height=3, is_perfect=False)Parameters: height: It is the height of the tree and its value can be between the range 0-9 (inclusive) is_perfect: If set True a perfect binary is created.Returns: Root node of the binary tree.
Example:
Python3
from binarytree import tree # Create a random binary# tree of any heightroot = tree()print("Binary tree of any height :")print(root) # Create a random binary# tree of given heightroot2 = tree(height = 2)print("Binary tree of given height :")print(root2) # Create a random perfect# binary tree of given heightroot3 = tree(height = 2, is_perfect = True)print("Perfect binary tree of given height :")print(root3)
Output:
Binary tree of any height :
14____
/ \
2 5__
/ / \
6 1 13
/ / / \
7 9 4 8
Binary tree of given height :
1__
/ \
5 2
/ \
4 3
Perfect binary tree of given height :
__3__
/ \
2 4
/ \ / \
6 0 1 5
The binary search tree is a special type of tree data structure whose inorder gives a sorted list of nodes or vertices. In Python, we can directly create a BST object using binarytree module. bst() generates a random binary search tree and return its root node.
Syntax: binarytree.bst(height=3, is_perfect=False)Parameters: height: It is the height of the tree and its value can be between the range 0-9 (inclusive) is_perfect: If set True a perfect binary is created.Returns: Root node of the BST.
Example:
Python3
from binarytree import bst # Create a random BST# of any heightroot = bst()print('BST of any height : \n', root) # Create a random BST of# given heightroot2 = bst(height = 2)print('BST of given height : \n', root2) # Create a random perfect# BST of given heightroot3 = bst(height = 2, is_perfect = True)print('Perfect BST of given height : \n', root3)
Output:
BST of any height :
____9______
/ \
__5__ ____12___
/ \ / \
2 8 10 _14
/ \ / \ /
1 4 7 11 13
BST of given height :
5
/ \
4 6
/
3
Perfect BST of given height :
__3__
/ \
1 5
/ \ / \
0 2 4 6
Heap is a tree data structure that can be of two types –
max heap
min heap
Using the heap() method of binarytree library, we can generate a random maxheap and return its root node. To generate minheap, we need to set the is_max attribute as False.
Syntax: binarytree.heap(height=3, is_max=True, is_perfect=False)Parameters: height: It is the height of the tree and its value can be between the range 0-9 (inclusive) is_max: If set True generates a max heap else min heap. is_perfect: If set True a perfect binary is created.Returns: Root node of the heap.
Python3
from binarytree import heap # Create a random max-heaproot = heap()print('Max-heap of any height : \n', root) # Create a random max-heap# of given heightroot2 = heap(height = 2) print('Max-heap of given height : \n', root2) # Create a random perfect# min-heap of given heightroot3 = heap(height = 2, is_max = False, is_perfect = True) print('Perfect min-heap of given height : \n', root3)
Output:
Max-heap of any height :
_______14______
/ \
___12__ __13__
/ \ / \
10 8 3 9
/ \ / \ / \ /
1 5 4 6 0 2 7
Max-heap of given height :
__6__
/ \
4 5
/ \ / \
2 0 1 3
Perfect min-heap of given height :
__0__
/ \
1 3
/ \ / \
2 6 4 5
kalrap615
Binary Tree
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
*args and **kwargs in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
|
[
{
"code": null,
"e": 23912,
"s": 23884,
"text": "\n25 Aug, 2021"
},
{
"code": null,
"e": 24405,
"s": 23912,
"text": "A binary tree is a data structure in which every node or vertex has atmost two children. In Python, a binary tree can be represented in different ways with different data structures(dictionary, list) and class representation for a node. However, binarytree library helps to directly implement a binary tree. It also supports heap and binary search tree(BST). This module does not come pre-installed with Python’s standard utility module. To install it type the below command in the terminal. "
},
{
"code": null,
"e": 24429,
"s": 24405,
"text": "pip install binarytree "
},
{
"code": null,
"e": 24565,
"s": 24429,
"text": "The node class represents the structure of a particular node in the binary tree. The attributes of this class are values, left, right. "
},
{
"code": null,
"e": 24792,
"s": 24565,
"text": "Syntax: binarytree.Node(value, left=None, right=None)Parameters: value: Contains the data for a node. This value must be number. left: Conatins the details of left node child. right: Contains details of the right node child. "
},
{
"code": null,
"e": 25020,
"s": 24792,
"text": "Note: If left or right child node is not an instance of binarytree.Node class then binarytree.exceptions.NodeTypeError is raised and if the node value is not a number then binarytree.exceptions.NodeValueError is raised.Example:"
},
{
"code": null,
"e": 25028,
"s": 25020,
"text": "Python3"
},
{
"code": "from binarytree import Noderoot = Node(3)root.left = Node(6)root.right = Node(8) # Getting binary treeprint('Binary tree :', root) # Getting list of nodesprint('List of nodes :', list(root)) # Getting inorder of nodesprint('Inorder of nodes :', root.inorder) # Checking tree propertiesprint('Size of tree :', root.size)print('Height of tree :', root.height) # Get all properties at onceprint('Properties of tree : \\n', root.properties)",
"e": 25464,
"s": 25028,
"text": null
},
{
"code": null,
"e": 25472,
"s": 25464,
"text": "Output:"
},
{
"code": null,
"e": 25929,
"s": 25472,
"text": "Binary tree : 3 / \\ 6 8List of nodes : [Node(3), Node(6), Node(8)]Inorder of nodes : [Node(6), Node(3), Node(8)]Size of tree : 3Height of tree : 1Properties of tree : {‘height’: 1, ‘size’: 3, ‘is_max_heap’: False, ‘is_min_heap’: True, ‘is_perfect’: True, ‘is_strict’: True, ‘is_complete’: True, ‘leaf_count’: 2, ‘min_node_value’: 3, ‘max_node_value’: 8, ‘min_leaf_depth’: 1, ‘max_leaf_depth’: 1, ‘is_bst’: False, ‘is_balanced’: True, ‘is_symmetric’: False}"
},
{
"code": null,
"e": 26425,
"s": 25931,
"text": "Instead of using the Node method repeatedly, we can use build() method to convert a list of values into a binary tree. Here, a given list contains the nodes of tree such that the element at index i has its left child at index 2*i+1, the right child at index 2*i+2 and parent at (i – 1)//2. The elements at index j for j>len(list)//2 are leaf nodes. None indicates the absence of a node at that index. We can also get the list of nodes back after building a binary tree using values attribute. "
},
{
"code": null,
"e": 26552,
"s": 26425,
"text": "Syntax: binarytree.build(values)Parameters: values: List representation of the binary tree.Returns: root of the binary tree. "
},
{
"code": null,
"e": 26562,
"s": 26552,
"text": "Example: "
},
{
"code": null,
"e": 26570,
"s": 26562,
"text": "Python3"
},
{
"code": "# Creating binary tree# from given listfrom binarytree import build # List of nodesnodes =[3, 6, 8, 2, 11, None, 13] # Building the binary treebinary_tree = build(nodes)print('Binary tree from list :\\n', binary_tree) # Getting list of nodes from# binarytreeprint('\\nList from binary tree :', binary_tree.values)",
"e": 26893,
"s": 26570,
"text": null
},
{
"code": null,
"e": 26901,
"s": 26893,
"text": "Output:"
},
{
"code": null,
"e": 27036,
"s": 26901,
"text": "Binary tree from list :\n \n ___3\n / \\\n 6 8\n / \\ \\\n2 11 13\n\n\nList from binary tree : [3, 6, 8, 2, 11, None, 13]"
},
{
"code": null,
"e": 27102,
"s": 27036,
"text": "tree() generates a random binary tree and returns its root node. "
},
{
"code": null,
"e": 27350,
"s": 27102,
"text": "Syntax: binarytree.tree(height=3, is_perfect=False)Parameters: height: It is the height of the tree and its value can be between the range 0-9 (inclusive) is_perfect: If set True a perfect binary is created.Returns: Root node of the binary tree. "
},
{
"code": null,
"e": 27359,
"s": 27350,
"text": "Example:"
},
{
"code": null,
"e": 27367,
"s": 27359,
"text": "Python3"
},
{
"code": "from binarytree import tree # Create a random binary# tree of any heightroot = tree()print(\"Binary tree of any height :\")print(root) # Create a random binary# tree of given heightroot2 = tree(height = 2)print(\"Binary tree of given height :\")print(root2) # Create a random perfect# binary tree of given heightroot3 = tree(height = 2, is_perfect = True)print(\"Perfect binary tree of given height :\")print(root3)",
"e": 27790,
"s": 27367,
"text": null
},
{
"code": null,
"e": 27799,
"s": 27790,
"text": "Output: "
},
{
"code": null,
"e": 28125,
"s": 27799,
"text": "Binary tree of any height :\n\n 14____\n / \\\n 2 5__\n / / \\\n 6 1 13\n / / / \\\n7 9 4 8\n\nBinary tree of given height :\n\n 1__\n / \\\n5 2\n / \\\n 4 3\n\nPerfect binary tree of given height :\n\n __3__\n / \\\n 2 4\n / \\ / \\\n6 0 1 5"
},
{
"code": null,
"e": 28388,
"s": 28125,
"text": "The binary search tree is a special type of tree data structure whose inorder gives a sorted list of nodes or vertices. In Python, we can directly create a BST object using binarytree module. bst() generates a random binary search tree and return its root node. "
},
{
"code": null,
"e": 28627,
"s": 28388,
"text": "Syntax: binarytree.bst(height=3, is_perfect=False)Parameters: height: It is the height of the tree and its value can be between the range 0-9 (inclusive) is_perfect: If set True a perfect binary is created.Returns: Root node of the BST. "
},
{
"code": null,
"e": 28636,
"s": 28627,
"text": "Example:"
},
{
"code": null,
"e": 28644,
"s": 28636,
"text": "Python3"
},
{
"code": "from binarytree import bst # Create a random BST# of any heightroot = bst()print('BST of any height : \\n', root) # Create a random BST of# given heightroot2 = bst(height = 2)print('BST of given height : \\n', root2) # Create a random perfect# BST of given heightroot3 = bst(height = 2, is_perfect = True)print('Perfect BST of given height : \\n', root3)",
"e": 29023,
"s": 28644,
"text": null
},
{
"code": null,
"e": 29031,
"s": 29023,
"text": "Output:"
},
{
"code": null,
"e": 29375,
"s": 29031,
"text": "BST of any height : \n \n ____9______\n / \\\n __5__ ____12___\n / \\ / \\\n 2 8 10 _14\n / \\ / \\ /\n1 4 7 11 13\n\nBST of given height : \n \n 5\n / \\\n 4 6\n /\n3\n\nPerfect BST of given height : \n \n __3__\n / \\\n 1 5\n / \\ / \\\n0 2 4 6"
},
{
"code": null,
"e": 29433,
"s": 29375,
"text": "Heap is a tree data structure that can be of two types – "
},
{
"code": null,
"e": 29443,
"s": 29433,
"text": "max heap "
},
{
"code": null,
"e": 29454,
"s": 29443,
"text": "min heap "
},
{
"code": null,
"e": 29628,
"s": 29454,
"text": "Using the heap() method of binarytree library, we can generate a random maxheap and return its root node. To generate minheap, we need to set the is_max attribute as False. "
},
{
"code": null,
"e": 29939,
"s": 29628,
"text": "Syntax: binarytree.heap(height=3, is_max=True, is_perfect=False)Parameters: height: It is the height of the tree and its value can be between the range 0-9 (inclusive) is_max: If set True generates a max heap else min heap. is_perfect: If set True a perfect binary is created.Returns: Root node of the heap. "
},
{
"code": null,
"e": 29947,
"s": 29939,
"text": "Python3"
},
{
"code": "from binarytree import heap # Create a random max-heaproot = heap()print('Max-heap of any height : \\n', root) # Create a random max-heap# of given heightroot2 = heap(height = 2) print('Max-heap of given height : \\n', root2) # Create a random perfect# min-heap of given heightroot3 = heap(height = 2, is_max = False, is_perfect = True) print('Perfect min-heap of given height : \\n', root3)",
"e": 30376,
"s": 29947,
"text": null
},
{
"code": null,
"e": 30384,
"s": 30376,
"text": "Output:"
},
{
"code": null,
"e": 30807,
"s": 30384,
"text": "Max-heap of any height : \n \n _______14______\n / \\\n ___12__ __13__\n / \\ / \\\n 10 8 3 9\n / \\ / \\ / \\ /\n1 5 4 6 0 2 7\n\nMax-heap of given height : \n \n __6__\n / \\\n 4 5\n / \\ / \\\n2 0 1 3\n\nPerfect min-heap of given height : \n \n __0__\n / \\\n 1 3\n / \\ / \\\n2 6 4 5"
},
{
"code": null,
"e": 30817,
"s": 30807,
"text": "kalrap615"
},
{
"code": null,
"e": 30829,
"s": 30817,
"text": "Binary Tree"
},
{
"code": null,
"e": 30844,
"s": 30829,
"text": "python-modules"
},
{
"code": null,
"e": 30851,
"s": 30844,
"text": "Python"
},
{
"code": null,
"e": 30949,
"s": 30851,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30967,
"s": 30949,
"text": "Python Dictionary"
},
{
"code": null,
"e": 30989,
"s": 30967,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 31021,
"s": 30989,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 31063,
"s": 31021,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 31089,
"s": 31063,
"text": "Python String | replace()"
},
{
"code": null,
"e": 31126,
"s": 31089,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 31170,
"s": 31126,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 31199,
"s": 31170,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 31241,
"s": 31199,
"text": "How To Convert Python Dictionary To JSON?"
}
] |
How to get the current open file line in Python?
|
Python doesn't support this directly. You could write a wrapper class for it. For example,
class FileLineWrapper(object):
def __init__(self, file):
self.f = file
self.curr_line = 0
def close(self):
return self.f.close()
def readline(self):
self.curr_line += 1
return self.f.readline()
# to allow using in 'with' statements
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
And use the above code as:
f = FileLineWrapper(open("my_file", "r"))
f.readline()
print(f.line)
This will give the output: 1
There are other methods to keep track of the line number if you are only using the readline method. For example,
f=open("my_file", "r")
for line_no, line in enumerate(f):
print line_no
f.close()
|
[
{
"code": null,
"e": 1153,
"s": 1062,
"text": "Python doesn't support this directly. You could write a wrapper class for it. For example,"
},
{
"code": null,
"e": 1558,
"s": 1153,
"text": "class FileLineWrapper(object):\n def __init__(self, file):\n self.f = file\n self.curr_line = 0\n def close(self):\n return self.f.close()\n def readline(self):\n self.curr_line += 1\n return self.f.readline()\n # to allow using in 'with' statements\n def __enter__(self):\n return self\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.close()"
},
{
"code": null,
"e": 1585,
"s": 1558,
"text": "And use the above code as:"
},
{
"code": null,
"e": 1654,
"s": 1585,
"text": "f = FileLineWrapper(open(\"my_file\", \"r\"))\nf.readline()\nprint(f.line)"
},
{
"code": null,
"e": 1683,
"s": 1654,
"text": "This will give the output: 1"
},
{
"code": null,
"e": 1796,
"s": 1683,
"text": "There are other methods to keep track of the line number if you are only using the readline method. For example,"
},
{
"code": null,
"e": 1882,
"s": 1796,
"text": "f=open(\"my_file\", \"r\")\nfor line_no, line in enumerate(f):\n print line_no\nf.close()"
}
] |
Kali Linux - Stressing Tools
|
Stressing tools are used to create DoS attacks or to create the stress test for different applications so as take appropriate measures for the future.
All the Stress testing tools are found in Applications → 02-Vulnerability Analysis → Stress testing.
All Stress testing test will be done on metsploitable machine which has IP of 192.168.1.102
Slowhttptest is one of the DoS attacking tools. It especially uses HTTP protocol to connect with the server and to keep the resources busy such as CPU and RAM. Let’s see in detail how to use it and explain its functions.
To open slowhttptest, first open the terminal and type “slowhttptest –parameters”.
You can type “slowhttptest –h” to see all the paramenters that you need to use. In case you receive an output, ‘Command not found’ you have to first type “apt-get install slowhttptest”.
Then after installation, again type slowhttptest –h
Type the following command −
slowhttptest -c 500 -H -g -o outputfile -i 10 -r 200 -t GET –u
http://192.168.1.202/index.php -x 24 -p 2
Where,
(-c 500) = 500 connections
(-c 500) = 500 connections
(-H) = Slowloris mode
(-H) = Slowloris mode
-g = Generate statistics
-g = Generate statistics
-o outputfile = Output file name
-o outputfile = Output file name
-i 10 = Use 10 seconds to wait for data
-i 10 = Use 10 seconds to wait for data
-r 200 = 200 connections with -t GET = GET requests
-r 200 = 200 connections with -t GET = GET requests
-u http://192.168.1.202/index.php = target URL
-u http://192.168.1.202/index.php = target URL
-x 24 = maximum of length of 24 bytes
-x 24 = maximum of length of 24 bytes
-p 2 = 2-second timeout
-p 2 = 2-second timeout
Once the test starts, the output will be as shown in the following screenshot, where you can notice that the service is available.
After a while, at the 287 connection the service goes down. This means that the server can handle a maximum of 287 HTTP connections.
Inviteflood is a SIP/SDP INVITE message flooding over UDP/IP. It executes on a variety of Linux distributions. It carries out DoS (Denial of Service) attacks against SIP devices by sending multiple INVITE requests.
To open Inviteflood, first open the terminal and type “inviteflood –parameters”
For help, you can use “inviteflood –h”
Next, you can use the following command −
inviteflood eth0 target_extension target_domain target_ip number_of_packets
Where,
target_extension is 2000
target_extension is 2000
target_domain is 192.168.x.x
target_domain is 192.168.x.x
target_ip is 192.168.x.x
target_ip is 192.168.x.x
number_of_packets is 1
number_of_packets is 1
-a is alias of SIP account
-a is alias of SIP account
Iaxflood is a VoIP DoS tool. To open it, type “iaxflood sourcename destinationname numpackets” in the terminal.
To know how to use, type “iaxflood –h”
THC-SSL-DOS is a tool to verify the performance of SSL. Establishing a secure SSL connection requires 15x more processing power on the server than on the client. THCSSL-DOS exploits this asymmetric property by overloading the server and knocking it off the Internet.
Following is the command −
thc-ssl-dos victimIP httpsport –accept
In this example, it will be −
thc-ssl-dos 192.168.1.1 443 –accept
Its output would be as follows −
84 Lectures
6.5 hours
Mohamad Mahjoub
8 Lectures
1 hours
Corey Charles
21 Lectures
4 hours
Atul Tiwari
55 Lectures
3 hours
Musab Zayadneh
29 Lectures
2 hours
Musab Zayadneh
32 Lectures
4 hours
Adnaan Arbaaz Ahmed
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2180,
"s": 2029,
"text": "Stressing tools are used to create DoS attacks or to create the stress test for different applications so as take appropriate measures for the future."
},
{
"code": null,
"e": 2281,
"s": 2180,
"text": "All the Stress testing tools are found in Applications → 02-Vulnerability Analysis → Stress testing."
},
{
"code": null,
"e": 2373,
"s": 2281,
"text": "All Stress testing test will be done on metsploitable machine which has IP of 192.168.1.102"
},
{
"code": null,
"e": 2594,
"s": 2373,
"text": "Slowhttptest is one of the DoS attacking tools. It especially uses HTTP protocol to connect with the server and to keep the resources busy such as CPU and RAM. Let’s see in detail how to use it and explain its functions."
},
{
"code": null,
"e": 2677,
"s": 2594,
"text": "To open slowhttptest, first open the terminal and type “slowhttptest –parameters”."
},
{
"code": null,
"e": 2863,
"s": 2677,
"text": "You can type “slowhttptest –h” to see all the paramenters that you need to use. In case you receive an output, ‘Command not found’ you have to first type “apt-get install slowhttptest”."
},
{
"code": null,
"e": 2915,
"s": 2863,
"text": "Then after installation, again type slowhttptest –h"
},
{
"code": null,
"e": 2944,
"s": 2915,
"text": "Type the following command −"
},
{
"code": null,
"e": 3051,
"s": 2944,
"text": "slowhttptest -c 500 -H -g -o outputfile -i 10 -r 200 -t GET –u \nhttp://192.168.1.202/index.php -x 24 -p 2\n"
},
{
"code": null,
"e": 3058,
"s": 3051,
"text": "Where,"
},
{
"code": null,
"e": 3085,
"s": 3058,
"text": "(-c 500) = 500 connections"
},
{
"code": null,
"e": 3112,
"s": 3085,
"text": "(-c 500) = 500 connections"
},
{
"code": null,
"e": 3134,
"s": 3112,
"text": "(-H) = Slowloris mode"
},
{
"code": null,
"e": 3156,
"s": 3134,
"text": "(-H) = Slowloris mode"
},
{
"code": null,
"e": 3181,
"s": 3156,
"text": "-g = Generate statistics"
},
{
"code": null,
"e": 3206,
"s": 3181,
"text": "-g = Generate statistics"
},
{
"code": null,
"e": 3239,
"s": 3206,
"text": "-o outputfile = Output file name"
},
{
"code": null,
"e": 3272,
"s": 3239,
"text": "-o outputfile = Output file name"
},
{
"code": null,
"e": 3312,
"s": 3272,
"text": "-i 10 = Use 10 seconds to wait for data"
},
{
"code": null,
"e": 3352,
"s": 3312,
"text": "-i 10 = Use 10 seconds to wait for data"
},
{
"code": null,
"e": 3405,
"s": 3352,
"text": "-r 200 = 200 connections with -t GET = GET requests "
},
{
"code": null,
"e": 3458,
"s": 3405,
"text": "-r 200 = 200 connections with -t GET = GET requests "
},
{
"code": null,
"e": 3505,
"s": 3458,
"text": "-u http://192.168.1.202/index.php = target URL"
},
{
"code": null,
"e": 3552,
"s": 3505,
"text": "-u http://192.168.1.202/index.php = target URL"
},
{
"code": null,
"e": 3590,
"s": 3552,
"text": "-x 24 = maximum of length of 24 bytes"
},
{
"code": null,
"e": 3628,
"s": 3590,
"text": "-x 24 = maximum of length of 24 bytes"
},
{
"code": null,
"e": 3652,
"s": 3628,
"text": "-p 2 = 2-second timeout"
},
{
"code": null,
"e": 3676,
"s": 3652,
"text": "-p 2 = 2-second timeout"
},
{
"code": null,
"e": 3807,
"s": 3676,
"text": "Once the test starts, the output will be as shown in the following screenshot, where you can notice that the service is available."
},
{
"code": null,
"e": 3940,
"s": 3807,
"text": "After a while, at the 287 connection the service goes down. This means that the server can handle a maximum of 287 HTTP connections."
},
{
"code": null,
"e": 4155,
"s": 3940,
"text": "Inviteflood is a SIP/SDP INVITE message flooding over UDP/IP. It executes on a variety of Linux distributions. It carries out DoS (Denial of Service) attacks against SIP devices by sending multiple INVITE requests."
},
{
"code": null,
"e": 4235,
"s": 4155,
"text": "To open Inviteflood, first open the terminal and type “inviteflood –parameters”"
},
{
"code": null,
"e": 4274,
"s": 4235,
"text": "For help, you can use “inviteflood –h”"
},
{
"code": null,
"e": 4316,
"s": 4274,
"text": "Next, you can use the following command −"
},
{
"code": null,
"e": 4394,
"s": 4316,
"text": "inviteflood eth0 target_extension target_domain target_ip number_of_packets\n"
},
{
"code": null,
"e": 4401,
"s": 4394,
"text": "Where,"
},
{
"code": null,
"e": 4426,
"s": 4401,
"text": "target_extension is 2000"
},
{
"code": null,
"e": 4451,
"s": 4426,
"text": "target_extension is 2000"
},
{
"code": null,
"e": 4480,
"s": 4451,
"text": "target_domain is 192.168.x.x"
},
{
"code": null,
"e": 4509,
"s": 4480,
"text": "target_domain is 192.168.x.x"
},
{
"code": null,
"e": 4534,
"s": 4509,
"text": "target_ip is 192.168.x.x"
},
{
"code": null,
"e": 4559,
"s": 4534,
"text": "target_ip is 192.168.x.x"
},
{
"code": null,
"e": 4582,
"s": 4559,
"text": "number_of_packets is 1"
},
{
"code": null,
"e": 4605,
"s": 4582,
"text": "number_of_packets is 1"
},
{
"code": null,
"e": 4632,
"s": 4605,
"text": "-a is alias of SIP account"
},
{
"code": null,
"e": 4659,
"s": 4632,
"text": "-a is alias of SIP account"
},
{
"code": null,
"e": 4771,
"s": 4659,
"text": "Iaxflood is a VoIP DoS tool. To open it, type “iaxflood sourcename destinationname numpackets” in the terminal."
},
{
"code": null,
"e": 4810,
"s": 4771,
"text": "To know how to use, type “iaxflood –h”"
},
{
"code": null,
"e": 5077,
"s": 4810,
"text": "THC-SSL-DOS is a tool to verify the performance of SSL. Establishing a secure SSL connection requires 15x more processing power on the server than on the client. THCSSL-DOS exploits this asymmetric property by overloading the server and knocking it off the Internet."
},
{
"code": null,
"e": 5104,
"s": 5077,
"text": "Following is the command −"
},
{
"code": null,
"e": 5145,
"s": 5104,
"text": "thc-ssl-dos victimIP httpsport –accept \n"
},
{
"code": null,
"e": 5175,
"s": 5145,
"text": "In this example, it will be −"
},
{
"code": null,
"e": 5213,
"s": 5175,
"text": "thc-ssl-dos 192.168.1.1 443 –accept \n"
},
{
"code": null,
"e": 5246,
"s": 5213,
"text": "Its output would be as follows −"
},
{
"code": null,
"e": 5281,
"s": 5246,
"text": "\n 84 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 5298,
"s": 5281,
"text": " Mohamad Mahjoub"
},
{
"code": null,
"e": 5330,
"s": 5298,
"text": "\n 8 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5345,
"s": 5330,
"text": " Corey Charles"
},
{
"code": null,
"e": 5378,
"s": 5345,
"text": "\n 21 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5391,
"s": 5378,
"text": " Atul Tiwari"
},
{
"code": null,
"e": 5424,
"s": 5391,
"text": "\n 55 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 5440,
"s": 5424,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 5473,
"s": 5440,
"text": "\n 29 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5489,
"s": 5473,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 5522,
"s": 5489,
"text": "\n 32 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5543,
"s": 5522,
"text": " Adnaan Arbaaz Ahmed"
},
{
"code": null,
"e": 5550,
"s": 5543,
"text": " Print"
},
{
"code": null,
"e": 5561,
"s": 5550,
"text": " Add Notes"
}
] |
Python program to fetch the indices of true values in a Boolean list
|
07 Jun, 2019
Given a list of only boolean values, write a Python program to fetch all the indices with True values from given list.
Let’s see certain ways to do this task.
Method #1: Using itertools [Pythonic way]
itertools.compress() function checks for all the elements in list and returns the list of indices with True values.
# Python program to fetch the indices# of true values in a Boolean listfrom itertools import compress # initializing list bool_list = [False, True, False, True, True, True] # printing given list print ("Given list is : " + str(bool_list)) # using itertools.compress() # to return true indices. res = list(compress(range(len(bool_list )), bool_list )) # printing result print ("Indices having True values are : " + str(res))
Given list is : [False, True, False, True, True, True]
Indices having True values are : [1, 3, 4, 5]
Method #2: Using enumerate() method
enumerate() method hashes the index with its value and coupled with list comprehension can let us check for the true values.
# Python program to fetch the indices# of true values in a Boolean list # initializing list bool_list = [False, True, False, True, True, True] # printing given list print ("Given list is : " + str(bool_list)) # using enumerate() + list comprehension # to return true indices. res = [i for i, val in enumerate(bool_list) if val] # printing result print ("Indices having True values are : " + str(res))
Given list is : [False, True, False, True, True, True]
Indices having True values are : [1, 3, 4, 5]
Method #3: Using filter() + range()
# Python program to fetch the indices# of true values in a Boolean list # initializing list bool_list = [False, True, False, True, True, True] # printing given list print ("Given list is : " + str(bool_list)) # using lambda + filter() + range() # to return true indices. res = list(filter(lambda i: bool_list[i], range(len(bool_list)))) # printing result print ("Indices having True values are : " + str(res))
Given list is : [False, True, False, True, True, True]
Indices having True values are : [1, 3, 4, 5]
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate over a list in Python
Rotate axis tick labels in Seaborn and Matplotlib
Enumerate() in Python
Deque in Python
Stack in Python
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Iterate over characters of a string in Python
Python | Convert set into a list
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Jun, 2019"
},
{
"code": null,
"e": 147,
"s": 28,
"text": "Given a list of only boolean values, write a Python program to fetch all the indices with True values from given list."
},
{
"code": null,
"e": 187,
"s": 147,
"text": "Let’s see certain ways to do this task."
},
{
"code": null,
"e": 229,
"s": 187,
"text": "Method #1: Using itertools [Pythonic way]"
},
{
"code": null,
"e": 345,
"s": 229,
"text": "itertools.compress() function checks for all the elements in list and returns the list of indices with True values."
},
{
"code": "# Python program to fetch the indices# of true values in a Boolean listfrom itertools import compress # initializing list bool_list = [False, True, False, True, True, True] # printing given list print (\"Given list is : \" + str(bool_list)) # using itertools.compress() # to return true indices. res = list(compress(range(len(bool_list )), bool_list )) # printing result print (\"Indices having True values are : \" + str(res)) ",
"e": 790,
"s": 345,
"text": null
},
{
"code": null,
"e": 892,
"s": 790,
"text": "Given list is : [False, True, False, True, True, True]\nIndices having True values are : [1, 3, 4, 5]\n"
},
{
"code": null,
"e": 930,
"s": 894,
"text": "Method #2: Using enumerate() method"
},
{
"code": null,
"e": 1055,
"s": 930,
"text": "enumerate() method hashes the index with its value and coupled with list comprehension can let us check for the true values."
},
{
"code": "# Python program to fetch the indices# of true values in a Boolean list # initializing list bool_list = [False, True, False, True, True, True] # printing given list print (\"Given list is : \" + str(bool_list)) # using enumerate() + list comprehension # to return true indices. res = [i for i, val in enumerate(bool_list) if val] # printing result print (\"Indices having True values are : \" + str(res)) ",
"e": 1476,
"s": 1055,
"text": null
},
{
"code": null,
"e": 1578,
"s": 1476,
"text": "Given list is : [False, True, False, True, True, True]\nIndices having True values are : [1, 3, 4, 5]\n"
},
{
"code": null,
"e": 1616,
"s": 1580,
"text": "Method #3: Using filter() + range()"
},
{
"code": "# Python program to fetch the indices# of true values in a Boolean list # initializing list bool_list = [False, True, False, True, True, True] # printing given list print (\"Given list is : \" + str(bool_list)) # using lambda + filter() + range() # to return true indices. res = list(filter(lambda i: bool_list[i], range(len(bool_list)))) # printing result print (\"Indices having True values are : \" + str(res)) ",
"e": 2044,
"s": 1616,
"text": null
},
{
"code": null,
"e": 2146,
"s": 2044,
"text": "Given list is : [False, True, False, True, True, True]\nIndices having True values are : [1, 3, 4, 5]\n"
},
{
"code": null,
"e": 2167,
"s": 2146,
"text": "Python list-programs"
},
{
"code": null,
"e": 2174,
"s": 2167,
"text": "Python"
},
{
"code": null,
"e": 2190,
"s": 2174,
"text": "Python Programs"
},
{
"code": null,
"e": 2288,
"s": 2190,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2318,
"s": 2288,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 2368,
"s": 2318,
"text": "Rotate axis tick labels in Seaborn and Matplotlib"
},
{
"code": null,
"e": 2390,
"s": 2368,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2406,
"s": 2390,
"text": "Deque in Python"
},
{
"code": null,
"e": 2422,
"s": 2406,
"text": "Stack in Python"
},
{
"code": null,
"e": 2444,
"s": 2422,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2490,
"s": 2444,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 2529,
"s": 2490,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2575,
"s": 2529,
"text": "Iterate over characters of a string in Python"
}
] |
Number of substrings of a string
|
31 May, 2022
Find total number of non-empty substrings of a string with N characters.
Input : str = “abc” Output : 6 Every substring of the given string : “a”, “b”, “c”, “ab”, “bc”, “abc”
Input : str = “abcd” Output : 10 Every substring of the given string : “a”, “b”, “c”, “d”, “ab”, “bc”, “cd”, “abc”, “bcd” and “abcd”
Count of non-empty substrings is n*(n+1)/2If we include empty string also as substring, the count becomes n*(n+1)/2 + 1
How does above formula work?
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Number of substrings of length one is n (We can choose any of the n characters)Number of substrings of length two is n-1 (We can choose any of the n-1 pairs formed by adjacent)Number of substrings of length three is n-2 (We can choose any of the n-2 triplets formed by adjacent)In general, number of substrings of length k is n-k+1 where 1 <= k <= n
Number of substrings of length one is n (We can choose any of the n characters)
Number of substrings of length two is n-1 (We can choose any of the n-1 pairs formed by adjacent)
Number of substrings of length three is n-2 (We can choose any of the n-2 triplets formed by adjacent)
In general, number of substrings of length k is n-k+1 where 1 <= k <= n
Total number of substrings of all lengths from 1 to n = n + (n-1) + (n-2) + (n-3) + ... 2 + 1 = n * (n + 1)/2
C++
Java
Python3
C#
PHP
Javascript
// CPP program to count number of substrings// of a string#include <bits/stdc++.h>using namespace std; int countNonEmptySubstr(string str){ int n = str.length(); return n*(n+1)/2;} // driver codeint main(){ string s = "abcde"; cout << countNonEmptySubstr(s); return 0;}
// Java program to count number of substrings// of a stringimport java.io.*; public class GFG { static int countNonEmptySubstr(String str) { int n = str.length(); return n * (n + 1) / 2; } // Driver code public static void main(String args[]) { String s = "abcde"; System.out.println( countNonEmptySubstr(s)); }} // This code is contributed// by Manish Shaw (manishshaw1)
# Python3 program to count number# of substrings of a string def countNonEmptySubstr(str): n = len(str); return int(n * (n + 1) / 2); # driver codes = "abcde";print (countNonEmptySubstr(s)); # This code is contributed by# Manish Shaw (manishshaw1)
// C# program to count number// of substrings of a stringusing System;class GFG { static int countNonEmptySubstr(string str) { int n = str.Length; return n * (n + 1) / 2; } // Driver Code public static void Main() { string s = "abcde"; Console.Write(countNonEmptySubstr(s)); }} // This code is contributed// by Manish Shaw (manishshaw1)
<?php// PHP program to count number// of substrings of a string function countNonEmptySubstr($str){ $n = strlen($str); return $n * ($n + 1) / 2;} // Driver Code$s = "abcde";echo countNonEmptySubstr($s); // This code is contributed by Anuj_67?>
<script> // JavaScript program to count number of substrings// of a stringfunction countNonEmptySubstr(str) { let n = str.length; return n * (n + 1) / 2; } // Driver code let s = "abcde"; document.write(countNonEmptySubstr(s)); // This code is contributed shivanisinghss2110 </script>
15
Time Complexity: O(1).
Auxiliary Space: O(1).
https://youtu.be/9QxJo
-g0cMA
manishshaw1
vt_m
praveenkumar14
surinderdawra388
shivanisinghss2110
anandkumarshivam2266
Mathematical
Strings
Strings
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n31 May, 2022"
},
{
"code": null,
"e": 126,
"s": 52,
"text": "Find total number of non-empty substrings of a string with N characters. "
},
{
"code": null,
"e": 228,
"s": 126,
"text": "Input : str = “abc” Output : 6 Every substring of the given string : “a”, “b”, “c”, “ab”, “bc”, “abc”"
},
{
"code": null,
"e": 361,
"s": 228,
"text": "Input : str = “abcd” Output : 10 Every substring of the given string : “a”, “b”, “c”, “d”, “ab”, “bc”, “cd”, “abc”, “bcd” and “abcd”"
},
{
"code": null,
"e": 481,
"s": 361,
"text": "Count of non-empty substrings is n*(n+1)/2If we include empty string also as substring, the count becomes n*(n+1)/2 + 1"
},
{
"code": null,
"e": 512,
"s": 481,
"text": "How does above formula work? "
},
{
"code": null,
"e": 521,
"s": 512,
"text": "Chapters"
},
{
"code": null,
"e": 548,
"s": 521,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 598,
"s": 548,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 621,
"s": 598,
"text": "captions off, selected"
},
{
"code": null,
"e": 629,
"s": 621,
"text": "English"
},
{
"code": null,
"e": 653,
"s": 629,
"text": "This is a modal window."
},
{
"code": null,
"e": 722,
"s": 653,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 744,
"s": 722,
"text": "End of dialog window."
},
{
"code": null,
"e": 1094,
"s": 744,
"text": "Number of substrings of length one is n (We can choose any of the n characters)Number of substrings of length two is n-1 (We can choose any of the n-1 pairs formed by adjacent)Number of substrings of length three is n-2 (We can choose any of the n-2 triplets formed by adjacent)In general, number of substrings of length k is n-k+1 where 1 <= k <= n"
},
{
"code": null,
"e": 1174,
"s": 1094,
"text": "Number of substrings of length one is n (We can choose any of the n characters)"
},
{
"code": null,
"e": 1272,
"s": 1174,
"text": "Number of substrings of length two is n-1 (We can choose any of the n-1 pairs formed by adjacent)"
},
{
"code": null,
"e": 1375,
"s": 1272,
"text": "Number of substrings of length three is n-2 (We can choose any of the n-2 triplets formed by adjacent)"
},
{
"code": null,
"e": 1447,
"s": 1375,
"text": "In general, number of substrings of length k is n-k+1 where 1 <= k <= n"
},
{
"code": null,
"e": 1557,
"s": 1447,
"text": "Total number of substrings of all lengths from 1 to n = n + (n-1) + (n-2) + (n-3) + ... 2 + 1 = n * (n + 1)/2"
},
{
"code": null,
"e": 1561,
"s": 1557,
"text": "C++"
},
{
"code": null,
"e": 1566,
"s": 1561,
"text": "Java"
},
{
"code": null,
"e": 1574,
"s": 1566,
"text": "Python3"
},
{
"code": null,
"e": 1577,
"s": 1574,
"text": "C#"
},
{
"code": null,
"e": 1581,
"s": 1577,
"text": "PHP"
},
{
"code": null,
"e": 1592,
"s": 1581,
"text": "Javascript"
},
{
"code": "// CPP program to count number of substrings// of a string#include <bits/stdc++.h>using namespace std; int countNonEmptySubstr(string str){ int n = str.length(); return n*(n+1)/2;} // driver codeint main(){ string s = \"abcde\"; cout << countNonEmptySubstr(s); return 0;}",
"e": 1875,
"s": 1592,
"text": null
},
{
"code": "// Java program to count number of substrings// of a stringimport java.io.*; public class GFG { static int countNonEmptySubstr(String str) { int n = str.length(); return n * (n + 1) / 2; } // Driver code public static void main(String args[]) { String s = \"abcde\"; System.out.println( countNonEmptySubstr(s)); }} // This code is contributed// by Manish Shaw (manishshaw1)",
"e": 2323,
"s": 1875,
"text": null
},
{
"code": "# Python3 program to count number# of substrings of a string def countNonEmptySubstr(str): n = len(str); return int(n * (n + 1) / 2); # driver codes = \"abcde\";print (countNonEmptySubstr(s)); # This code is contributed by# Manish Shaw (manishshaw1)",
"e": 2577,
"s": 2323,
"text": null
},
{
"code": "// C# program to count number// of substrings of a stringusing System;class GFG { static int countNonEmptySubstr(string str) { int n = str.Length; return n * (n + 1) / 2; } // Driver Code public static void Main() { string s = \"abcde\"; Console.Write(countNonEmptySubstr(s)); }} // This code is contributed// by Manish Shaw (manishshaw1)",
"e": 2973,
"s": 2577,
"text": null
},
{
"code": "<?php// PHP program to count number// of substrings of a string function countNonEmptySubstr($str){ $n = strlen($str); return $n * ($n + 1) / 2;} // Driver Code$s = \"abcde\";echo countNonEmptySubstr($s); // This code is contributed by Anuj_67?>",
"e": 3227,
"s": 2973,
"text": null
},
{
"code": "<script> // JavaScript program to count number of substrings// of a stringfunction countNonEmptySubstr(str) { let n = str.length; return n * (n + 1) / 2; } // Driver code let s = \"abcde\"; document.write(countNonEmptySubstr(s)); // This code is contributed shivanisinghss2110 </script>",
"e": 3555,
"s": 3227,
"text": null
},
{
"code": null,
"e": 3558,
"s": 3555,
"text": "15"
},
{
"code": null,
"e": 3583,
"s": 3560,
"text": "Time Complexity: O(1)."
},
{
"code": null,
"e": 3606,
"s": 3583,
"text": "Auxiliary Space: O(1)."
},
{
"code": null,
"e": 3629,
"s": 3606,
"text": "https://youtu.be/9QxJo"
},
{
"code": null,
"e": 3637,
"s": 3629,
"text": "-g0cMA "
},
{
"code": null,
"e": 3649,
"s": 3637,
"text": "manishshaw1"
},
{
"code": null,
"e": 3654,
"s": 3649,
"text": "vt_m"
},
{
"code": null,
"e": 3669,
"s": 3654,
"text": "praveenkumar14"
},
{
"code": null,
"e": 3686,
"s": 3669,
"text": "surinderdawra388"
},
{
"code": null,
"e": 3705,
"s": 3686,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 3726,
"s": 3705,
"text": "anandkumarshivam2266"
},
{
"code": null,
"e": 3739,
"s": 3726,
"text": "Mathematical"
},
{
"code": null,
"e": 3747,
"s": 3739,
"text": "Strings"
},
{
"code": null,
"e": 3755,
"s": 3747,
"text": "Strings"
},
{
"code": null,
"e": 3768,
"s": 3755,
"text": "Mathematical"
}
] |
Python Pillow - Using Image Module
|
To display the image, pillow library is using an image class within it. The image module inside pillow package contains some important inbuilt functions like, load images or create new images, etc.
To load the image, we simply import the image module from the pillow and call the Image.open(), passing the image filename.
Instead of calling the Pillow module, we will call the PIL module as to make it backward compatible with an older module called Python Imaging Library (PIL). That’s why our code starts with “from PIL import Image” instead of “from Pillow import Image”.
Next, we’re going to load the image by calling the Image.open() function, which returns a value of the Image object data type. Any modification we make to the image object can be saved to an image file with the save() method. The image object we received using Image.open(), later can be used to resize, crop, draw or other image manipulation method calls on this Image object.
Following example demonstrates the rotation of an image using python pillow −
from PIL import Image
#Open image using Image module
im = Image.open("images/cuba.jpg")
#Show actual Image
im.show()
#Show rotated Image
im = im.rotate(45)
im.show()
If you save the above program as Example.py and execute, it displays the original and rotated images using standard PNG display utility, as follows −
Actual image
Rotated image (45 degrees)
The instance of the Image class has some attributes. Let’s try to understand few of them by example −
This function is used to get the file name or the path of the image.
>>>image = Image.open('beach1.jpg')
>>> image.filename
'beach1.jpg'
This function returns file format of the image file like ‘JPEG’, ‘BMP’, ‘PNG’, etc.
>>> image = Image.open('beach1.jpg')
>>>
>>> image.format
'JPEG'
It is used to get the pixel format used by the image. Typical values are “1”, “L”, “RGB” or “CMYK”.
>>> image.mode
'RGB'
It returns the tuple consist of height & weight of the image.
>>> image.size
(1280, 721)
It returns only the width of the image.
>>> image.width
1280
It returns only the height of the image.
>>> image.height
721
It returns a dictionary holding data associated with the image.
>>> image.info
{'jfif': 257, 'jfif_version': (1, 1), 'dpi': (300, 300), 'jfif_unit': 1, 'jfif_density': (300, 300), 'exif': b"Exif\x00\x00MM\x00*\x00\x00\x00
....
....
\xeb\x00\x00'\x10\x00\x00\xd7\xb3\x00\x00\x03\xe8"}
It returns the colour palette table, if any.
>>> image.palette
Output above − None
|
[
{
"code": null,
"e": 2532,
"s": 2334,
"text": "To display the image, pillow library is using an image class within it. The image module inside pillow package contains some important inbuilt functions like, load images or create new images, etc."
},
{
"code": null,
"e": 2656,
"s": 2532,
"text": "To load the image, we simply import the image module from the pillow and call the Image.open(), passing the image filename."
},
{
"code": null,
"e": 2909,
"s": 2656,
"text": "Instead of calling the Pillow module, we will call the PIL module as to make it backward compatible with an older module called Python Imaging Library (PIL). That’s why our code starts with “from PIL import Image” instead of “from Pillow import Image”."
},
{
"code": null,
"e": 3287,
"s": 2909,
"text": "Next, we’re going to load the image by calling the Image.open() function, which returns a value of the Image object data type. Any modification we make to the image object can be saved to an image file with the save() method. The image object we received using Image.open(), later can be used to resize, crop, draw or other image manipulation method calls on this Image object."
},
{
"code": null,
"e": 3365,
"s": 3287,
"text": "Following example demonstrates the rotation of an image using python pillow −"
},
{
"code": null,
"e": 3531,
"s": 3365,
"text": "from PIL import Image\n#Open image using Image module\nim = Image.open(\"images/cuba.jpg\")\n#Show actual Image\nim.show()\n#Show rotated Image\nim = im.rotate(45)\nim.show()"
},
{
"code": null,
"e": 3681,
"s": 3531,
"text": "If you save the above program as Example.py and execute, it displays the original and rotated images using standard PNG display utility, as follows −"
},
{
"code": null,
"e": 3694,
"s": 3681,
"text": "Actual image"
},
{
"code": null,
"e": 3721,
"s": 3694,
"text": "Rotated image (45 degrees)"
},
{
"code": null,
"e": 3823,
"s": 3721,
"text": "The instance of the Image class has some attributes. Let’s try to understand few of them by example −"
},
{
"code": null,
"e": 3892,
"s": 3823,
"text": "This function is used to get the file name or the path of the image."
},
{
"code": null,
"e": 3961,
"s": 3892,
"text": ">>>image = Image.open('beach1.jpg')\n>>> image.filename\n'beach1.jpg'\n"
},
{
"code": null,
"e": 4045,
"s": 3961,
"text": "This function returns file format of the image file like ‘JPEG’, ‘BMP’, ‘PNG’, etc."
},
{
"code": null,
"e": 4111,
"s": 4045,
"text": ">>> image = Image.open('beach1.jpg')\n>>>\n>>> image.format\n'JPEG'\n"
},
{
"code": null,
"e": 4211,
"s": 4111,
"text": "It is used to get the pixel format used by the image. Typical values are “1”, “L”, “RGB” or “CMYK”."
},
{
"code": null,
"e": 4233,
"s": 4211,
"text": ">>> image.mode\n'RGB'\n"
},
{
"code": null,
"e": 4295,
"s": 4233,
"text": "It returns the tuple consist of height & weight of the image."
},
{
"code": null,
"e": 4323,
"s": 4295,
"text": ">>> image.size\n(1280, 721)\n"
},
{
"code": null,
"e": 4363,
"s": 4323,
"text": "It returns only the width of the image."
},
{
"code": null,
"e": 4385,
"s": 4363,
"text": ">>> image.width\n1280\n"
},
{
"code": null,
"e": 4426,
"s": 4385,
"text": "It returns only the height of the image."
},
{
"code": null,
"e": 4448,
"s": 4426,
"text": ">>> image.height\n721\n"
},
{
"code": null,
"e": 4512,
"s": 4448,
"text": "It returns a dictionary holding data associated with the image."
},
{
"code": null,
"e": 4733,
"s": 4512,
"text": ">>> image.info\n{'jfif': 257, 'jfif_version': (1, 1), 'dpi': (300, 300), 'jfif_unit': 1, 'jfif_density': (300, 300), 'exif': b\"Exif\\x00\\x00MM\\x00*\\x00\\x00\\x00\n....\n....\n\\xeb\\x00\\x00'\\x10\\x00\\x00\\xd7\\xb3\\x00\\x00\\x03\\xe8\"}\n"
},
{
"code": null,
"e": 4778,
"s": 4733,
"text": "It returns the colour palette table, if any."
},
{
"code": null,
"e": 4797,
"s": 4778,
"text": ">>> image.palette\n"
}
] |
R - XML Files
|
XML is a file format which shares both the file format and the data on the World Wide Web, intranets, and elsewhere using standard ASCII text. It stands for Extensible Markup Language (XML). Similar to HTML it contains markup tags. But unlike HTML where the markup tag describes structure of the page, in xml the markup tags describe the meaning of the data contained into he file.
You can read a xml file in R using the "XML" package. This package can be installed using following command.
install.packages("XML")
Create a XMl file by copying the below data into a text editor like notepad. Save the file with a .xml extension and choosing the file type as all files(*.*).
<RECORDS>
<EMPLOYEE>
<ID>1</ID>
<NAME>Rick</NAME>
<SALARY>623.3</SALARY>
<STARTDATE>1/1/2012</STARTDATE>
<DEPT>IT</DEPT>
</EMPLOYEE>
<EMPLOYEE>
<ID>2</ID>
<NAME>Dan</NAME>
<SALARY>515.2</SALARY>
<STARTDATE>9/23/2013</STARTDATE>
<DEPT>Operations</DEPT>
</EMPLOYEE>
<EMPLOYEE>
<ID>3</ID>
<NAME>Michelle</NAME>
<SALARY>611</SALARY>
<STARTDATE>11/15/2014</STARTDATE>
<DEPT>IT</DEPT>
</EMPLOYEE>
<EMPLOYEE>
<ID>4</ID>
<NAME>Ryan</NAME>
<SALARY>729</SALARY>
<STARTDATE>5/11/2014</STARTDATE>
<DEPT>HR</DEPT>
</EMPLOYEE>
<EMPLOYEE>
<ID>5</ID>
<NAME>Gary</NAME>
<SALARY>843.25</SALARY>
<STARTDATE>3/27/2015</STARTDATE>
<DEPT>Finance</DEPT>
</EMPLOYEE>
<EMPLOYEE>
<ID>6</ID>
<NAME>Nina</NAME>
<SALARY>578</SALARY>
<STARTDATE>5/21/2013</STARTDATE>
<DEPT>IT</DEPT>
</EMPLOYEE>
<EMPLOYEE>
<ID>7</ID>
<NAME>Simon</NAME>
<SALARY>632.8</SALARY>
<STARTDATE>7/30/2013</STARTDATE>
<DEPT>Operations</DEPT>
</EMPLOYEE>
<EMPLOYEE>
<ID>8</ID>
<NAME>Guru</NAME>
<SALARY>722.5</SALARY>
<STARTDATE>6/17/2014</STARTDATE>
<DEPT>Finance</DEPT>
</EMPLOYEE>
</RECORDS>
The xml file is read by R using the function xmlParse(). It is stored as a list in R.
# Load the package required to read XML files.
library("XML")
# Also load the other required package.
library("methods")
# Give the input file name to the function.
result <- xmlParse(file = "input.xml")
# Print the result.
print(result)
When we execute the above code, it produces the following result −
1
Rick
623.3
1/1/2012
IT
2
Dan
515.2
9/23/2013
Operations
3
Michelle
611
11/15/2014
IT
4
Ryan
729
5/11/2014
HR
5
Gary
843.25
3/27/2015
Finance
6
Nina
578
5/21/2013
IT
7
Simon
632.8
7/30/2013
Operations
8
Guru
722.5
6/17/2014
Finance
# Load the packages required to read XML files.
library("XML")
library("methods")
# Give the input file name to the function.
result <- xmlParse(file = "input.xml")
# Exract the root node form the xml file.
rootnode <- xmlRoot(result)
# Find number of nodes in the root.
rootsize <- xmlSize(rootnode)
# Print the result.
print(rootsize)
When we execute the above code, it produces the following result −
output
[1] 8
Let's look at the first record of the parsed file. It will give us an idea of the various elements present in the top level node.
# Load the packages required to read XML files.
library("XML")
library("methods")
# Give the input file name to the function.
result <- xmlParse(file = "input.xml")
# Exract the root node form the xml file.
rootnode <- xmlRoot(result)
# Print the result.
print(rootnode[1])
When we execute the above code, it produces the following result −
$EMPLOYEE
1
Rick
623.3
1/1/2012
IT
attr(,"class")
[1] "XMLInternalNodeList" "XMLNodeList"
# Load the packages required to read XML files.
library("XML")
library("methods")
# Give the input file name to the function.
result <- xmlParse(file = "input.xml")
# Exract the root node form the xml file.
rootnode <- xmlRoot(result)
# Get the first element of the first node.
print(rootnode[[1]][[1]])
# Get the fifth element of the first node.
print(rootnode[[1]][[5]])
# Get the second element of the third node.
print(rootnode[[3]][[2]])
When we execute the above code, it produces the following result −
1
IT
Michelle
To handle the data effectively in large files we read the data in the xml file as a data frame. Then process the data frame for data analysis.
# Load the packages required to read XML files.
library("XML")
library("methods")
# Convert the input xml file to a data frame.
xmldataframe <- xmlToDataFrame("input.xml")
print(xmldataframe)
When we execute the above code, it produces the following result −
ID NAME SALARY STARTDATE DEPT
1 1 Rick 623.30 2012-01-01 IT
2 2 Dan 515.20 2013-09-23 Operations
3 3 Michelle 611.00 2014-11-15 IT
4 4 Ryan 729.00 2014-05-11 HR
5 NA Gary 843.25 2015-03-27 Finance
6 6 Nina 578.00 2013-05-21 IT
7 7 Simon 632.80 2013-07-30 Operations
8 8 Guru 722.50 2014-06-17 Finance
As the data is now available as a dataframe we can use data frame related function to read and manipulate the file.
|
[
{
"code": null,
"e": 2918,
"s": 2536,
"text": "XML is a file format which shares both the file format and the data on the World Wide Web, intranets, and elsewhere using standard ASCII text. It stands for Extensible Markup Language (XML). Similar to HTML it contains markup tags. But unlike HTML where the markup tag describes structure of the page, in xml the markup tags describe the meaning of the data contained into he file."
},
{
"code": null,
"e": 3027,
"s": 2918,
"text": "You can read a xml file in R using the \"XML\" package. This package can be installed using following command."
},
{
"code": null,
"e": 3052,
"s": 3027,
"text": "install.packages(\"XML\")\n"
},
{
"code": null,
"e": 3211,
"s": 3052,
"text": "Create a XMl file by copying the below data into a text editor like notepad. Save the file with a .xml extension and choosing the file type as all files(*.*)."
},
{
"code": null,
"e": 4565,
"s": 3211,
"text": "<RECORDS>\n <EMPLOYEE>\n <ID>1</ID>\n <NAME>Rick</NAME>\n <SALARY>623.3</SALARY>\n <STARTDATE>1/1/2012</STARTDATE>\n <DEPT>IT</DEPT>\n </EMPLOYEE>\n\t\n <EMPLOYEE>\n <ID>2</ID>\n <NAME>Dan</NAME>\n <SALARY>515.2</SALARY>\n <STARTDATE>9/23/2013</STARTDATE>\n <DEPT>Operations</DEPT>\n </EMPLOYEE>\n \n <EMPLOYEE>\n <ID>3</ID>\n <NAME>Michelle</NAME>\n <SALARY>611</SALARY>\n <STARTDATE>11/15/2014</STARTDATE>\n <DEPT>IT</DEPT>\n </EMPLOYEE>\n \n <EMPLOYEE>\n <ID>4</ID>\n <NAME>Ryan</NAME>\n <SALARY>729</SALARY>\n <STARTDATE>5/11/2014</STARTDATE>\n <DEPT>HR</DEPT>\n </EMPLOYEE>\n \n <EMPLOYEE>\n <ID>5</ID>\n <NAME>Gary</NAME>\n <SALARY>843.25</SALARY>\n <STARTDATE>3/27/2015</STARTDATE>\n <DEPT>Finance</DEPT>\n </EMPLOYEE>\n \n <EMPLOYEE>\n <ID>6</ID>\n <NAME>Nina</NAME>\n <SALARY>578</SALARY>\n <STARTDATE>5/21/2013</STARTDATE>\n <DEPT>IT</DEPT>\n </EMPLOYEE>\n \n <EMPLOYEE>\n <ID>7</ID>\n <NAME>Simon</NAME>\n <SALARY>632.8</SALARY>\n <STARTDATE>7/30/2013</STARTDATE>\n <DEPT>Operations</DEPT>\n </EMPLOYEE>\n \n <EMPLOYEE>\n <ID>8</ID>\n <NAME>Guru</NAME>\n <SALARY>722.5</SALARY>\n <STARTDATE>6/17/2014</STARTDATE>\n <DEPT>Finance</DEPT>\n </EMPLOYEE>\n\t\n</RECORDS>"
},
{
"code": null,
"e": 4651,
"s": 4565,
"text": "The xml file is read by R using the function xmlParse(). It is stored as a list in R."
},
{
"code": null,
"e": 4892,
"s": 4651,
"text": "# Load the package required to read XML files.\nlibrary(\"XML\")\n\n# Also load the other required package.\nlibrary(\"methods\")\n\n# Give the input file name to the function.\nresult <- xmlParse(file = \"input.xml\")\n\n# Print the result.\nprint(result)"
},
{
"code": null,
"e": 4959,
"s": 4892,
"text": "When we execute the above code, it produces the following result −"
},
{
"code": null,
"e": 5200,
"s": 4959,
"text": "1\nRick\n623.3\n1/1/2012\nIT\n\n2\nDan\n515.2\n9/23/2013\nOperations\n\n3\nMichelle\n611\n11/15/2014\nIT\n\n4\nRyan\n729\n5/11/2014\nHR\n\n5\nGary\n843.25\n3/27/2015\nFinance\n\n6\nNina\n578\n5/21/2013\nIT\n\n7\nSimon\n632.8\n7/30/2013\nOperations\n\n8\nGuru\n722.5\n6/17/2014\nFinance\n"
},
{
"code": null,
"e": 5541,
"s": 5200,
"text": "# Load the packages required to read XML files.\nlibrary(\"XML\")\nlibrary(\"methods\")\n\n# Give the input file name to the function.\nresult <- xmlParse(file = \"input.xml\")\n\n# Exract the root node form the xml file.\nrootnode <- xmlRoot(result)\n\n# Find number of nodes in the root.\nrootsize <- xmlSize(rootnode)\n\n# Print the result.\nprint(rootsize)"
},
{
"code": null,
"e": 5608,
"s": 5541,
"text": "When we execute the above code, it produces the following result −"
},
{
"code": null,
"e": 5622,
"s": 5608,
"text": "output\n[1] 8\n"
},
{
"code": null,
"e": 5752,
"s": 5622,
"text": "Let's look at the first record of the parsed file. It will give us an idea of the various elements present in the top level node."
},
{
"code": null,
"e": 6029,
"s": 5752,
"text": "# Load the packages required to read XML files.\nlibrary(\"XML\")\nlibrary(\"methods\")\n\n# Give the input file name to the function.\nresult <- xmlParse(file = \"input.xml\")\n\n# Exract the root node form the xml file.\nrootnode <- xmlRoot(result)\n\n# Print the result.\nprint(rootnode[1])"
},
{
"code": null,
"e": 6096,
"s": 6029,
"text": "When we execute the above code, it produces the following result −"
},
{
"code": null,
"e": 6206,
"s": 6096,
"text": "$EMPLOYEE\n 1\n Rick\n 623.3\n 1/1/2012\n IT\n \n\nattr(,\"class\")\n[1] \"XMLInternalNodeList\" \"XMLNodeList\" \n"
},
{
"code": null,
"e": 6654,
"s": 6206,
"text": "# Load the packages required to read XML files.\nlibrary(\"XML\")\nlibrary(\"methods\")\n\n# Give the input file name to the function.\nresult <- xmlParse(file = \"input.xml\")\n\n# Exract the root node form the xml file.\nrootnode <- xmlRoot(result)\n\n# Get the first element of the first node.\nprint(rootnode[[1]][[1]])\n\n# Get the fifth element of the first node.\nprint(rootnode[[1]][[5]])\n\n# Get the second element of the third node.\nprint(rootnode[[3]][[2]])"
},
{
"code": null,
"e": 6721,
"s": 6654,
"text": "When we execute the above code, it produces the following result −"
},
{
"code": null,
"e": 6739,
"s": 6721,
"text": "1 \nIT \nMichelle \n"
},
{
"code": null,
"e": 6882,
"s": 6739,
"text": "To handle the data effectively in large files we read the data in the xml file as a data frame. Then process the data frame for data analysis."
},
{
"code": null,
"e": 7075,
"s": 6882,
"text": "# Load the packages required to read XML files.\nlibrary(\"XML\")\nlibrary(\"methods\")\n\n# Convert the input xml file to a data frame.\nxmldataframe <- xmlToDataFrame(\"input.xml\")\nprint(xmldataframe)"
},
{
"code": null,
"e": 7142,
"s": 7075,
"text": "When we execute the above code, it produces the following result −"
},
{
"code": null,
"e": 7622,
"s": 7142,
"text": " ID NAME SALARY STARTDATE DEPT \n1 1 Rick 623.30 2012-01-01 IT\n2 2 Dan 515.20 2013-09-23 Operations\n3 3 Michelle 611.00 2014-11-15 IT\n4 4 Ryan 729.00 2014-05-11 HR\n5 NA Gary 843.25 2015-03-27 Finance\n6 6 Nina 578.00 2013-05-21 IT\n7 7 Simon 632.80 2013-07-30 Operations\n8 8 Guru 722.50 2014-06-17 Finance\n"
}
] |
How can we validate decimal numbers in JavaScript?
|
Following is the code to validate decimal numbers in JavaScript −
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result {
font-size: 20px;
font-weight: 500;
}
</style>
</head>
<body>
<h1>Validate decimal numbers in JavaScript</h1>
<div style="color: green;" class="result"></div>
<input type="number" class="num" />
<button class="Btn">CHECK</button>
<h3>Click the above button to check if a valid decimal number is entered or not</h3>
<script>
let resEle = document.querySelector(".result");
document.querySelector(".Btn").addEventListener("click", () => {
var str = document.querySelector(".num").value;
var regex = /^[-+]?[0-9]+\.[0-9]+$/;
var match = str.match(regex);
if (match) resEle.innerHTML = "The number given is a decimal number";
else resEle.innerHTML = "The number given is not a decimal number";
});
</script>
</body>
</html>
The above code will produce the following output −
On entering a normal number and clicking on ‘CHECK’ button −
On entering a decimal number and clicking on ‘CHECK’ −
|
[
{
"code": null,
"e": 1253,
"s": 1187,
"text": "Following is the code to validate decimal numbers in JavaScript −"
},
{
"code": null,
"e": 1264,
"s": 1253,
"text": " Live Demo"
},
{
"code": null,
"e": 2303,
"s": 1264,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .result {\n font-size: 20px;\n font-weight: 500;\n }\n</style>\n</head>\n<body>\n<h1>Validate decimal numbers in JavaScript</h1>\n<div style=\"color: green;\" class=\"result\"></div>\n<input type=\"number\" class=\"num\" />\n<button class=\"Btn\">CHECK</button>\n<h3>Click the above button to check if a valid decimal number is entered or not</h3>\n<script>\n let resEle = document.querySelector(\".result\");\n document.querySelector(\".Btn\").addEventListener(\"click\", () => {\n var str = document.querySelector(\".num\").value;\n var regex = /^[-+]?[0-9]+\\.[0-9]+$/;\n var match = str.match(regex);\n if (match) resEle.innerHTML = \"The number given is a decimal number\";\n else resEle.innerHTML = \"The number given is not a decimal number\";\n });\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2354,
"s": 2303,
"text": "The above code will produce the following output −"
},
{
"code": null,
"e": 2415,
"s": 2354,
"text": "On entering a normal number and clicking on ‘CHECK’ button −"
},
{
"code": null,
"e": 2470,
"s": 2415,
"text": "On entering a decimal number and clicking on ‘CHECK’ −"
}
] |
Include v/s Extend in Ruby
|
18 Mar, 2021
Include is used to importing module code. Ruby will throw an error when we try to access the methods of import module with the class directly because it gets imported as a subclass for the superclass. So, the only way is to access it through the instance of the class.
Extend is also used to importing module code but extends import them as class methods. Ruby will throw an error when we try to access methods of import module with the instance of the class because the module gets import to the superclass just as the instance of the extended module. So, the only way is to access it through the class definition.
In simple words, the difference between include and extend is that ‘include’ is for adding methods only to an instance of a class and ‘extend’ is for adding methods to the class but not to its instance.
Example :
# Ruby program of Include and Extend # Creating a module contains a methodmodule Geek def geeks puts 'GeeksforGeeks!' endend class Lord # only can access geek methods # with the instance of the class. include Geekend class Star # only can access geek methods # with the class definition. extend Geekend # object access Lord.new.geeks # class accessStar.geeks # NoMethodError: undefined method# `geeks' for Lord:ClassLord.geeks
Output
GeeksforGeeks!
GeeksforGeeks!
main.rb:20:in `': undefined method `geeks' for Lord:Class (NoMethodError)
If we want to import instance methods on a class and its class methods too. We can ‘include’ and ‘extend’ it at the same time.Example :
# Ruby program to understand include and extend # Creating a module contains a methodmodule Geek def prints(x) puts x endend class GFG # by using both include and extend # we can access them by both instances # and class name. include Geek extend Geekend # access the prints() in Geek# module by include in Lord classGFG.new.prints("Howdy") # object access # access the prints() in Geek # module by extend it in Lord classGFG.prints("GeeksforGeeks!!") # class access
Output
Howdy
GeeksforGeeks!!
Picked
Ruby Keyword
Ruby modules
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n18 Mar, 2021"
},
{
"code": null,
"e": 322,
"s": 53,
"text": "Include is used to importing module code. Ruby will throw an error when we try to access the methods of import module with the class directly because it gets imported as a subclass for the superclass. So, the only way is to access it through the instance of the class."
},
{
"code": null,
"e": 669,
"s": 322,
"text": "Extend is also used to importing module code but extends import them as class methods. Ruby will throw an error when we try to access methods of import module with the instance of the class because the module gets import to the superclass just as the instance of the extended module. So, the only way is to access it through the class definition."
},
{
"code": null,
"e": 872,
"s": 669,
"text": "In simple words, the difference between include and extend is that ‘include’ is for adding methods only to an instance of a class and ‘extend’ is for adding methods to the class but not to its instance."
},
{
"code": null,
"e": 882,
"s": 872,
"text": "Example :"
},
{
"code": "# Ruby program of Include and Extend # Creating a module contains a methodmodule Geek def geeks puts 'GeeksforGeeks!' endend class Lord # only can access geek methods # with the instance of the class. include Geekend class Star # only can access geek methods # with the class definition. extend Geekend # object access Lord.new.geeks # class accessStar.geeks # NoMethodError: undefined method# `geeks' for Lord:ClassLord.geeks ",
"e": 1338,
"s": 882,
"text": null
},
{
"code": null,
"e": 1345,
"s": 1338,
"text": "Output"
},
{
"code": null,
"e": 1450,
"s": 1345,
"text": "GeeksforGeeks!\nGeeksforGeeks!\nmain.rb:20:in `': undefined method `geeks' for Lord:Class (NoMethodError)\n"
},
{
"code": null,
"e": 1586,
"s": 1450,
"text": "If we want to import instance methods on a class and its class methods too. We can ‘include’ and ‘extend’ it at the same time.Example :"
},
{
"code": "# Ruby program to understand include and extend # Creating a module contains a methodmodule Geek def prints(x) puts x endend class GFG # by using both include and extend # we can access them by both instances # and class name. include Geek extend Geekend # access the prints() in Geek# module by include in Lord classGFG.new.prints(\"Howdy\") # object access # access the prints() in Geek # module by extend it in Lord classGFG.prints(\"GeeksforGeeks!!\") # class access",
"e": 2072,
"s": 1586,
"text": null
},
{
"code": null,
"e": 2079,
"s": 2072,
"text": "Output"
},
{
"code": null,
"e": 2102,
"s": 2079,
"text": "Howdy\nGeeksforGeeks!!\n"
},
{
"code": null,
"e": 2109,
"s": 2102,
"text": "Picked"
},
{
"code": null,
"e": 2122,
"s": 2109,
"text": "Ruby Keyword"
},
{
"code": null,
"e": 2135,
"s": 2122,
"text": "Ruby modules"
},
{
"code": null,
"e": 2140,
"s": 2135,
"text": "Ruby"
}
] |
Rounding Floating Point Number To two Decimal Places in C and C++
|
07 Aug, 2021
How to round off a floating point value to two places. For example, 5.567 should become 5.57 and 5.534 should become 5.53
First Method:- Using Float precision
C++
C
#include<bits/stdc++.h>using namespace std; int main(){ float var = 37.66666; // Directly print the number with .2f precision cout << fixed << setprecision(2) << var; return 0;} // This code is contributed by shivanisinghss2110
#include <iostream>using namespace std;int main(){ float var = 37.66666; // Directly print the number with .2f precision printf("%.2f", var); return 0;}
Output:
37.67
Second Method: Using integer typecast If we are in Function then how return two decimal point value
C++
#include <iostream>using namespace std;float round(float var){ // 37.66666 * 100 =3766.66 // 3766.66 + .5 =3767.16 for rounding off value // then type cast to int so value is 3767 // then divided by 100 so the value converted into 37.67 float value = (int)(var * 100 + .5); return (float)value / 100;} int main(){ float var = 37.66666; cout << round(var); return 0;}
Output:
37.67
Third Method: using sprintf() and sscanf()
C++
#include <iostream>using namespace std;float round(float var){ // we use array of chars to store number // as a string. char str[40]; // Print in string the value of var // with two decimal point sprintf(str, "%.2f", var); // scan string value in var sscanf(str, "%f", &var); return var;} int main(){ float var = 37.66666; cout << round(var); return 0;}
Output:
37.67
This article is contributed by Devanshu Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
arjunaggarwal
simmytarika5
shivanisinghss2110
cpp-data-types
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n07 Aug, 2021"
},
{
"code": null,
"e": 176,
"s": 54,
"text": "How to round off a floating point value to two places. For example, 5.567 should become 5.57 and 5.534 should become 5.53"
},
{
"code": null,
"e": 214,
"s": 176,
"text": "First Method:- Using Float precision "
},
{
"code": null,
"e": 218,
"s": 214,
"text": "C++"
},
{
"code": null,
"e": 220,
"s": 218,
"text": "C"
},
{
"code": "#include<bits/stdc++.h>using namespace std; int main(){ float var = 37.66666; // Directly print the number with .2f precision cout << fixed << setprecision(2) << var; return 0;} // This code is contributed by shivanisinghss2110",
"e": 461,
"s": 220,
"text": null
},
{
"code": "#include <iostream>using namespace std;int main(){ float var = 37.66666; // Directly print the number with .2f precision printf(\"%.2f\", var); return 0;}",
"e": 627,
"s": 461,
"text": null
},
{
"code": null,
"e": 641,
"s": 627,
"text": "Output:\n37.67"
},
{
"code": null,
"e": 741,
"s": 641,
"text": "Second Method: Using integer typecast If we are in Function then how return two decimal point value"
},
{
"code": null,
"e": 745,
"s": 741,
"text": "C++"
},
{
"code": "#include <iostream>using namespace std;float round(float var){ // 37.66666 * 100 =3766.66 // 3766.66 + .5 =3767.16 for rounding off value // then type cast to int so value is 3767 // then divided by 100 so the value converted into 37.67 float value = (int)(var * 100 + .5); return (float)value / 100;} int main(){ float var = 37.66666; cout << round(var); return 0;}",
"e": 1142,
"s": 745,
"text": null
},
{
"code": null,
"e": 1156,
"s": 1142,
"text": "Output:\n37.67"
},
{
"code": null,
"e": 1200,
"s": 1156,
"text": "Third Method: using sprintf() and sscanf() "
},
{
"code": null,
"e": 1204,
"s": 1200,
"text": "C++"
},
{
"code": "#include <iostream>using namespace std;float round(float var){ // we use array of chars to store number // as a string. char str[40]; // Print in string the value of var // with two decimal point sprintf(str, \"%.2f\", var); // scan string value in var sscanf(str, \"%f\", &var); return var;} int main(){ float var = 37.66666; cout << round(var); return 0;}",
"e": 1597,
"s": 1204,
"text": null
},
{
"code": null,
"e": 1611,
"s": 1597,
"text": "Output:\n37.67"
},
{
"code": null,
"e": 2036,
"s": 1611,
"text": "This article is contributed by Devanshu Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 2050,
"s": 2036,
"text": "arjunaggarwal"
},
{
"code": null,
"e": 2063,
"s": 2050,
"text": "simmytarika5"
},
{
"code": null,
"e": 2082,
"s": 2063,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 2097,
"s": 2082,
"text": "cpp-data-types"
},
{
"code": null,
"e": 2108,
"s": 2097,
"text": "C Language"
}
] |
Python | Pandas Series.isnull()
|
12 Feb, 2019
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.isnull() function detect missing values in the given series object. It return a boolean same-sized object indicating if the values are NA. Missing values gets mapped to True and non-missing value gets mapped to False.
Syntax: Series.isnull()
Parameter : None
Returns : boolean
Example #1: Use Series.isnull() function to detect missing values in the given series object.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([10, 25, 3, 25, 24, 6]) # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp'] # set the indexsr.index = index_ # Print the seriesprint(sr)
Output :
Now we will use Series.isnull() function to detect all the missing values in the given series object.
# detect missing valuesresult = sr.isnull() # Print the resultprint(result)
Output :As we can see in the output, the Series.isnull() function has returned an object containing boolean values. All values have been mapped to False because there is no missing value in the given series object. Example #2 : Use Series.isnull() function to detect missing values in the given series object.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([11, 21, 8, 18, 65, None, 32, 10, 5, 24, None]) # Create the Indexindex_ = pd.date_range('2010-10-09', periods = 11, freq ='M') # set the indexsr.index = index_ # Print the seriesprint(sr)
Output :
Now we will use Series.isnull() function to detect all the missing values in the given series object.
# detect missing valuesresult = sr.isnull() # Print the resultprint(result)
Output :As we can see in the output, the Series.isnull() function has returned an object containing boolean values. All missing values have been mapped to True.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Feb, 2019"
},
{
"code": null,
"e": 284,
"s": 28,
"text": "Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer and label-based indexing and provides a host of methods for performing operations involving the index."
},
{
"code": null,
"e": 516,
"s": 284,
"text": "Pandas Series.isnull() function detect missing values in the given series object. It return a boolean same-sized object indicating if the values are NA. Missing values gets mapped to True and non-missing value gets mapped to False."
},
{
"code": null,
"e": 540,
"s": 516,
"text": "Syntax: Series.isnull()"
},
{
"code": null,
"e": 557,
"s": 540,
"text": "Parameter : None"
},
{
"code": null,
"e": 575,
"s": 557,
"text": "Returns : boolean"
},
{
"code": null,
"e": 669,
"s": 575,
"text": "Example #1: Use Series.isnull() function to detect missing values in the given series object."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([10, 25, 3, 25, 24, 6]) # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp'] # set the indexsr.index = index_ # Print the seriesprint(sr)",
"e": 925,
"s": 669,
"text": null
},
{
"code": null,
"e": 934,
"s": 925,
"text": "Output :"
},
{
"code": null,
"e": 1036,
"s": 934,
"text": "Now we will use Series.isnull() function to detect all the missing values in the given series object."
},
{
"code": "# detect missing valuesresult = sr.isnull() # Print the resultprint(result)",
"e": 1113,
"s": 1036,
"text": null
},
{
"code": null,
"e": 1423,
"s": 1113,
"text": "Output :As we can see in the output, the Series.isnull() function has returned an object containing boolean values. All values have been mapped to False because there is no missing value in the given series object. Example #2 : Use Series.isnull() function to detect missing values in the given series object."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([11, 21, 8, 18, 65, None, 32, 10, 5, 24, None]) # Create the Indexindex_ = pd.date_range('2010-10-09', periods = 11, freq ='M') # set the indexsr.index = index_ # Print the seriesprint(sr)",
"e": 1696,
"s": 1423,
"text": null
},
{
"code": null,
"e": 1705,
"s": 1696,
"text": "Output :"
},
{
"code": null,
"e": 1807,
"s": 1705,
"text": "Now we will use Series.isnull() function to detect all the missing values in the given series object."
},
{
"code": "# detect missing valuesresult = sr.isnull() # Print the resultprint(result)",
"e": 1884,
"s": 1807,
"text": null
},
{
"code": null,
"e": 2045,
"s": 1884,
"text": "Output :As we can see in the output, the Series.isnull() function has returned an object containing boolean values. All missing values have been mapped to True."
},
{
"code": null,
"e": 2066,
"s": 2045,
"text": "Python pandas-series"
},
{
"code": null,
"e": 2095,
"s": 2066,
"text": "Python pandas-series-methods"
},
{
"code": null,
"e": 2109,
"s": 2095,
"text": "Python-pandas"
},
{
"code": null,
"e": 2116,
"s": 2109,
"text": "Python"
}
] |
Generic Set In Java
|
24 Oct, 2020
The Set interface is present in java.util package. It is basically a collection of objects with no duplicate objects that means there can be no two objects in a Set e1 and e2 such that e1.equals(e2) and at most one null element. It is an interface that models the mathematical set. This interface inherits the features from the Collection interface and places a feature that restricts the addition of duplicate elements on its own. The two interfaces which implement the Set interface are SortedSet and NavigableSet.
In this image, the NavigableSet inherits/extends the SortedSet. Now, since the Set doesn’t retain the original order of insertion of elements, so NavigableSet provides the implementation of this interface to navigate the set. TreeSet which is an implementation of a Red-Black Tree and implements the NavigableSet.
Declaration of a Set Interface
public interface Set extends Collection{
}
Syntax of a Set
Set< Integer > set = new HashSet< Integer >();
Now, this is targeted to only Integer datatype. i.e only Integer instances can be put in the Set. If we try to put something else in the Set, the compiler will give an error. The checks of generic type occur at the time of compilation.
Syntax of a Generic Set
Set< T > set = new HashSet< T >();
Above syntax is a generalized way to use T to show the generic behavior of a Set which means that T can be replaced with any non-primitive like Integer, String, Double, Character, or any user-defined type.
add() method is used to add elements in a Set. If the element already exists in the Set, it returns false
Set<Character> set = new HashSet<Character>();
Character ch = 'a';
set.add(ch);
The difference is, if we try to add something which is not a Character, then the compiler will show an error.
1. We can use an iterator to iterate over a Set.
Set<Integer> set = new HashSet<Integer>();
Iterator<Iterator> it = set.iterator();
while(it.hasNext()){
Integer aInt = iterator.next();
}
2. Another way to iterate over a Set is to use Generic for-loop.
Set<String> set = new HashSet<String>;
for(String st : set) {
System.out.println(st);
}
Example:
Java
// Java program to demonstrate Generic Set import java.util.HashSet;import java.util.Iterator;import java.util.Set; public class GenericSet { public static void main(String[] args) { // create an instance of Set using // generics Set<Integer> set1 = new HashSet<Integer>(); // Add elements set1.add(100); set1.add(Integer.valueOf(101)); // Create another set Set<String> set2 = new HashSet<String>(); // Add elements set2.add("geeksforgeeks"); set2.add("generics"); // Iterate set1 using for-each loop for (Integer data : set1) { System.out.printf("Integer Value :%d\n", data); } // Iterate set2 using iterator Iterator<String> stringIt = set2.iterator(); while (stringIt.hasNext()) { System.out.printf("String Value :%s\n", stringIt.next()); } }}
Integer Value :100
Integer Value :101
String Value :geeksforgeeks
String Value :generics
Java-Generics
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
Stream In Java
ArrayList in Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n24 Oct, 2020"
},
{
"code": null,
"e": 570,
"s": 53,
"text": "The Set interface is present in java.util package. It is basically a collection of objects with no duplicate objects that means there can be no two objects in a Set e1 and e2 such that e1.equals(e2) and at most one null element. It is an interface that models the mathematical set. This interface inherits the features from the Collection interface and places a feature that restricts the addition of duplicate elements on its own. The two interfaces which implement the Set interface are SortedSet and NavigableSet."
},
{
"code": null,
"e": 884,
"s": 570,
"text": "In this image, the NavigableSet inherits/extends the SortedSet. Now, since the Set doesn’t retain the original order of insertion of elements, so NavigableSet provides the implementation of this interface to navigate the set. TreeSet which is an implementation of a Red-Black Tree and implements the NavigableSet."
},
{
"code": null,
"e": 916,
"s": 884,
"text": "Declaration of a Set Interface "
},
{
"code": null,
"e": 961,
"s": 916,
"text": "public interface Set extends Collection{\n\n}\n"
},
{
"code": null,
"e": 977,
"s": 961,
"text": "Syntax of a Set"
},
{
"code": null,
"e": 1025,
"s": 977,
"text": "Set< Integer > set = new HashSet< Integer >();\n"
},
{
"code": null,
"e": 1261,
"s": 1025,
"text": "Now, this is targeted to only Integer datatype. i.e only Integer instances can be put in the Set. If we try to put something else in the Set, the compiler will give an error. The checks of generic type occur at the time of compilation."
},
{
"code": null,
"e": 1285,
"s": 1261,
"text": "Syntax of a Generic Set"
},
{
"code": null,
"e": 1321,
"s": 1285,
"text": "Set< T > set = new HashSet< T >();\n"
},
{
"code": null,
"e": 1527,
"s": 1321,
"text": "Above syntax is a generalized way to use T to show the generic behavior of a Set which means that T can be replaced with any non-primitive like Integer, String, Double, Character, or any user-defined type."
},
{
"code": null,
"e": 1633,
"s": 1527,
"text": "add() method is used to add elements in a Set. If the element already exists in the Set, it returns false"
},
{
"code": null,
"e": 1715,
"s": 1633,
"text": "Set<Character> set = new HashSet<Character>();\n\nCharacter ch = 'a';\nset.add(ch);\n"
},
{
"code": null,
"e": 1825,
"s": 1715,
"text": "The difference is, if we try to add something which is not a Character, then the compiler will show an error."
},
{
"code": null,
"e": 1875,
"s": 1825,
"text": "1. We can use an iterator to iterate over a Set."
},
{
"code": null,
"e": 2022,
"s": 1875,
"text": "Set<Integer> set = new HashSet<Integer>();\n \nIterator<Iterator> it = set.iterator();\n\nwhile(it.hasNext()){\n Integer aInt = iterator.next();\n}\n"
},
{
"code": null,
"e": 2088,
"s": 2022,
"text": "2. Another way to iterate over a Set is to use Generic for-loop."
},
{
"code": null,
"e": 2182,
"s": 2088,
"text": "Set<String> set = new HashSet<String>;\n\nfor(String st : set) {\n System.out.println(st);\n}\n"
},
{
"code": null,
"e": 2191,
"s": 2182,
"text": "Example:"
},
{
"code": null,
"e": 2196,
"s": 2191,
"text": "Java"
},
{
"code": "// Java program to demonstrate Generic Set import java.util.HashSet;import java.util.Iterator;import java.util.Set; public class GenericSet { public static void main(String[] args) { // create an instance of Set using // generics Set<Integer> set1 = new HashSet<Integer>(); // Add elements set1.add(100); set1.add(Integer.valueOf(101)); // Create another set Set<String> set2 = new HashSet<String>(); // Add elements set2.add(\"geeksforgeeks\"); set2.add(\"generics\"); // Iterate set1 using for-each loop for (Integer data : set1) { System.out.printf(\"Integer Value :%d\\n\", data); } // Iterate set2 using iterator Iterator<String> stringIt = set2.iterator(); while (stringIt.hasNext()) { System.out.printf(\"String Value :%s\\n\", stringIt.next()); } }}",
"e": 3144,
"s": 2196,
"text": null
},
{
"code": null,
"e": 3233,
"s": 3144,
"text": "Integer Value :100\nInteger Value :101\nString Value :geeksforgeeks\nString Value :generics"
},
{
"code": null,
"e": 3247,
"s": 3233,
"text": "Java-Generics"
},
{
"code": null,
"e": 3252,
"s": 3247,
"text": "Java"
},
{
"code": null,
"e": 3257,
"s": 3252,
"text": "Java"
},
{
"code": null,
"e": 3355,
"s": 3257,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3406,
"s": 3355,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 3437,
"s": 3406,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 3456,
"s": 3437,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 3486,
"s": 3456,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 3501,
"s": 3486,
"text": "Stream In Java"
},
{
"code": null,
"e": 3519,
"s": 3501,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 3539,
"s": 3519,
"text": "Collections in Java"
},
{
"code": null,
"e": 3563,
"s": 3539,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 3595,
"s": 3563,
"text": "Multidimensional Arrays in Java"
}
] |
pandas.bdate_range() function in Python
|
14 Aug, 2020
This method is used to return a fixed frequency DatetimeIndex, with the business day as the default frequency.
Syntax : pandas.bdate_range(start=None, end=None, periods=None, freq=’B’, tz=None, normalize=True, name=None, weekmask=None, holidays=None, closed=None, **kwargs,)
Parameters :
start : string or datetime-like, default None, Left bound for generating dates.
end : string or datetime-like, default None, Right bound for generating dates.
periods : integer, default None, Number of periods to generate.
freq : string or DateOffset, default ‘B’ (business daily), Frequency strings can have multiples, e.g. ‘5H’.
tz : string or None, Time zone name for returning localized DatetimeIndex, for example Asia/Beijing.
Below is the implementation of the above method with some examples :
Example 1 :
Python3
# importing packagesimport pandas # using pandas.bdate_range() methodprint(pandas.bdate_range(start='8/1/2020', end='8/20/2020'))
Output:
Example 2 :
Python3
# importing packagesimport pandas # using pandas.bdate_range() methodprint(pandas.bdate_range(start='8/1/2020', end='8/5/2020', freq='5H'))
Output :
Python pandas-datetimeIndex
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
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Aug, 2020"
},
{
"code": null,
"e": 139,
"s": 28,
"text": "This method is used to return a fixed frequency DatetimeIndex, with the business day as the default frequency."
},
{
"code": null,
"e": 303,
"s": 139,
"text": "Syntax : pandas.bdate_range(start=None, end=None, periods=None, freq=’B’, tz=None, normalize=True, name=None, weekmask=None, holidays=None, closed=None, **kwargs,)"
},
{
"code": null,
"e": 316,
"s": 303,
"text": "Parameters :"
},
{
"code": null,
"e": 396,
"s": 316,
"text": "start : string or datetime-like, default None, Left bound for generating dates."
},
{
"code": null,
"e": 475,
"s": 396,
"text": "end : string or datetime-like, default None, Right bound for generating dates."
},
{
"code": null,
"e": 539,
"s": 475,
"text": "periods : integer, default None, Number of periods to generate."
},
{
"code": null,
"e": 648,
"s": 539,
"text": "freq : string or DateOffset, default ‘B’ (business daily), Frequency strings can have multiples, e.g. ‘5H’."
},
{
"code": null,
"e": 749,
"s": 648,
"text": "tz : string or None, Time zone name for returning localized DatetimeIndex, for example Asia/Beijing."
},
{
"code": null,
"e": 818,
"s": 749,
"text": "Below is the implementation of the above method with some examples :"
},
{
"code": null,
"e": 830,
"s": 818,
"text": "Example 1 :"
},
{
"code": null,
"e": 838,
"s": 830,
"text": "Python3"
},
{
"code": "# importing packagesimport pandas # using pandas.bdate_range() methodprint(pandas.bdate_range(start='8/1/2020', end='8/20/2020'))",
"e": 993,
"s": 838,
"text": null
},
{
"code": null,
"e": 1001,
"s": 993,
"text": "Output:"
},
{
"code": null,
"e": 1013,
"s": 1001,
"text": "Example 2 :"
},
{
"code": null,
"e": 1021,
"s": 1013,
"text": "Python3"
},
{
"code": "# importing packagesimport pandas # using pandas.bdate_range() methodprint(pandas.bdate_range(start='8/1/2020', end='8/5/2020', freq='5H'))",
"e": 1210,
"s": 1021,
"text": null
},
{
"code": null,
"e": 1219,
"s": 1210,
"text": "Output :"
},
{
"code": null,
"e": 1247,
"s": 1219,
"text": "Python pandas-datetimeIndex"
},
{
"code": null,
"e": 1261,
"s": 1247,
"text": "Python-pandas"
},
{
"code": null,
"e": 1268,
"s": 1261,
"text": "Python"
},
{
"code": null,
"e": 1366,
"s": 1268,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1398,
"s": 1366,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1425,
"s": 1398,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1446,
"s": 1425,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1469,
"s": 1446,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1525,
"s": 1469,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1556,
"s": 1525,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1598,
"s": 1556,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1640,
"s": 1598,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1679,
"s": 1640,
"text": "Python | datetime.timedelta() function"
}
] |
Design and Analysis Shortest Paths
|
Dijkstra’s algorithm solves the single-source shortest-paths problem on a directed weighted graph G = (V, E), where all the edges are non-negative (i.e., w(u, v) ≥ 0 for each edge (u, v) Є E).
In the following algorithm, we will use one function Extract-Min(), which extracts the node with the smallest key.
Algorithm: Dijkstra’s-Algorithm (G, w, s)
for each vertex v Є G.V
v.d := ∞
v.∏ := NIL
s.d := 0
S := Ф
Q := G.V
while Q ≠ Ф
u := Extract-Min (Q)
S := S U {u}
for each vertex v Є G.adj[u]
if v.d > u.d + w(u, v)
v.d := u.d + w(u, v)
v.∏ := u
The complexity of this algorithm is fully dependent on the implementation of Extract-Min function. If extract min function is implemented using linear search, the complexity of this algorithm is O(V2 + E).
In this algorithm, if we use min-heap on which Extract-Min() function works to return the node from Q with the smallest key, the complexity of this algorithm can be reduced further.
Let us consider vertex 1 and 9 as the start and destination vertex respectively. Initially, all the vertices except the start vertex are marked by ∞ and the start vertex is marked by 0.
Hence, the minimum distance of vertex 9 from vertex 1 is 20. And the path is
1→ 3→ 7→ 8→ 6→ 9
This path is determined based on predecessor information.
This algorithm solves the single source shortest path problem of a directed graph G = (V, E) in which the edge weights may be negative. Moreover, this algorithm can be applied to find the shortest path, if there does not exist any negative weighted cycle.
Algorithm: Bellman-Ford-Algorithm (G, w, s)
for each vertex v Є G.V
v.d := ∞
v.∏ := NIL
s.d := 0
for i = 1 to |G.V| - 1
for each edge (u, v) Є G.E
if v.d > u.d + w(u, v)
v.d := u.d +w(u, v)
v.∏ := u
for each edge (u, v) Є G.E
if v.d > u.d + w(u, v)
return FALSE
return TRUE
The first for loop is used for initialization, which runs in O(V) times. The next for loop runs |V - 1| passes over the edges, which takes O(E) times.
Hence, Bellman-Ford algorithm runs in O(V, E) time.
The following example shows how Bellman-Ford algorithm works step by step. This graph has a negative edge but does not have any negative cycle, hence the problem can be solved using this technique.
At the time of initialization, all the vertices except the source are marked by ∞ and the source is marked by 0.
In the first step, all the vertices which are reachable from the source are updated by minimum cost. Hence, vertices a and h are updated.
In the next step, vertices a, b, f and e are updated.
Following the same logic, in this step vertices b, f, c and g are updated.
Here, vertices c and d are updated.
Hence, the minimum distance between vertex s and vertex d is 20.
Based on the predecessor information, the path is s→ h→ e→ g→ c→ d
|
[
{
"code": null,
"e": 2926,
"s": 2733,
"text": "Dijkstra’s algorithm solves the single-source shortest-paths problem on a directed weighted graph G = (V, E), where all the edges are non-negative (i.e., w(u, v) ≥ 0 for each edge (u, v) Є E)."
},
{
"code": null,
"e": 3041,
"s": 2926,
"text": "In the following algorithm, we will use one function Extract-Min(), which extracts the node with the smallest key."
},
{
"code": null,
"e": 3335,
"s": 3041,
"text": "Algorithm: Dijkstra’s-Algorithm (G, w, s) \nfor each vertex v Є G.V \n v.d := ∞ \n v.∏ := NIL \ns.d := 0 \nS := Ф \nQ := G.V \nwhile Q ≠ Ф \n u := Extract-Min (Q) \n S := S U {u} \n for each vertex v Є G.adj[u] \n if v.d > u.d + w(u, v) \n v.d := u.d + w(u, v) \n v.∏ := u\n"
},
{
"code": null,
"e": 3541,
"s": 3335,
"text": "The complexity of this algorithm is fully dependent on the implementation of Extract-Min function. If extract min function is implemented using linear search, the complexity of this algorithm is O(V2 + E)."
},
{
"code": null,
"e": 3723,
"s": 3541,
"text": "In this algorithm, if we use min-heap on which Extract-Min() function works to return the node from Q with the smallest key, the complexity of this algorithm can be reduced further."
},
{
"code": null,
"e": 3909,
"s": 3723,
"text": "Let us consider vertex 1 and 9 as the start and destination vertex respectively. Initially, all the vertices except the start vertex are marked by ∞ and the start vertex is marked by 0."
},
{
"code": null,
"e": 3986,
"s": 3909,
"text": "Hence, the minimum distance of vertex 9 from vertex 1 is 20. And the path is"
},
{
"code": null,
"e": 4003,
"s": 3986,
"text": "1→ 3→ 7→ 8→ 6→ 9"
},
{
"code": null,
"e": 4061,
"s": 4003,
"text": "This path is determined based on predecessor information."
},
{
"code": null,
"e": 4317,
"s": 4061,
"text": "This algorithm solves the single source shortest path problem of a directed graph G = (V, E) in which the edge weights may be negative. Moreover, this algorithm can be applied to find the shortest path, if there does not exist any negative weighted cycle."
},
{
"code": null,
"e": 4648,
"s": 4317,
"text": "Algorithm: Bellman-Ford-Algorithm (G, w, s) \nfor each vertex v Є G.V \n v.d := ∞ \n v.∏ := NIL \ns.d := 0 \nfor i = 1 to |G.V| - 1 \n for each edge (u, v) Є G.E \n if v.d > u.d + w(u, v) \n v.d := u.d +w(u, v) \n v.∏ := u \nfor each edge (u, v) Є G.E \n if v.d > u.d + w(u, v) \n return FALSE \nreturn TRUE\n"
},
{
"code": null,
"e": 4799,
"s": 4648,
"text": "The first for loop is used for initialization, which runs in O(V) times. The next for loop runs |V - 1| passes over the edges, which takes O(E) times."
},
{
"code": null,
"e": 4851,
"s": 4799,
"text": "Hence, Bellman-Ford algorithm runs in O(V, E) time."
},
{
"code": null,
"e": 5049,
"s": 4851,
"text": "The following example shows how Bellman-Ford algorithm works step by step. This graph has a negative edge but does not have any negative cycle, hence the problem can be solved using this technique."
},
{
"code": null,
"e": 5162,
"s": 5049,
"text": "At the time of initialization, all the vertices except the source are marked by ∞ and the source is marked by 0."
},
{
"code": null,
"e": 5300,
"s": 5162,
"text": "In the first step, all the vertices which are reachable from the source are updated by minimum cost. Hence, vertices a and h are updated."
},
{
"code": null,
"e": 5354,
"s": 5300,
"text": "In the next step, vertices a, b, f and e are updated."
},
{
"code": null,
"e": 5429,
"s": 5354,
"text": "Following the same logic, in this step vertices b, f, c and g are updated."
},
{
"code": null,
"e": 5465,
"s": 5429,
"text": "Here, vertices c and d are updated."
},
{
"code": null,
"e": 5530,
"s": 5465,
"text": "Hence, the minimum distance between vertex s and vertex d is 20."
}
] |
Program to check whether a binary tree is BST or not in Python
|
Suppose we have binary tree; we have to check whether it is a binary search tree or not. As we know a BST has following properties −
all nodes on its left subtree is smaller than current node value
all nodes on its right subtree is larger than current node value
these properties hold recursively for all nodes
So, if the input is like
then the output will be True
To solve this, we will follow these steps −
x := a list of inorder traversal sequence of tree elements
if x is sorted, thenreturn true
return true
return false
Let us see the following implementation to get better understanding −
Live Demo
class TreeNode:
def __init__(self, data, left = None, right = None):
self.data = data
self.left = left
self.right = right
class Solution:
def solve(self, root):
def inorder(root,l):
if root is None:
return
inorder(root.left,l) l.append(root.data)
inorder(root.right,l)
l = []
inorder(root,l)
return l == sorted(l)
ob = Solution()
root = TreeNode(5)
root.left = TreeNode(1)
root.right = TreeNode(9) root.right.left = TreeNode(7) root.right.right = TreeNode(10) root.right.left.left = TreeNode(6) root.right.left.right = TreeNode(8) print(ob.solve(root))
root = TreeNode(5)
root.left = TreeNode(1)
root.right = TreeNode(9)
root.right.left = TreeNode(7)
root.right.right = TreeNode(10)
root.right.left.left = TreeNode(6)
root.right.left.right = TreeNode(8)
True
|
[
{
"code": null,
"e": 1320,
"s": 1187,
"text": "Suppose we have binary tree; we have to check whether it is a binary search tree or not. As we know a BST has following properties −"
},
{
"code": null,
"e": 1385,
"s": 1320,
"text": "all nodes on its left subtree is smaller than current node value"
},
{
"code": null,
"e": 1450,
"s": 1385,
"text": "all nodes on its right subtree is larger than current node value"
},
{
"code": null,
"e": 1498,
"s": 1450,
"text": "these properties hold recursively for all nodes"
},
{
"code": null,
"e": 1523,
"s": 1498,
"text": "So, if the input is like"
},
{
"code": null,
"e": 1552,
"s": 1523,
"text": "then the output will be True"
},
{
"code": null,
"e": 1596,
"s": 1552,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1655,
"s": 1596,
"text": "x := a list of inorder traversal sequence of tree elements"
},
{
"code": null,
"e": 1687,
"s": 1655,
"text": "if x is sorted, thenreturn true"
},
{
"code": null,
"e": 1699,
"s": 1687,
"text": "return true"
},
{
"code": null,
"e": 1712,
"s": 1699,
"text": "return false"
},
{
"code": null,
"e": 1782,
"s": 1712,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 1793,
"s": 1782,
"text": " Live Demo"
},
{
"code": null,
"e": 2454,
"s": 1793,
"text": "class TreeNode:\n def __init__(self, data, left = None, right = None):\n self.data = data\n self.left = left\n self.right = right\nclass Solution:\n def solve(self, root):\n def inorder(root,l):\n if root is None:\n return\n inorder(root.left,l) l.append(root.data)\n inorder(root.right,l)\n l = []\n inorder(root,l)\n return l == sorted(l)\nob = Solution()\nroot = TreeNode(5)\nroot.left = TreeNode(1)\nroot.right = TreeNode(9) root.right.left = TreeNode(7) root.right.right = TreeNode(10) root.right.left.left = TreeNode(6) root.right.left.right = TreeNode(8) print(ob.solve(root))"
},
{
"code": null,
"e": 2655,
"s": 2454,
"text": "root = TreeNode(5)\nroot.left = TreeNode(1)\nroot.right = TreeNode(9)\nroot.right.left = TreeNode(7)\nroot.right.right = TreeNode(10)\nroot.right.left.left = TreeNode(6)\nroot.right.left.right = TreeNode(8)"
},
{
"code": null,
"e": 2660,
"s": 2655,
"text": "True"
}
] |
How to check if email address is already in use or not using express-validator in Node.js ?
|
08 Apr, 2022
The registration or Sign Up in any website always requires a username. Most of the time we use ’email’ to register on a website. The registration email is always unique and must refer to only one user otherwise conflict between the users can happen. To solve this conflict every website must have the functionality to not accept the email that already exists on the website. This functionality can be implemented anywhere in our code like in index file or route file but this comes under the validation part. So we usually prefer to code this logic where all the other validations are coded. Here we use ‘express-validator’ middleware to implement this functionality.
Command to install express-validator:
npm install express-validator
Steps to use express-validator to implement the logic:
Install express-validator middleware.
Create a validator.js file to code all the validation logic.
Validate email by validateEmail : check(’email’) and chain on all the validation with ‘ . ‘
Use the validation name(validateEmail) in the routes as a middleware as an array of validations.
Destructure ‘validationResult’ function from express-validator to use it to find any errors.
If error occurs redirect to the same page passing the error information.
If error list is empty, give access to the user for the subsequent request.
Note: Here we use local or custom database to implement the logic, the same steps can be followed to implement the logic in a regular database like MongoDB or MySql.
Example: This example illustrates how to check if email address is already in use or not for a particular website.
Filename: index.js
javascript
const express = require('express')const bodyParser = require('body-parser')const { validationResult } = require('express-validator')const repo = require('./repository')const { validateEmail } = require('./validator')const signupTemplet = require('./signup') const app = express() const port = process.env.PORT || 3000 // The body-parser middleware to parse form dataapp.use(bodyParser.urlencoded({ extended: true })) // Get route to display HTML form to sign upapp.get('/signup', (req, res) => { res.send(signupTemplet({}))}) // Post route to handle form submission logic andapp.post( '/signup', [validateEmail], async (req, res) => { const errors = validationResult(req) if (!errors.isEmpty()) { return res.send(signupTemplet({ errors })) } const { email, password } = req.body await repo.create({ email, password }) res.send('Sign Up successfully') }) // Server setupapp.listen(port, () => { console.log(`Server start on port ${port}`)})
Filename: repository.js This file contains all the logic to create a local database and interact with it.
javascript
// Importing node.js file system moduleconst fs = require('fs') class Repository { constructor(filename) { // The filename where datas are // going to store if (!filename) { throw new Error('Filename is required to create a datastore!') } this.filename = filename try { fs.accessSync(this.filename) } catch (err) { // If file not exist it is created // with empty array fs.writeFileSync(this.filename, '[]') } } // Get all existing records async getAll() { return JSON.parse( await fs.promises.readFile(this.filename, { encoding: 'utf8' }) ) } // Find record by properties async getOneBy(filters) { const records = await this.getAll() for (let record of records) { let found = true for (let key in filters) { if (record[key] !== filters[key]) { found = false } } if (found) return record; } } // Create new record async create(attrs) { const records = await this.getAll() records.push(attrs) await fs.promises.writeFile( this.filename, JSON.stringify(records, null, 2) ) return attrs }} // The 'datastore.json' file created at runtime// and all the information provided via signup form// store in this file in JSON format.module.exports = new Repository('datastore.json')
Filename: signup.js This file contains logic to show sign up form.
javascript
const getError = (errors, prop) => { try { // Return error message if any error occurs return errors.mapped()[prop].msg } catch (error) { // Return empty string if no error return '' }} module.exports = ({ errors }) => { return ` <!DOCTYPE html> <html> <head> <link rel='stylesheet'href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.9.0/css/bulma.min.css'> <style> div.columns{ margin-top: 100px; } .button{ margin-top : 10px } </style> </head> <body> <div class='container'> <div class='columns is-centered'> <div class='column is-5'> <h1 class='title'>Sign Up<h1> <form method='POST'> <div> <div> <label class='label' id='email'>Username</label> </div> <input class='input' type='text' name='email' placeholder='Email' for='email'> <p class="help is-danger"> ${getError(errors, 'email')} </p> </div> <div> <div> <label class='label' id='password'> Password </label> </div> <input class='input' type='password' name='password' placeholder='Password' for='password'> </div> <div> <button class='button is-primary'> Sign Up </button> </div> </form> </div> </div> </div> </body> </html> `}
Filename: validator.js This file contain all the validation logic (Logic to see if email already exist or not).
javascript
const { check } = require('express-validator')const repo = require('./repository') module.exports = { validateEmail: check('email') // To delete leading and triling space .trim() // Normalizing the email address .normalizeEmail() // Checking if follow the email // address format or not .isEmail() // Custom message .withMessage('Invalid email') // Custom validation // Validate email in use or not .custom(async (email) => { const existingUser = await repo.getOneBy({ email }) if (existingUser) { throw new Error('Email already in use') } })}
Run index.js file using the following command:
node index.js
Filename: package.json
package.json file
Database:
Database
Output:
Sign Up with email already in use
Response when Sign Up with email that already in use
Sign Up with email that not in use
Response when Sign Up with email that not in use
Database after successful Sign Up(Sign Up with email that not in use)
Database after successful Sign Up(Sign Up with email that not in use)
Note: We have used some Bulma classes (CSS framework) in the signup.js file to design the content.
rkbhola5
Node.js-Misc
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to install the previous version of node.js and npm ?
Node.js fs.writeFile() Method
Difference between promise and async await in Node.js
Mongoose | findByIdAndUpdate() Function
JWT Authentication with Node.js
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Apr, 2022"
},
{
"code": null,
"e": 696,
"s": 28,
"text": "The registration or Sign Up in any website always requires a username. Most of the time we use ’email’ to register on a website. The registration email is always unique and must refer to only one user otherwise conflict between the users can happen. To solve this conflict every website must have the functionality to not accept the email that already exists on the website. This functionality can be implemented anywhere in our code like in index file or route file but this comes under the validation part. So we usually prefer to code this logic where all the other validations are coded. Here we use ‘express-validator’ middleware to implement this functionality."
},
{
"code": null,
"e": 734,
"s": 696,
"text": "Command to install express-validator:"
},
{
"code": null,
"e": 764,
"s": 734,
"text": "npm install express-validator"
},
{
"code": null,
"e": 819,
"s": 764,
"text": "Steps to use express-validator to implement the logic:"
},
{
"code": null,
"e": 857,
"s": 819,
"text": "Install express-validator middleware."
},
{
"code": null,
"e": 918,
"s": 857,
"text": "Create a validator.js file to code all the validation logic."
},
{
"code": null,
"e": 1010,
"s": 918,
"text": "Validate email by validateEmail : check(’email’) and chain on all the validation with ‘ . ‘"
},
{
"code": null,
"e": 1107,
"s": 1010,
"text": "Use the validation name(validateEmail) in the routes as a middleware as an array of validations."
},
{
"code": null,
"e": 1200,
"s": 1107,
"text": "Destructure ‘validationResult’ function from express-validator to use it to find any errors."
},
{
"code": null,
"e": 1273,
"s": 1200,
"text": "If error occurs redirect to the same page passing the error information."
},
{
"code": null,
"e": 1349,
"s": 1273,
"text": "If error list is empty, give access to the user for the subsequent request."
},
{
"code": null,
"e": 1515,
"s": 1349,
"text": "Note: Here we use local or custom database to implement the logic, the same steps can be followed to implement the logic in a regular database like MongoDB or MySql."
},
{
"code": null,
"e": 1630,
"s": 1515,
"text": "Example: This example illustrates how to check if email address is already in use or not for a particular website."
},
{
"code": null,
"e": 1649,
"s": 1630,
"text": "Filename: index.js"
},
{
"code": null,
"e": 1660,
"s": 1649,
"text": "javascript"
},
{
"code": "const express = require('express')const bodyParser = require('body-parser')const { validationResult } = require('express-validator')const repo = require('./repository')const { validateEmail } = require('./validator')const signupTemplet = require('./signup') const app = express() const port = process.env.PORT || 3000 // The body-parser middleware to parse form dataapp.use(bodyParser.urlencoded({ extended: true })) // Get route to display HTML form to sign upapp.get('/signup', (req, res) => { res.send(signupTemplet({}))}) // Post route to handle form submission logic andapp.post( '/signup', [validateEmail], async (req, res) => { const errors = validationResult(req) if (!errors.isEmpty()) { return res.send(signupTemplet({ errors })) } const { email, password } = req.body await repo.create({ email, password }) res.send('Sign Up successfully') }) // Server setupapp.listen(port, () => { console.log(`Server start on port ${port}`)})",
"e": 2671,
"s": 1660,
"text": null
},
{
"code": null,
"e": 2777,
"s": 2671,
"text": "Filename: repository.js This file contains all the logic to create a local database and interact with it."
},
{
"code": null,
"e": 2788,
"s": 2777,
"text": "javascript"
},
{
"code": "// Importing node.js file system moduleconst fs = require('fs') class Repository { constructor(filename) { // The filename where datas are // going to store if (!filename) { throw new Error('Filename is required to create a datastore!') } this.filename = filename try { fs.accessSync(this.filename) } catch (err) { // If file not exist it is created // with empty array fs.writeFileSync(this.filename, '[]') } } // Get all existing records async getAll() { return JSON.parse( await fs.promises.readFile(this.filename, { encoding: 'utf8' }) ) } // Find record by properties async getOneBy(filters) { const records = await this.getAll() for (let record of records) { let found = true for (let key in filters) { if (record[key] !== filters[key]) { found = false } } if (found) return record; } } // Create new record async create(attrs) { const records = await this.getAll() records.push(attrs) await fs.promises.writeFile( this.filename, JSON.stringify(records, null, 2) ) return attrs }} // The 'datastore.json' file created at runtime// and all the information provided via signup form// store in this file in JSON format.module.exports = new Repository('datastore.json')",
"e": 4334,
"s": 2788,
"text": null
},
{
"code": null,
"e": 4401,
"s": 4334,
"text": "Filename: signup.js This file contains logic to show sign up form."
},
{
"code": null,
"e": 4412,
"s": 4401,
"text": "javascript"
},
{
"code": "const getError = (errors, prop) => { try { // Return error message if any error occurs return errors.mapped()[prop].msg } catch (error) { // Return empty string if no error return '' }} module.exports = ({ errors }) => { return ` <!DOCTYPE html> <html> <head> <link rel='stylesheet'href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.9.0/css/bulma.min.css'> <style> div.columns{ margin-top: 100px; } .button{ margin-top : 10px } </style> </head> <body> <div class='container'> <div class='columns is-centered'> <div class='column is-5'> <h1 class='title'>Sign Up<h1> <form method='POST'> <div> <div> <label class='label' id='email'>Username</label> </div> <input class='input' type='text' name='email' placeholder='Email' for='email'> <p class=\"help is-danger\"> ${getError(errors, 'email')} </p> </div> <div> <div> <label class='label' id='password'> Password </label> </div> <input class='input' type='password' name='password' placeholder='Password' for='password'> </div> <div> <button class='button is-primary'> Sign Up </button> </div> </form> </div> </div> </div> </body> </html> `}",
"e": 6359,
"s": 4412,
"text": null
},
{
"code": null,
"e": 6471,
"s": 6359,
"text": "Filename: validator.js This file contain all the validation logic (Logic to see if email already exist or not)."
},
{
"code": null,
"e": 6482,
"s": 6471,
"text": "javascript"
},
{
"code": "const { check } = require('express-validator')const repo = require('./repository') module.exports = { validateEmail: check('email') // To delete leading and triling space .trim() // Normalizing the email address .normalizeEmail() // Checking if follow the email // address format or not .isEmail() // Custom message .withMessage('Invalid email') // Custom validation // Validate email in use or not .custom(async (email) => { const existingUser = await repo.getOneBy({ email }) if (existingUser) { throw new Error('Email already in use') } })}",
"e": 7206,
"s": 6482,
"text": null
},
{
"code": null,
"e": 7253,
"s": 7206,
"text": "Run index.js file using the following command:"
},
{
"code": null,
"e": 7267,
"s": 7253,
"text": "node index.js"
},
{
"code": null,
"e": 7290,
"s": 7267,
"text": "Filename: package.json"
},
{
"code": null,
"e": 7308,
"s": 7290,
"text": "package.json file"
},
{
"code": null,
"e": 7318,
"s": 7308,
"text": "Database:"
},
{
"code": null,
"e": 7327,
"s": 7318,
"text": "Database"
},
{
"code": null,
"e": 7335,
"s": 7327,
"text": "Output:"
},
{
"code": null,
"e": 7369,
"s": 7335,
"text": "Sign Up with email already in use"
},
{
"code": null,
"e": 7422,
"s": 7369,
"text": "Response when Sign Up with email that already in use"
},
{
"code": null,
"e": 7457,
"s": 7422,
"text": "Sign Up with email that not in use"
},
{
"code": null,
"e": 7506,
"s": 7457,
"text": "Response when Sign Up with email that not in use"
},
{
"code": null,
"e": 7576,
"s": 7506,
"text": "Database after successful Sign Up(Sign Up with email that not in use)"
},
{
"code": null,
"e": 7646,
"s": 7576,
"text": "Database after successful Sign Up(Sign Up with email that not in use)"
},
{
"code": null,
"e": 7745,
"s": 7646,
"text": "Note: We have used some Bulma classes (CSS framework) in the signup.js file to design the content."
},
{
"code": null,
"e": 7754,
"s": 7745,
"text": "rkbhola5"
},
{
"code": null,
"e": 7767,
"s": 7754,
"text": "Node.js-Misc"
},
{
"code": null,
"e": 7775,
"s": 7767,
"text": "Node.js"
},
{
"code": null,
"e": 7792,
"s": 7775,
"text": "Web Technologies"
},
{
"code": null,
"e": 7890,
"s": 7792,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7947,
"s": 7890,
"text": "How to install the previous version of node.js and npm ?"
},
{
"code": null,
"e": 7977,
"s": 7947,
"text": "Node.js fs.writeFile() Method"
},
{
"code": null,
"e": 8031,
"s": 7977,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 8071,
"s": 8031,
"text": "Mongoose | findByIdAndUpdate() Function"
},
{
"code": null,
"e": 8103,
"s": 8071,
"text": "JWT Authentication with Node.js"
},
{
"code": null,
"e": 8165,
"s": 8103,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 8226,
"s": 8165,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 8276,
"s": 8226,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 8319,
"s": 8276,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
VLAN ACL (VACL)
|
19 Oct, 2021
Prerequisite – Virtual LAN (VLAN), Access-lists (ACL) VLAN (Virtual LAN) is a concept in which we divide the broadcast domain into smaller broadcast domains logically at layer 2. If we create different VLANs then by default, a host from one VLAN can communicate with all the hosts residing in the same VLAN. If we want some hosts not able to reach other hosts within the same VLAN, then the concept of VLAN Access-list or Private VLAN can be used. (Access-list, is a set of various permit or deny conditions, used for packet filtering)
VLAN ACL (VACL) – VLAN ACL is used to filter traffic of a VLAN (traffic within a VLAN i.e traffic for destination host residing in the same VLAN). All packets entering the VLAN are checked against the VACL. Unlike Router ACL, VACL is not defined in a direction but it is possible to filter traffic based on the direction of the traffic by combining VACLs and Private VLAN features.
Procedure –
Define the standard or extended access list to be used in VACL – An access list should be defined to identify the type of traffic and the hosts on which it is applied.Define a VLAN access map – A VLAN access-map is defined in which hosts IP address will be matched (using the access-list defined)Configure an action clause in a VLAN access map sequence – This will tell what action (forward or drop) should be taken on the traffic (defined in the VLAN access map)Apply the VLAN access map to the specified VLANs – The last step in the configuration of VACL is to create a filter list specifying, on which VLAN the access map has been applied.Display VLAN access map information – We can verify the information by using the command.
Define the standard or extended access list to be used in VACL – An access list should be defined to identify the type of traffic and the hosts on which it is applied.
Define a VLAN access map – A VLAN access-map is defined in which hosts IP address will be matched (using the access-list defined)
Configure an action clause in a VLAN access map sequence – This will tell what action (forward or drop) should be taken on the traffic (defined in the VLAN access map)
Apply the VLAN access map to the specified VLANs – The last step in the configuration of VACL is to create a filter list specifying, on which VLAN the access map has been applied.
Display VLAN access map information – We can verify the information by using the command.
Configuration –
There is a switch named switch1 which is connected to 3 routers named Router1 (IP address-192.168.1.1/24), Router2 (IP address-192.168.1.2/24), and Router3 (IP address-192.168.1.3/24) as shown in the figure. Configuring IP address on Router1.
Router1(config)#int fa0/0
Router1(config-if)#ip address 192.168.1.1 255.255.255.0
Router1(config-if)#no shut
Configuring IP address on Router2.
Router2(config)#int fa0/0
Router2(config-if)#ip address 192.168.1.2 255.255.255.0
Router2(config-if)#no shut
Configuring IP address on Router3.
Router3(config)#int fa0/0
Router3(config-if)#ip address 192.168.1.3 255.255.255.0
Router3(config-if)#no shut
In this task, we will deny traffic from Router1 to Router3 using VACL.
Configuring access-list on switch1 stating that all IP traffic should be allowed from host 192.168.1.1 to 192.168.1.3
switch1(config)#ip access-list extended My_access_list
switch1(config-ext-nacl)#permit ip host 192.168.1.1 host 192.168.1.3
Now, configuring VLAN access-map which states that match the IP address defined in access-list and take action of drop (which means traffic should not be allowed from 192.168.1.1 to 192.168.1.3).
switch1(config)#vlan access-map Mapping 10
switch1(config-access-map)#match ip address My_access_list
switch1(config-access-map)#action drop
switch1(config-access-map)#exit
In the first command, 10 is the sequence number of the access map. If we do not define any sequence number then it will automatically take 10 as a sequence number. Now, for the traffic from Router1 (192.168.1.1) to Router3 (192.168.1.3), the traffic will be dropped but what about the traffic from Router2 to Router3?
The traffic from Router2 to Router3 will also get drop because no action is defined for this traffic (implicit deny). Therefore, we have to define another rule stating that the other traffic should be allowed.
switch1(config)#vlan access-map Mapping 20
switch1(config-access-map)#action forward
switch1(config-access-map)#exit
In the first command, 20 is the sequence number which means this rule will be checked after the first rule having sequence number 10.
At last, we will assign this access-map, named My_access_list, to a VLAN (here VLAN 1)
switch1(config)#vlan filter Mapping vlan-list 1
To verify the configuration, use the command.
switch1#show vlan access-map
This command will display the access map. This will display the name of the access-map, sequence number of the rule, and the access-list name (that has been used).
switch1#show vlan filter
This will display the VLANs which are filtered by the VLAN access map.
vivekpal23123451254
niharikatanwar61
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Differences between IPv4 and IPv6
GSM in Wireless Communication
Secure Socket Layer (SSL)
Wireless Application Protocol
Mobile Internet Protocol (or Mobile IP)
User Datagram Protocol (UDP)
Introduction of Mobile Ad hoc Network (MANET)
Types of area networks - LAN, MAN and WAN
Advanced Encryption Standard (AES)
Cryptography and its Types
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Oct, 2021"
},
{
"code": null,
"e": 565,
"s": 28,
"text": "Prerequisite – Virtual LAN (VLAN), Access-lists (ACL) VLAN (Virtual LAN) is a concept in which we divide the broadcast domain into smaller broadcast domains logically at layer 2. If we create different VLANs then by default, a host from one VLAN can communicate with all the hosts residing in the same VLAN. If we want some hosts not able to reach other hosts within the same VLAN, then the concept of VLAN Access-list or Private VLAN can be used. (Access-list, is a set of various permit or deny conditions, used for packet filtering) "
},
{
"code": null,
"e": 948,
"s": 565,
"text": "VLAN ACL (VACL) – VLAN ACL is used to filter traffic of a VLAN (traffic within a VLAN i.e traffic for destination host residing in the same VLAN). All packets entering the VLAN are checked against the VACL. Unlike Router ACL, VACL is not defined in a direction but it is possible to filter traffic based on the direction of the traffic by combining VACLs and Private VLAN features. "
},
{
"code": null,
"e": 961,
"s": 948,
"text": "Procedure – "
},
{
"code": null,
"e": 1693,
"s": 961,
"text": "Define the standard or extended access list to be used in VACL – An access list should be defined to identify the type of traffic and the hosts on which it is applied.Define a VLAN access map – A VLAN access-map is defined in which hosts IP address will be matched (using the access-list defined)Configure an action clause in a VLAN access map sequence – This will tell what action (forward or drop) should be taken on the traffic (defined in the VLAN access map)Apply the VLAN access map to the specified VLANs – The last step in the configuration of VACL is to create a filter list specifying, on which VLAN the access map has been applied.Display VLAN access map information – We can verify the information by using the command."
},
{
"code": null,
"e": 1861,
"s": 1693,
"text": "Define the standard or extended access list to be used in VACL – An access list should be defined to identify the type of traffic and the hosts on which it is applied."
},
{
"code": null,
"e": 1991,
"s": 1861,
"text": "Define a VLAN access map – A VLAN access-map is defined in which hosts IP address will be matched (using the access-list defined)"
},
{
"code": null,
"e": 2159,
"s": 1991,
"text": "Configure an action clause in a VLAN access map sequence – This will tell what action (forward or drop) should be taken on the traffic (defined in the VLAN access map)"
},
{
"code": null,
"e": 2339,
"s": 2159,
"text": "Apply the VLAN access map to the specified VLANs – The last step in the configuration of VACL is to create a filter list specifying, on which VLAN the access map has been applied."
},
{
"code": null,
"e": 2429,
"s": 2339,
"text": "Display VLAN access map information – We can verify the information by using the command."
},
{
"code": null,
"e": 2446,
"s": 2429,
"text": "Configuration – "
},
{
"code": null,
"e": 2690,
"s": 2446,
"text": "There is a switch named switch1 which is connected to 3 routers named Router1 (IP address-192.168.1.1/24), Router2 (IP address-192.168.1.2/24), and Router3 (IP address-192.168.1.3/24) as shown in the figure. Configuring IP address on Router1. "
},
{
"code": null,
"e": 2799,
"s": 2690,
"text": "Router1(config)#int fa0/0\nRouter1(config-if)#ip address 192.168.1.1 255.255.255.0\nRouter1(config-if)#no shut"
},
{
"code": null,
"e": 2835,
"s": 2799,
"text": "Configuring IP address on Router2. "
},
{
"code": null,
"e": 2944,
"s": 2835,
"text": "Router2(config)#int fa0/0\nRouter2(config-if)#ip address 192.168.1.2 255.255.255.0\nRouter2(config-if)#no shut"
},
{
"code": null,
"e": 2980,
"s": 2944,
"text": "Configuring IP address on Router3. "
},
{
"code": null,
"e": 3089,
"s": 2980,
"text": "Router3(config)#int fa0/0\nRouter3(config-if)#ip address 192.168.1.3 255.255.255.0\nRouter3(config-if)#no shut"
},
{
"code": null,
"e": 3161,
"s": 3089,
"text": "In this task, we will deny traffic from Router1 to Router3 using VACL. "
},
{
"code": null,
"e": 3281,
"s": 3161,
"text": "Configuring access-list on switch1 stating that all IP traffic should be allowed from host 192.168.1.1 to 192.168.1.3 "
},
{
"code": null,
"e": 3406,
"s": 3281,
"text": "switch1(config)#ip access-list extended My_access_list\nswitch1(config-ext-nacl)#permit ip host 192.168.1.1 host 192.168.1.3 "
},
{
"code": null,
"e": 3603,
"s": 3406,
"text": "Now, configuring VLAN access-map which states that match the IP address defined in access-list and take action of drop (which means traffic should not be allowed from 192.168.1.1 to 192.168.1.3). "
},
{
"code": null,
"e": 3777,
"s": 3603,
"text": "switch1(config)#vlan access-map Mapping 10\nswitch1(config-access-map)#match ip address My_access_list\nswitch1(config-access-map)#action drop \nswitch1(config-access-map)#exit"
},
{
"code": null,
"e": 4096,
"s": 3777,
"text": "In the first command, 10 is the sequence number of the access map. If we do not define any sequence number then it will automatically take 10 as a sequence number. Now, for the traffic from Router1 (192.168.1.1) to Router3 (192.168.1.3), the traffic will be dropped but what about the traffic from Router2 to Router3? "
},
{
"code": null,
"e": 4308,
"s": 4096,
"text": "The traffic from Router2 to Router3 will also get drop because no action is defined for this traffic (implicit deny). Therefore, we have to define another rule stating that the other traffic should be allowed. "
},
{
"code": null,
"e": 4426,
"s": 4308,
"text": "switch1(config)#vlan access-map Mapping 20\nswitch1(config-access-map)#action forward \nswitch1(config-access-map)#exit"
},
{
"code": null,
"e": 4561,
"s": 4426,
"text": "In the first command, 20 is the sequence number which means this rule will be checked after the first rule having sequence number 10. "
},
{
"code": null,
"e": 4649,
"s": 4561,
"text": "At last, we will assign this access-map, named My_access_list, to a VLAN (here VLAN 1) "
},
{
"code": null,
"e": 4697,
"s": 4649,
"text": "switch1(config)#vlan filter Mapping vlan-list 1"
},
{
"code": null,
"e": 4744,
"s": 4697,
"text": "To verify the configuration, use the command. "
},
{
"code": null,
"e": 4773,
"s": 4744,
"text": "switch1#show vlan access-map"
},
{
"code": null,
"e": 4939,
"s": 4773,
"text": "This command will display the access map. This will display the name of the access-map, sequence number of the rule, and the access-list name (that has been used). "
},
{
"code": null,
"e": 4964,
"s": 4939,
"text": "switch1#show vlan filter"
},
{
"code": null,
"e": 5036,
"s": 4964,
"text": "This will display the VLANs which are filtered by the VLAN access map. "
},
{
"code": null,
"e": 5056,
"s": 5036,
"text": "vivekpal23123451254"
},
{
"code": null,
"e": 5073,
"s": 5056,
"text": "niharikatanwar61"
},
{
"code": null,
"e": 5091,
"s": 5073,
"text": "Computer Networks"
},
{
"code": null,
"e": 5109,
"s": 5091,
"text": "Computer Networks"
},
{
"code": null,
"e": 5207,
"s": 5109,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5241,
"s": 5207,
"text": "Differences between IPv4 and IPv6"
},
{
"code": null,
"e": 5271,
"s": 5241,
"text": "GSM in Wireless Communication"
},
{
"code": null,
"e": 5297,
"s": 5271,
"text": "Secure Socket Layer (SSL)"
},
{
"code": null,
"e": 5327,
"s": 5297,
"text": "Wireless Application Protocol"
},
{
"code": null,
"e": 5367,
"s": 5327,
"text": "Mobile Internet Protocol (or Mobile IP)"
},
{
"code": null,
"e": 5396,
"s": 5367,
"text": "User Datagram Protocol (UDP)"
},
{
"code": null,
"e": 5442,
"s": 5396,
"text": "Introduction of Mobile Ad hoc Network (MANET)"
},
{
"code": null,
"e": 5484,
"s": 5442,
"text": "Types of area networks - LAN, MAN and WAN"
},
{
"code": null,
"e": 5519,
"s": 5484,
"text": "Advanced Encryption Standard (AES)"
}
] |
How to create Neon Light Button using HTML and CSS ?
|
16 Aug, 2021
The neon light button animation effect can be easily generated by using HTML and CSS. By using HTML we will design the basic structure of the button and then by using the properties of CSS, we can create the neon light animation effect. HTML code: In this section, we will design a simple button structure using anchor tag.
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <title> How to create Neon Light Button using HTML and CSS? </title></head> <body> <a>GeeksForGeeks</a></body> </html>
CSS code: In this section, we will use some CSS properties to design the button and use hover class to get the animation effect when we hover the mouse over the button.
CSS
<style> /*styling background*/ body { margin: 0; padding: 0; display: flex; height: 100vh; justify-content: center; align-items: center; background-color: #000; font-family: sans-serif; } /* styling the button*/ a { padding: 20px 20px; display: inline-block; color: #008000; letter-spacing: 2px; text-transform: uppercase; text-decoration: none; font-size: 3em; overflow: hidden; } /*creating animation effect*/ a:hover { color: #111; background: #39ff14; box-shadow: 0 0 50px #39ff14; }</style>
Complete Code: In this section, we will combine the above two section to create a Neon Light Button using HTML abd CSS.
HTML
<!DOCTYPE html><html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title> How to create Neon Light Button using HTML and CSS? </title> <style> /*styling background*/ body { margin: 0; padding: 0; display: flex; height: 100vh; justify-content: center; align-items: center; background-color: #000; font-family: sans-serif; } /* styling the button*/ a { padding: 20px 20px; display: inline-block; color: #008000; letter-spacing: 2px; text-transform: uppercase; text-decoration: none; font-size: 3em; overflow: hidden; } /*creating animation effect*/ a:hover { color: #111; background: #39ff14; box-shadow: 0 0 50px #39ff14; } </style></head> <body> <a>GeeksForGeeks</a></body> </html>
Output:
kapoorsagar226
CSS-Misc
HTML-Misc
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of CSS (Cascading Style Sheet)
How to set space between the flexbox ?
Design a Tribute Page using HTML & CSS
How to position a div at the bottom of its container using CSS?
How to Upload Image into Database and Display it using PHP ?
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 ?
Types of CSS (Cascading Style Sheet)
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Aug, 2021"
},
{
"code": null,
"e": 353,
"s": 28,
"text": "The neon light button animation effect can be easily generated by using HTML and CSS. By using HTML we will design the basic structure of the button and then by using the properties of CSS, we can create the neon light animation effect. HTML code: In this section, we will design a simple button structure using anchor tag. "
},
{
"code": null,
"e": 358,
"s": 353,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <title> How to create Neon Light Button using HTML and CSS? </title></head> <body> <a>GeeksForGeeks</a></body> </html>",
"e": 565,
"s": 358,
"text": null
},
{
"code": null,
"e": 735,
"s": 565,
"text": "CSS code: In this section, we will use some CSS properties to design the button and use hover class to get the animation effect when we hover the mouse over the button. "
},
{
"code": null,
"e": 739,
"s": 735,
"text": "CSS"
},
{
"code": "<style> /*styling background*/ body { margin: 0; padding: 0; display: flex; height: 100vh; justify-content: center; align-items: center; background-color: #000; font-family: sans-serif; } /* styling the button*/ a { padding: 20px 20px; display: inline-block; color: #008000; letter-spacing: 2px; text-transform: uppercase; text-decoration: none; font-size: 3em; overflow: hidden; } /*creating animation effect*/ a:hover { color: #111; background: #39ff14; box-shadow: 0 0 50px #39ff14; }</style>",
"e": 1397,
"s": 739,
"text": null
},
{
"code": null,
"e": 1518,
"s": 1397,
"text": "Complete Code: In this section, we will combine the above two section to create a Neon Light Button using HTML abd CSS. "
},
{
"code": null,
"e": 1523,
"s": 1518,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\" dir=\"ltr\"> <head> <meta charset=\"utf-8\"> <title> How to create Neon Light Button using HTML and CSS? </title> <style> /*styling background*/ body { margin: 0; padding: 0; display: flex; height: 100vh; justify-content: center; align-items: center; background-color: #000; font-family: sans-serif; } /* styling the button*/ a { padding: 20px 20px; display: inline-block; color: #008000; letter-spacing: 2px; text-transform: uppercase; text-decoration: none; font-size: 3em; overflow: hidden; } /*creating animation effect*/ a:hover { color: #111; background: #39ff14; box-shadow: 0 0 50px #39ff14; } </style></head> <body> <a>GeeksForGeeks</a></body> </html>",
"e": 2518,
"s": 1523,
"text": null
},
{
"code": null,
"e": 2528,
"s": 2518,
"text": "Output: "
},
{
"code": null,
"e": 2545,
"s": 2530,
"text": "kapoorsagar226"
},
{
"code": null,
"e": 2554,
"s": 2545,
"text": "CSS-Misc"
},
{
"code": null,
"e": 2564,
"s": 2554,
"text": "HTML-Misc"
},
{
"code": null,
"e": 2568,
"s": 2564,
"text": "CSS"
},
{
"code": null,
"e": 2573,
"s": 2568,
"text": "HTML"
},
{
"code": null,
"e": 2590,
"s": 2573,
"text": "Web Technologies"
},
{
"code": null,
"e": 2617,
"s": 2590,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 2622,
"s": 2617,
"text": "HTML"
},
{
"code": null,
"e": 2720,
"s": 2622,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2757,
"s": 2720,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 2796,
"s": 2757,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 2835,
"s": 2796,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 2899,
"s": 2835,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 2960,
"s": 2899,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 2984,
"s": 2960,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 3037,
"s": 2984,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 3097,
"s": 3037,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 3158,
"s": 3097,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
PyQt5 – Changing size of Indicator in Check Box
|
22 Apr, 2020
In this article we will see how to change the size of indicator. Indicator is the part of check box although if we change the size of check box with the help of resize method or setGeometry method, but it will change the size of check box but not the indicator.
In order to change the size of indicator we have to change the height and width in the style sheet of the indicator which is used with check box object. Below is the style sheet code.
QCheckBox::indicator
{
width : 40px;
height : 40px;
}
Below is the implementation.
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom 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 the check-box checkbox = QCheckBox('Geek ?', self) # setting geometry of check box checkbox.setGeometry(200, 150, 100, 80) # setting stylesheet # changing width and height of indicator checkbox.setStyleSheet("QCheckBox::indicator" "{" "width :40px;" "height : 40px;" "}") # 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.
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": "\n22 Apr, 2020"
},
{
"code": null,
"e": 290,
"s": 28,
"text": "In this article we will see how to change the size of indicator. Indicator is the part of check box although if we change the size of check box with the help of resize method or setGeometry method, but it will change the size of check box but not the indicator."
},
{
"code": null,
"e": 474,
"s": 290,
"text": "In order to change the size of indicator we have to change the height and width in the style sheet of the indicator which is used with check box object. Below is the style sheet code."
},
{
"code": null,
"e": 529,
"s": 474,
"text": "QCheckBox::indicator\n{\nwidth : 40px;\nheight : 40px;\n}\n"
},
{
"code": null,
"e": 558,
"s": 529,
"text": "Below is the implementation."
},
{
"code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom 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 the check-box checkbox = QCheckBox('Geek ?', self) # setting geometry of check box checkbox.setGeometry(200, 150, 100, 80) # setting stylesheet # changing width and height of indicator checkbox.setStyleSheet(\"QCheckBox::indicator\" \"{\" \"width :40px;\" \"height : 40px;\" \"}\") # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 1681,
"s": 558,
"text": null
},
{
"code": null,
"e": 1690,
"s": 1681,
"text": "Output :"
},
{
"code": null,
"e": 1701,
"s": 1690,
"text": "Python-gui"
},
{
"code": null,
"e": 1713,
"s": 1701,
"text": "Python-PyQt"
},
{
"code": null,
"e": 1720,
"s": 1713,
"text": "Python"
},
{
"code": null,
"e": 1818,
"s": 1720,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1836,
"s": 1818,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1878,
"s": 1836,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1900,
"s": 1878,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1935,
"s": 1900,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1961,
"s": 1935,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1993,
"s": 1961,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2022,
"s": 1993,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2052,
"s": 2022,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 2079,
"s": 2052,
"text": "Python Classes and Objects"
}
] |
Stream skip() method in Java with examples
|
06 Dec, 2018
Prerequisite : Streams in javaThe skip(long N) is a method of java.util.stream.Stream object. This method takes one long (N) as an argument and returns a stream after removing first N elements. skip() can be quite expensive on ordered parallel pipelines, if the value of N is large, because skip(N) is constrained to skip the first N elements in the encounter order and not just any n elements.Note : If a stream contains less than N elements, then an empty stream is returned.
Syntax :
Stream<T> skip(long N)
Where N is the number of elements to be skipped
and this function returns new stream as output.
Exception : If the value of N is negative, then IllegalArgumentException is thrown by the function.
Example 1 : Implementation of skip function.
// Java code for skip() functionimport java.util.*; class GFG { // Driver code public static void main(String[] args) { // Creating a list of integers List<Integer> list = new ArrayList<Integer>(); // adding elements in the list list.add(-2); list.add(0); list.add(2); list.add(4); list.add(6); list.add(8); list.add(10); list.add(12); list.add(14); list.add(16); // setting the value of N as 4 int limit = 4; int count = 0; Iterator<Integer> it = list.iterator(); // Iterating through the list of integers while (it.hasNext()) { it.next(); count++; // Check if first four i.e, (equal to N) // integers are iterated. if (count <= limit) { // If yes then remove first N elements. it.remove(); } } System.out.print("New stream is : "); // Displaying new stream for (Integer number : list) { System.out.print(number + " "); } }}
Output :
New stream is : 6 8 10 12 14 16
Application :
// Java code for skip() functionimport java.util.stream.Stream;import java.util.ArrayList;import java.util.List; class gfg{ // Function to skip the elements of stream upto given range, i.e, 3 public static Stream<String> skip_func(Stream<String> ss, int range){ return ss.skip(range); } // Driver code public static void main(String[] args){ // list to save stream of strings List<String> arr = new ArrayList<>(); arr.add("geeks"); arr.add("for"); arr.add("geeks"); arr.add("computer"); arr.add("science"); Stream<String> str = arr.stream(); // calling function to skip the elements to range 3 Stream<String> sk = skip_func(str,3); sk.forEach(System.out::println); } }
Output :
computer
science
Difference between limit() and skip() :
The limit() method returns a reduced stream of first N elements but skip() method returns a stream of remaining elements after skipping first N elements.limit() is a short-circuiting stateful intermediate operation i.e, when processed with an infinite input, it may produce a finite stream as a result without processing the entire input but skip() is a stateful intermediate operation i.e, it may need to process the entire input before producing a result.
The limit() method returns a reduced stream of first N elements but skip() method returns a stream of remaining elements after skipping first N elements.
limit() is a short-circuiting stateful intermediate operation i.e, when processed with an infinite input, it may produce a finite stream as a result without processing the entire input but skip() is a stateful intermediate operation i.e, it may need to process the entire input before producing a result.
Java - util package
Java-Functions
java-stream
Java-Stream interface
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n06 Dec, 2018"
},
{
"code": null,
"e": 532,
"s": 54,
"text": "Prerequisite : Streams in javaThe skip(long N) is a method of java.util.stream.Stream object. This method takes one long (N) as an argument and returns a stream after removing first N elements. skip() can be quite expensive on ordered parallel pipelines, if the value of N is large, because skip(N) is constrained to skip the first N elements in the encounter order and not just any n elements.Note : If a stream contains less than N elements, then an empty stream is returned."
},
{
"code": null,
"e": 541,
"s": 532,
"text": "Syntax :"
},
{
"code": null,
"e": 662,
"s": 541,
"text": "Stream<T> skip(long N)\n\nWhere N is the number of elements to be skipped\nand this function returns new stream as output.\n"
},
{
"code": null,
"e": 762,
"s": 662,
"text": "Exception : If the value of N is negative, then IllegalArgumentException is thrown by the function."
},
{
"code": null,
"e": 807,
"s": 762,
"text": "Example 1 : Implementation of skip function."
},
{
"code": "// Java code for skip() functionimport java.util.*; class GFG { // Driver code public static void main(String[] args) { // Creating a list of integers List<Integer> list = new ArrayList<Integer>(); // adding elements in the list list.add(-2); list.add(0); list.add(2); list.add(4); list.add(6); list.add(8); list.add(10); list.add(12); list.add(14); list.add(16); // setting the value of N as 4 int limit = 4; int count = 0; Iterator<Integer> it = list.iterator(); // Iterating through the list of integers while (it.hasNext()) { it.next(); count++; // Check if first four i.e, (equal to N) // integers are iterated. if (count <= limit) { // If yes then remove first N elements. it.remove(); } } System.out.print(\"New stream is : \"); // Displaying new stream for (Integer number : list) { System.out.print(number + \" \"); } }}",
"e": 1939,
"s": 807,
"text": null
},
{
"code": null,
"e": 1948,
"s": 1939,
"text": "Output :"
},
{
"code": null,
"e": 1982,
"s": 1948,
"text": "New stream is : 6 8 10 12 14 16 \n"
},
{
"code": null,
"e": 1996,
"s": 1982,
"text": "Application :"
},
{
"code": "// Java code for skip() functionimport java.util.stream.Stream;import java.util.ArrayList;import java.util.List; class gfg{ // Function to skip the elements of stream upto given range, i.e, 3 public static Stream<String> skip_func(Stream<String> ss, int range){ return ss.skip(range); } // Driver code public static void main(String[] args){ // list to save stream of strings List<String> arr = new ArrayList<>(); arr.add(\"geeks\"); arr.add(\"for\"); arr.add(\"geeks\"); arr.add(\"computer\"); arr.add(\"science\"); Stream<String> str = arr.stream(); // calling function to skip the elements to range 3 Stream<String> sk = skip_func(str,3); sk.forEach(System.out::println); } }",
"e": 2842,
"s": 1996,
"text": null
},
{
"code": null,
"e": 2851,
"s": 2842,
"text": "Output :"
},
{
"code": null,
"e": 2869,
"s": 2851,
"text": "computer\nscience\n"
},
{
"code": null,
"e": 2909,
"s": 2869,
"text": "Difference between limit() and skip() :"
},
{
"code": null,
"e": 3367,
"s": 2909,
"text": "The limit() method returns a reduced stream of first N elements but skip() method returns a stream of remaining elements after skipping first N elements.limit() is a short-circuiting stateful intermediate operation i.e, when processed with an infinite input, it may produce a finite stream as a result without processing the entire input but skip() is a stateful intermediate operation i.e, it may need to process the entire input before producing a result."
},
{
"code": null,
"e": 3521,
"s": 3367,
"text": "The limit() method returns a reduced stream of first N elements but skip() method returns a stream of remaining elements after skipping first N elements."
},
{
"code": null,
"e": 3826,
"s": 3521,
"text": "limit() is a short-circuiting stateful intermediate operation i.e, when processed with an infinite input, it may produce a finite stream as a result without processing the entire input but skip() is a stateful intermediate operation i.e, it may need to process the entire input before producing a result."
},
{
"code": null,
"e": 3846,
"s": 3826,
"text": "Java - util package"
},
{
"code": null,
"e": 3861,
"s": 3846,
"text": "Java-Functions"
},
{
"code": null,
"e": 3873,
"s": 3861,
"text": "java-stream"
},
{
"code": null,
"e": 3895,
"s": 3873,
"text": "Java-Stream interface"
},
{
"code": null,
"e": 3900,
"s": 3895,
"text": "Java"
},
{
"code": null,
"e": 3905,
"s": 3900,
"text": "Java"
}
] |
Object Level Lock vs Class Level Lock in Java
|
19 Apr, 2022
Synchronized is the modifier applicable only for methods and blocks but not for classes and variables. If multiple threads are trying to operate simultaneously on the same java object then there may be a chance of data inconsistency problem to overcome this problem we should go for a ‘synchronized‘ keyword. If a method or block declares as synchronized then at a time only one thread is allowed to execute that method or block on the given object so that the data inconsistency problem will be resolved. Internally synchronization concept is implemented by using the lock. Every object in java has a unique lock. Whenever we are using a ‘synchronized‘ keyword then only the lock concept will come into the picture.
If a thread want’s to execute a synchronized method on the given object first it has to get a lock of that object once the thread got the lock then it is allowed to execute any synchronized method on that object. Acquiring and releasing lock internally takes care of by JVM and the programmer is not responsible for this activity. While a thread executing a synchronized method on the given object the remaining threads are not allowed to execute any synchronized method simultaneously on the same object. But remaining threads are allowed to execute non-synchronized methods simultaneously.
Object Level Lock is a mechanism where every object in java has a unique lock which is nothing but an object–level lock. If a thread wants to execute a synchronized method on the given object then the thread first required the object level lock once the thread gets object level lock then it is allowed to execute any synchronized method on the given object and once the method execution completed automatically thread releases the lock of that object.
Example:
Java
// Java program to illustrate Object Level Lock Concept // Import required packagesimport java.io.*;import java.util.*; // Class 1// Helper Class 1// Consists of synchronized method wishclass Display { // Declaring Non-static wish method public void wish(String name) { // synchronizing wish method // and getting the lock of current object synchronized (this) { for (int i = 1; i <= 10; i++) { // display message only System.out.print("Good Morning: "); // Try block to check. for exceptions try { // Putting thread on sleep for specified // time // using the sleep() method Thread.sleep(1000); } // Catch block to handle the exceptions catch (InterruptedException e) { // Print the occurred exception/s System.out.println(e); } // Display message only System.out.println(name); } } }} // Class 2// Helper Class 2 (extending main Thread Class)// myThread with override the run method and// consists of parameterized constructorclass myThread extends Thread { // member variable of this class Display d; String name; // Constructor(Parameterized) of this class myThread(Display d, String name) { // this keyword refers to current object itself this.d = d; this.name = name; } // run() method for thread public void run() { // Calling wish method of display class d.wish(name); }} // Class 3// Main Classclass GFG { // Main driver method public static void main(String[] args) { // Creating display class(Class 1) object // in the main() method Display d = new Display(); // Creating thread objects in main method() myThread t1 = new myThread(d, "Dhoni"); myThread t2 = new myThread(d, "Yuvraj"); // Starting the threads using the start() method t1.start(); t2.start(); }}
Class Level Lock is a mechanism where every class in java has a unique lock which is nothing but a class level lock. If a thread wants to execute a static synchronized method then the thread requires a class level lock once the thread gets a class level lock then it is allowed to execute any static synchronized method of that class. Once method execution completes automatically thread releases the lock. While a thread executing a static synchronized method the remaining thread is not allowed to execute any static synchronized method of that class simultaneously.
Example:
Java
// java program to illustrate Class Level Lock Concept // Importing required packagesimport java.io.*;import java.util.*; // Class 1// Helper Class// Consist of synchronized method wishclass Display { // Declaring static wish method public static void wish(String name) { // synchronizing wish method // and getting the lock of display class synchronized (Display.class) { for (int i = 1; i <= 10; i++) { // Display message only System.out.print("Good Morning: "); // Try block to check for exceptions try { // Putting thread on sleep for specified // time // using the sleep() method Thread.sleep(1000); } // Catch block to handle the exception catch (InterruptedException e) { // Throwing exception System.out.println(e); } // Display message System.out.println(name); } } }} // C;asss 2// Helper Class (extends the Thread class)// myThread with override the run method// as per our requirements it also consists// of parameterized constructorclass myThread extends Thread { // Member variables of this class Display d; String name; // Constructor of this class myThread(Display d, String name) { // This keyword refers to current object itself this.d = d; this.name = name; } // run method for thread/s public void run() { // Calling wish method of display class d.wish(name); }} // Class 3// Main Classclass GFG { // Main driver method public static void main(String[] args) { // Creating Display class(Class 1) object // in the main() method Display d = new Display(); // Creating a thread objects myThread t1 = new myThread(d, "Dhoni"); myThread t2 = new myThread(d, "Yuvraj"); // Starting the threads using start() method t1.start(); t2.start(); }}
Class Level Lock
Object Level Lock
We can get a class level lock as follows:
public class GFG {
public void m1( ) {
synchronized (GFG.class) {
// some line of code
}
}
We can get object level lock as follows:
public class GFG {
public void m1( ) {
synchronized (this) {
// some line of code
}
}
}
akshaysingh98088
anikaseth98
sooda367
anikakapoor
rkbhola5
Difference Between
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n19 Apr, 2022"
},
{
"code": null,
"e": 770,
"s": 53,
"text": "Synchronized is the modifier applicable only for methods and blocks but not for classes and variables. If multiple threads are trying to operate simultaneously on the same java object then there may be a chance of data inconsistency problem to overcome this problem we should go for a ‘synchronized‘ keyword. If a method or block declares as synchronized then at a time only one thread is allowed to execute that method or block on the given object so that the data inconsistency problem will be resolved. Internally synchronization concept is implemented by using the lock. Every object in java has a unique lock. Whenever we are using a ‘synchronized‘ keyword then only the lock concept will come into the picture."
},
{
"code": null,
"e": 1362,
"s": 770,
"text": "If a thread want’s to execute a synchronized method on the given object first it has to get a lock of that object once the thread got the lock then it is allowed to execute any synchronized method on that object. Acquiring and releasing lock internally takes care of by JVM and the programmer is not responsible for this activity. While a thread executing a synchronized method on the given object the remaining threads are not allowed to execute any synchronized method simultaneously on the same object. But remaining threads are allowed to execute non-synchronized methods simultaneously."
},
{
"code": null,
"e": 1815,
"s": 1362,
"text": "Object Level Lock is a mechanism where every object in java has a unique lock which is nothing but an object–level lock. If a thread wants to execute a synchronized method on the given object then the thread first required the object level lock once the thread gets object level lock then it is allowed to execute any synchronized method on the given object and once the method execution completed automatically thread releases the lock of that object."
},
{
"code": null,
"e": 1824,
"s": 1815,
"text": "Example:"
},
{
"code": null,
"e": 1829,
"s": 1824,
"text": "Java"
},
{
"code": "// Java program to illustrate Object Level Lock Concept // Import required packagesimport java.io.*;import java.util.*; // Class 1// Helper Class 1// Consists of synchronized method wishclass Display { // Declaring Non-static wish method public void wish(String name) { // synchronizing wish method // and getting the lock of current object synchronized (this) { for (int i = 1; i <= 10; i++) { // display message only System.out.print(\"Good Morning: \"); // Try block to check. for exceptions try { // Putting thread on sleep for specified // time // using the sleep() method Thread.sleep(1000); } // Catch block to handle the exceptions catch (InterruptedException e) { // Print the occurred exception/s System.out.println(e); } // Display message only System.out.println(name); } } }} // Class 2// Helper Class 2 (extending main Thread Class)// myThread with override the run method and// consists of parameterized constructorclass myThread extends Thread { // member variable of this class Display d; String name; // Constructor(Parameterized) of this class myThread(Display d, String name) { // this keyword refers to current object itself this.d = d; this.name = name; } // run() method for thread public void run() { // Calling wish method of display class d.wish(name); }} // Class 3// Main Classclass GFG { // Main driver method public static void main(String[] args) { // Creating display class(Class 1) object // in the main() method Display d = new Display(); // Creating thread objects in main method() myThread t1 = new myThread(d, \"Dhoni\"); myThread t2 = new myThread(d, \"Yuvraj\"); // Starting the threads using the start() method t1.start(); t2.start(); }}",
"e": 3993,
"s": 1829,
"text": null
},
{
"code": null,
"e": 4562,
"s": 3993,
"text": "Class Level Lock is a mechanism where every class in java has a unique lock which is nothing but a class level lock. If a thread wants to execute a static synchronized method then the thread requires a class level lock once the thread gets a class level lock then it is allowed to execute any static synchronized method of that class. Once method execution completes automatically thread releases the lock. While a thread executing a static synchronized method the remaining thread is not allowed to execute any static synchronized method of that class simultaneously."
},
{
"code": null,
"e": 4571,
"s": 4562,
"text": "Example:"
},
{
"code": null,
"e": 4576,
"s": 4571,
"text": "Java"
},
{
"code": "// java program to illustrate Class Level Lock Concept // Importing required packagesimport java.io.*;import java.util.*; // Class 1// Helper Class// Consist of synchronized method wishclass Display { // Declaring static wish method public static void wish(String name) { // synchronizing wish method // and getting the lock of display class synchronized (Display.class) { for (int i = 1; i <= 10; i++) { // Display message only System.out.print(\"Good Morning: \"); // Try block to check for exceptions try { // Putting thread on sleep for specified // time // using the sleep() method Thread.sleep(1000); } // Catch block to handle the exception catch (InterruptedException e) { // Throwing exception System.out.println(e); } // Display message System.out.println(name); } } }} // C;asss 2// Helper Class (extends the Thread class)// myThread with override the run method// as per our requirements it also consists// of parameterized constructorclass myThread extends Thread { // Member variables of this class Display d; String name; // Constructor of this class myThread(Display d, String name) { // This keyword refers to current object itself this.d = d; this.name = name; } // run method for thread/s public void run() { // Calling wish method of display class d.wish(name); }} // Class 3// Main Classclass GFG { // Main driver method public static void main(String[] args) { // Creating Display class(Class 1) object // in the main() method Display d = new Display(); // Creating a thread objects myThread t1 = new myThread(d, \"Dhoni\"); myThread t2 = new myThread(d, \"Yuvraj\"); // Starting the threads using start() method t1.start(); t2.start(); }}",
"e": 6724,
"s": 4576,
"text": null
},
{
"code": null,
"e": 6741,
"s": 6724,
"text": "Class Level Lock"
},
{
"code": null,
"e": 6759,
"s": 6741,
"text": "Object Level Lock"
},
{
"code": null,
"e": 6801,
"s": 6759,
"text": "We can get a class level lock as follows:"
},
{
"code": null,
"e": 6820,
"s": 6801,
"text": "public class GFG {"
},
{
"code": null,
"e": 6842,
"s": 6820,
"text": " public void m1( ) {"
},
{
"code": null,
"e": 6874,
"s": 6842,
"text": " synchronized (GFG.class) {"
},
{
"code": null,
"e": 6900,
"s": 6874,
"text": " // some line of code "
},
{
"code": null,
"e": 6904,
"s": 6900,
"text": " }"
},
{
"code": null,
"e": 6906,
"s": 6904,
"text": "}"
},
{
"code": null,
"e": 6947,
"s": 6906,
"text": "We can get object level lock as follows:"
},
{
"code": null,
"e": 6966,
"s": 6947,
"text": "public class GFG {"
},
{
"code": null,
"e": 6988,
"s": 6966,
"text": " public void m1( ) {"
},
{
"code": null,
"e": 7015,
"s": 6988,
"text": " synchronized (this) {"
},
{
"code": null,
"e": 7044,
"s": 7015,
"text": " // some line of code"
},
{
"code": null,
"e": 7051,
"s": 7044,
"text": " }"
},
{
"code": null,
"e": 7055,
"s": 7051,
"text": " }"
},
{
"code": null,
"e": 7057,
"s": 7055,
"text": "}"
},
{
"code": null,
"e": 7076,
"s": 7059,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 7088,
"s": 7076,
"text": "anikaseth98"
},
{
"code": null,
"e": 7097,
"s": 7088,
"text": "sooda367"
},
{
"code": null,
"e": 7109,
"s": 7097,
"text": "anikakapoor"
},
{
"code": null,
"e": 7118,
"s": 7109,
"text": "rkbhola5"
},
{
"code": null,
"e": 7137,
"s": 7118,
"text": "Difference Between"
},
{
"code": null,
"e": 7142,
"s": 7137,
"text": "Java"
},
{
"code": null,
"e": 7147,
"s": 7142,
"text": "Java"
}
] |
Python – Variations of Principal Component Analysis
|
26 Jun, 2021
Principal Component Analysis (PCA) is an unsupervised dimensionality reduction and visualisation technique. It is often referred to as a linear technique because the mapping of new features is given by the multiplication of feature by the matrix of PCA eigenvectors. It works by simply identifying the hyperplane that lies close to the data and then projects the data onto it in order to maximize the variance. Due to the simplistic approach PCA follows, it is widely used in data mining, bioinformatics, psychology, etc. Most of us are unaware of the fact that there are various versions of this algorithm out there which are better than the conventional approach. Let’s look at them one by one.
Randomized PCA: This is an extension to PCA which uses approximated Singular Value Decomposition(SVD) of data. Conventional PCA works in O(n*p2) + O(p3) where n is the number of data points and p is the number of features whereas randomized version works in O(n*d*2) + O(d3) where d is the number of principal components. Thus, it is blazing fast when d is much smaller than n. sklearn provides a method randomized_svd in sklearn.utils.extmath which can be used to do randomized PCA. This method returns three matrices: U which is an m x m matrix, Sigma is an m x n diagonal matrix, and V^T is the transpose of an n x n matrix where T is a superscript. Another way to use sklearn.decomposition.PCA and change the svd_solver hyperparameter from ‘auto’ to ‘randomized’ or ‘full’. However, Scikit-learn automatically uses randomized PCA if either p or n exceeds 500 or the number of principal components is less than 80% of p and n.
Code:
Python3
# Python3 program to show the working of# randomized PCA # importing librariesimport numpy as npfrom sklearn.decomposition import PCAfrom sklearn.utils.extmath import randomized_svd # dummy dataX = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]]) # creates instance of PCA with randomized svd_solverpca = PCA(n_components = 2, svd_solver ='randomized') # This function takes a matrix and returns the# U, Sigma and V ^ T elementsU, S, VT = randomized_svd(X, n_components = 2) # matrix returned by randomized_svdprint(f"Matrix U of size m * m: {U}\n")print(f"Matrix S of size m * n: {S}\n")print(f"Matrix V ^ T of size n * n: {VT}\n") # fitting the pca modelpca.fit(X) # printing the explained variance ratioprint("Explained Variance using PCA with randomized svd_solver:", pca.explained_variance_ratio_)
Output:
Matrix U of size m*m: [[ 0.21956688 -0.53396977]
[ 0.35264795 0.45713538]
[ 0.57221483 -0.07683439]
[-0.21956688 0.53396977]
[-0.35264795 -0.45713538]
[-0.57221483 0.07683439]]
Matrix S of size m*n: [6.30061232 0.54980396]
Matrix V^T of size n*n: [[-0.83849224 -0.54491354]
[-0.54491354 0.83849224]]
Explained Variance using PCA with randomized svd_solver: [0.99244289 0.00755711]
Incremental PCA: The major problem with PCA and most of the dimensionality reduction algorithms is that they require whole data to fit in the memory at a single time and as the data is very huge at times thus it becomes very difficult to fit in memory. Fortunately, there is an algorithm called Incremental PCA which is useful for large training datasets as it splits the data into min-batches and feeds it to Incremental PCA one batch at a time. This is called as on-the-fly learning. As not much data is present in the memory at a time thus memory usage is controlled. Scikit-Learn provides us with a class called as sklearn.decomposition.IncrementalPCA using which we can implement this.
Code:
Python3
# Python3 program to show the working of# incremental PCA # importing librariesimport numpy as npfrom sklearn.decomposition import IncrementalPCA # dummy dataX = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]]) # specify the number of batchesno_of_batches = 3 # create an instance of IncrementalPCAincremental_pca = IncrementalPCA(n_components = 2) # fit the data in batchesfor batch in np.array_split(X, no_of_batches): incremental_pca.fit(batch) # fit and transform the datafinal = incremental_pca.transform(X) # prints an 2d-array (as n_components = 2)print(final)
Output:
[[-4.24264069e+00 7.07106781e-01]
[-4.94974747e+00 1.41421356e+00]
[-6.36396103e+00 1.41421356e+00]
[-1.41421356e+00 7.07106781e-01]
[-7.07106781e-01 -5.55111512e-17]
[ 7.07106781e-01 5.55111512e-17]]
Kernal PCA: Kernel PCA is yet another extension of PCA using a kernel. The kernel is a mathematical technique using which we can map instances to very high dimensional space called the feature space, enabling non-linear classification and regression with Support Vector Machines(SVM). This is usually employed in novelty detections and image de-noising. Scikit-Learn provides a class KernelPCA in sklearn.decomposition which can be used to perform Kernel PCA.
Code:
Python3
# Python3 program to show the working of# Kernel PCA # importing librariesimport numpy as npfrom sklearn.decomposition import KernelPCA # dummy dataX = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]]) # creating an instance of KernelPCA using rbf kernelkernel_pca = KernelPCA(n_components = 2, kernel ="rbf", gamma = 0.03) # fit and transform the datafinal = kernel_pca.fit_transform(X) # prints an 2d-array (as n_components = 2)print(final)
Output:
[[-0.3149893 -0.17944928]
[-0.46965347 -0.0475298 ]
[-0.62541667 0.22697909]
[ 0.3149893 -0.17944928]
[ 0.46965347 -0.0475298 ]
[ 0.62541667 0.22697909]]
KernelPCA is unsupervised thus there is no obvious measure to select the best kernel. As we usually use dimensionality reduction as a step in supervised learning algorithms so we can use a pipeline with GridSearchCV for selecting optimal hyperparameters and then using those hyperparameters (kernel and gamma) to get the best classification accuracy.
rajeev0719singh
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Recurrent Neural Network
Support Vector Machine Algorithm
ML | Monte Carlo Tree Search (MCTS)
Markov Decision Process
DBSCAN Clustering in ML | Density based clustering
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
Python Dictionary
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Jun, 2021"
},
{
"code": null,
"e": 726,
"s": 28,
"text": "Principal Component Analysis (PCA) is an unsupervised dimensionality reduction and visualisation technique. It is often referred to as a linear technique because the mapping of new features is given by the multiplication of feature by the matrix of PCA eigenvectors. It works by simply identifying the hyperplane that lies close to the data and then projects the data onto it in order to maximize the variance. Due to the simplistic approach PCA follows, it is widely used in data mining, bioinformatics, psychology, etc. Most of us are unaware of the fact that there are various versions of this algorithm out there which are better than the conventional approach. Let’s look at them one by one. "
},
{
"code": null,
"e": 1657,
"s": 726,
"text": "Randomized PCA: This is an extension to PCA which uses approximated Singular Value Decomposition(SVD) of data. Conventional PCA works in O(n*p2) + O(p3) where n is the number of data points and p is the number of features whereas randomized version works in O(n*d*2) + O(d3) where d is the number of principal components. Thus, it is blazing fast when d is much smaller than n. sklearn provides a method randomized_svd in sklearn.utils.extmath which can be used to do randomized PCA. This method returns three matrices: U which is an m x m matrix, Sigma is an m x n diagonal matrix, and V^T is the transpose of an n x n matrix where T is a superscript. Another way to use sklearn.decomposition.PCA and change the svd_solver hyperparameter from ‘auto’ to ‘randomized’ or ‘full’. However, Scikit-learn automatically uses randomized PCA if either p or n exceeds 500 or the number of principal components is less than 80% of p and n. "
},
{
"code": null,
"e": 1665,
"s": 1657,
"text": "Code: "
},
{
"code": null,
"e": 1673,
"s": 1665,
"text": "Python3"
},
{
"code": "# Python3 program to show the working of# randomized PCA # importing librariesimport numpy as npfrom sklearn.decomposition import PCAfrom sklearn.utils.extmath import randomized_svd # dummy dataX = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]]) # creates instance of PCA with randomized svd_solverpca = PCA(n_components = 2, svd_solver ='randomized') # This function takes a matrix and returns the# U, Sigma and V ^ T elementsU, S, VT = randomized_svd(X, n_components = 2) # matrix returned by randomized_svdprint(f\"Matrix U of size m * m: {U}\\n\")print(f\"Matrix S of size m * n: {S}\\n\")print(f\"Matrix V ^ T of size n * n: {VT}\\n\") # fitting the pca modelpca.fit(X) # printing the explained variance ratioprint(\"Explained Variance using PCA with randomized svd_solver:\", pca.explained_variance_ratio_)",
"e": 2492,
"s": 1673,
"text": null
},
{
"code": null,
"e": 2501,
"s": 2492,
"text": "Output: "
},
{
"code": null,
"e": 2895,
"s": 2501,
"text": "Matrix U of size m*m: [[ 0.21956688 -0.53396977]\n [ 0.35264795 0.45713538]\n [ 0.57221483 -0.07683439]\n [-0.21956688 0.53396977]\n [-0.35264795 -0.45713538]\n [-0.57221483 0.07683439]]\n\nMatrix S of size m*n: [6.30061232 0.54980396]\n\nMatrix V^T of size n*n: [[-0.83849224 -0.54491354]\n [-0.54491354 0.83849224]]\n\nExplained Variance using PCA with randomized svd_solver: [0.99244289 0.00755711]"
},
{
"code": null,
"e": 3586,
"s": 2895,
"text": "Incremental PCA: The major problem with PCA and most of the dimensionality reduction algorithms is that they require whole data to fit in the memory at a single time and as the data is very huge at times thus it becomes very difficult to fit in memory. Fortunately, there is an algorithm called Incremental PCA which is useful for large training datasets as it splits the data into min-batches and feeds it to Incremental PCA one batch at a time. This is called as on-the-fly learning. As not much data is present in the memory at a time thus memory usage is controlled. Scikit-Learn provides us with a class called as sklearn.decomposition.IncrementalPCA using which we can implement this."
},
{
"code": null,
"e": 3593,
"s": 3586,
"text": "Code: "
},
{
"code": null,
"e": 3601,
"s": 3593,
"text": "Python3"
},
{
"code": "# Python3 program to show the working of# incremental PCA # importing librariesimport numpy as npfrom sklearn.decomposition import IncrementalPCA # dummy dataX = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]]) # specify the number of batchesno_of_batches = 3 # create an instance of IncrementalPCAincremental_pca = IncrementalPCA(n_components = 2) # fit the data in batchesfor batch in np.array_split(X, no_of_batches): incremental_pca.fit(batch) # fit and transform the datafinal = incremental_pca.transform(X) # prints an 2d-array (as n_components = 2)print(final)",
"e": 4186,
"s": 3601,
"text": null
},
{
"code": null,
"e": 4195,
"s": 4186,
"text": "Output: "
},
{
"code": null,
"e": 4406,
"s": 4195,
"text": "[[-4.24264069e+00 7.07106781e-01]\n [-4.94974747e+00 1.41421356e+00]\n [-6.36396103e+00 1.41421356e+00]\n [-1.41421356e+00 7.07106781e-01]\n [-7.07106781e-01 -5.55111512e-17]\n [ 7.07106781e-01 5.55111512e-17]]"
},
{
"code": null,
"e": 4866,
"s": 4406,
"text": "Kernal PCA: Kernel PCA is yet another extension of PCA using a kernel. The kernel is a mathematical technique using which we can map instances to very high dimensional space called the feature space, enabling non-linear classification and regression with Support Vector Machines(SVM). This is usually employed in novelty detections and image de-noising. Scikit-Learn provides a class KernelPCA in sklearn.decomposition which can be used to perform Kernel PCA."
},
{
"code": null,
"e": 4874,
"s": 4866,
"text": "Code: "
},
{
"code": null,
"e": 4882,
"s": 4874,
"text": "Python3"
},
{
"code": "# Python3 program to show the working of# Kernel PCA # importing librariesimport numpy as npfrom sklearn.decomposition import KernelPCA # dummy dataX = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]]) # creating an instance of KernelPCA using rbf kernelkernel_pca = KernelPCA(n_components = 2, kernel =\"rbf\", gamma = 0.03) # fit and transform the datafinal = kernel_pca.fit_transform(X) # prints an 2d-array (as n_components = 2)print(final)",
"e": 5340,
"s": 4882,
"text": null
},
{
"code": null,
"e": 5349,
"s": 5340,
"text": "Output: "
},
{
"code": null,
"e": 5512,
"s": 5349,
"text": "[[-0.3149893 -0.17944928]\n [-0.46965347 -0.0475298 ]\n [-0.62541667 0.22697909]\n [ 0.3149893 -0.17944928]\n [ 0.46965347 -0.0475298 ]\n [ 0.62541667 0.22697909]]"
},
{
"code": null,
"e": 5864,
"s": 5512,
"text": "KernelPCA is unsupervised thus there is no obvious measure to select the best kernel. As we usually use dimensionality reduction as a step in supervised learning algorithms so we can use a pipeline with GridSearchCV for selecting optimal hyperparameters and then using those hyperparameters (kernel and gamma) to get the best classification accuracy. "
},
{
"code": null,
"e": 5880,
"s": 5864,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 5897,
"s": 5880,
"text": "Machine Learning"
},
{
"code": null,
"e": 5904,
"s": 5897,
"text": "Python"
},
{
"code": null,
"e": 5921,
"s": 5904,
"text": "Machine Learning"
},
{
"code": null,
"e": 6019,
"s": 5921,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6060,
"s": 6019,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 6093,
"s": 6060,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 6129,
"s": 6093,
"text": "ML | Monte Carlo Tree Search (MCTS)"
},
{
"code": null,
"e": 6153,
"s": 6129,
"text": "Markov Decision Process"
},
{
"code": null,
"e": 6204,
"s": 6153,
"text": "DBSCAN Clustering in ML | Density based clustering"
},
{
"code": null,
"e": 6232,
"s": 6204,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 6282,
"s": 6232,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 6304,
"s": 6282,
"text": "Python map() function"
},
{
"code": null,
"e": 6322,
"s": 6304,
"text": "Python Dictionary"
}
] |
How to Install R Studio on Windows and Linux?
|
13 Oct, 2021
R programming language is a language and free software environment, available under GNU license, supported by R Foundation for Statistical Computing. The language is most widely known for its powerful statistical and data interpretation capabilities.
To use R language, you need the R environment to be installed on your machine, and an IDE (Integrated development environment) to run the language (can also be run using CMD on Windows or Terminal on Linux).
It is a powerful IDE, specifically used for the R language.
Provides literate programming tools, which basically allow the use of R scripts, outputs, text, and images into reports, Word documents, and even an HTML file.
The use of Shiny (open-source R package) allows us to create interactive content in reports and presentations.
To Install R Studio on windows we will follow the following steps.
Step 1: First, you need to set up an R environment in your local machine. You can download the same from r-project.org.
Step 2: After downloading R for the Windows platform, install it by double-clicking it.
Step 3: Download R Studio from their official page. Note: It is free of cost (under AGPL licensing).
Step 4: After downloading, you will get a file named “RStudio-1.x.xxxx.exe” in your Downloads folder.
Step 5: Double-click the installer, and install the software.
Step 6: Test the R Studio installation
Search for RStudio in the Window search bar on Taskbar.
Start the application.
Insert the following code in the console.
Input : print('Hello world!')
Output : [1] "Hello world!"
Step 7: Your installation is successful.
Installing R Studio on Ubuntu has steps similar to Windows:
Step 1: Open terminal (Ctrl+Alt+T) in Ubuntu.
Step 2: Update the package’s cache.
sudo apt-get update
Step 3: Install R environment.
sudo apt -y install r-base
Check for the version of R package using
R --version
Step 4: Check R installation by using the following command.
user@Ubuntu:~$ R
(Note that R version should be 3.6+ to be able to install all packages like tm, e1071, etc.). If there is issue with R version, see the end of the post.
Step 5: Exit the terminal.
Step 1: Open Ubuntu Software Center.
Step 2: Search for r-base.
Step 3: Click install.
Step 1: Install gdebi package to install .deb packages easily.
sudo add-apt-repository universe
sudo apt-get install gdebi-core
Step 2: Go to R Studio downloads and select the latest *.deb package available under Ubuntu 18/Debian 10.
Step 3: Navigate to the Downloads folder in the local machine.
$ cd Downloads/
$ ls
rstudio-1.2.5042-amd64.deb
Step 4: Install using gdebi package.
sudo gdebi rstudio-1.2.5042-amd64.deb
Step 5: Run the RStudio using Terminal
user@Ubuntu:~/Downloads/ $ rstudio
Alternatively, use the menu to search for Rstudio.
Step 6: Test the R Studio using the basic “Hello world!” command and exit.
Input : print('Hello world!')
Output : [1] "Hello world!"
Alternatively, RStudio can be installed through Ubuntu Software as well, but using the above approach generally guarantees the latest version is installed.
If there are issues with the R version getting downloaded or the previously installed version is older, check R version with
R --version
Now, Run the following commands in Terminal (Ctrl + Alt + T)
Add the key to secure APT from the CRAN package list:
sudo apt-key adv –keyserver keyserver.ubuntu.com –recv-keys E298A3A825C0D65DFD57CBB651716619E084DAB9
Add the latest CRAN repository to the repository list. (This is for Ubuntu 18.04 specifically):
sudo add-apt-repository ‘deb https://cloud.r-project.org/bin/linux/ubuntu bionic-cran35/’
Update the package cache:
sudo apt update
Install the r-base package:
sudo apt install r-base
rajeev0719singh
kumar_satyam
how-to-install
Picked
How To
Installation Guide
R Language
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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 Align Text in HTML?
How to Install PIP on Windows ?
Installation of Node.js on Linux
How to install Jupyter Notebook on Windows?
How to Install OpenCV for Python on Windows?
How to Install FFmpeg on Windows?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Oct, 2021"
},
{
"code": null,
"e": 280,
"s": 28,
"text": "R programming language is a language and free software environment, available under GNU license, supported by R Foundation for Statistical Computing. The language is most widely known for its powerful statistical and data interpretation capabilities. "
},
{
"code": null,
"e": 489,
"s": 280,
"text": "To use R language, you need the R environment to be installed on your machine, and an IDE (Integrated development environment) to run the language (can also be run using CMD on Windows or Terminal on Linux). "
},
{
"code": null,
"e": 549,
"s": 489,
"text": "It is a powerful IDE, specifically used for the R language."
},
{
"code": null,
"e": 709,
"s": 549,
"text": "Provides literate programming tools, which basically allow the use of R scripts, outputs, text, and images into reports, Word documents, and even an HTML file."
},
{
"code": null,
"e": 820,
"s": 709,
"text": "The use of Shiny (open-source R package) allows us to create interactive content in reports and presentations."
},
{
"code": null,
"e": 887,
"s": 820,
"text": "To Install R Studio on windows we will follow the following steps."
},
{
"code": null,
"e": 1008,
"s": 887,
"text": "Step 1: First, you need to set up an R environment in your local machine. You can download the same from r-project.org. "
},
{
"code": null,
"e": 1098,
"s": 1008,
"text": "Step 2: After downloading R for the Windows platform, install it by double-clicking it. "
},
{
"code": null,
"e": 1201,
"s": 1098,
"text": "Step 3: Download R Studio from their official page. Note: It is free of cost (under AGPL licensing). "
},
{
"code": null,
"e": 1304,
"s": 1201,
"text": "Step 4: After downloading, you will get a file named “RStudio-1.x.xxxx.exe” in your Downloads folder. "
},
{
"code": null,
"e": 1367,
"s": 1304,
"text": "Step 5: Double-click the installer, and install the software. "
},
{
"code": null,
"e": 1408,
"s": 1367,
"text": "Step 6: Test the R Studio installation "
},
{
"code": null,
"e": 1464,
"s": 1408,
"text": "Search for RStudio in the Window search bar on Taskbar."
},
{
"code": null,
"e": 1487,
"s": 1464,
"text": "Start the application."
},
{
"code": null,
"e": 1529,
"s": 1487,
"text": "Insert the following code in the console."
},
{
"code": null,
"e": 1589,
"s": 1529,
"text": "Input : print('Hello world!') \nOutput : [1] \"Hello world!\""
},
{
"code": null,
"e": 1632,
"s": 1589,
"text": "Step 7: Your installation is successful. "
},
{
"code": null,
"e": 1693,
"s": 1632,
"text": "Installing R Studio on Ubuntu has steps similar to Windows: "
},
{
"code": null,
"e": 1739,
"s": 1693,
"text": "Step 1: Open terminal (Ctrl+Alt+T) in Ubuntu."
},
{
"code": null,
"e": 1776,
"s": 1739,
"text": "Step 2: Update the package’s cache. "
},
{
"code": null,
"e": 1796,
"s": 1776,
"text": "sudo apt-get update"
},
{
"code": null,
"e": 1828,
"s": 1796,
"text": "Step 3: Install R environment. "
},
{
"code": null,
"e": 1855,
"s": 1828,
"text": "sudo apt -y install r-base"
},
{
"code": null,
"e": 1896,
"s": 1855,
"text": "Check for the version of R package using"
},
{
"code": null,
"e": 1908,
"s": 1896,
"text": "R --version"
},
{
"code": null,
"e": 1970,
"s": 1908,
"text": "Step 4: Check R installation by using the following command. "
},
{
"code": null,
"e": 1988,
"s": 1970,
"text": "user@Ubuntu:~$ R "
},
{
"code": null,
"e": 2142,
"s": 1988,
"text": "(Note that R version should be 3.6+ to be able to install all packages like tm, e1071, etc.). If there is issue with R version, see the end of the post. "
},
{
"code": null,
"e": 2169,
"s": 2142,
"text": "Step 5: Exit the terminal."
},
{
"code": null,
"e": 2206,
"s": 2169,
"text": "Step 1: Open Ubuntu Software Center."
},
{
"code": null,
"e": 2233,
"s": 2206,
"text": "Step 2: Search for r-base."
},
{
"code": null,
"e": 2257,
"s": 2233,
"text": "Step 3: Click install. "
},
{
"code": null,
"e": 2320,
"s": 2257,
"text": "Step 1: Install gdebi package to install .deb packages easily."
},
{
"code": null,
"e": 2385,
"s": 2320,
"text": "sudo add-apt-repository universe\nsudo apt-get install gdebi-core"
},
{
"code": null,
"e": 2491,
"s": 2385,
"text": "Step 2: Go to R Studio downloads and select the latest *.deb package available under Ubuntu 18/Debian 10."
},
{
"code": null,
"e": 2554,
"s": 2491,
"text": "Step 3: Navigate to the Downloads folder in the local machine."
},
{
"code": null,
"e": 2603,
"s": 2554,
"text": "$ cd Downloads/\n$ ls\n rstudio-1.2.5042-amd64.deb"
},
{
"code": null,
"e": 2640,
"s": 2603,
"text": "Step 4: Install using gdebi package."
},
{
"code": null,
"e": 2678,
"s": 2640,
"text": "sudo gdebi rstudio-1.2.5042-amd64.deb"
},
{
"code": null,
"e": 2717,
"s": 2678,
"text": "Step 5: Run the RStudio using Terminal"
},
{
"code": null,
"e": 2753,
"s": 2717,
"text": "user@Ubuntu:~/Downloads/ $ rstudio "
},
{
"code": null,
"e": 2804,
"s": 2753,
"text": "Alternatively, use the menu to search for Rstudio."
},
{
"code": null,
"e": 2879,
"s": 2804,
"text": "Step 6: Test the R Studio using the basic “Hello world!” command and exit."
},
{
"code": null,
"e": 2939,
"s": 2879,
"text": "Input : print('Hello world!') \nOutput : [1] \"Hello world!\""
},
{
"code": null,
"e": 3096,
"s": 2939,
"text": "Alternatively, RStudio can be installed through Ubuntu Software as well, but using the above approach generally guarantees the latest version is installed. "
},
{
"code": null,
"e": 3222,
"s": 3096,
"text": "If there are issues with the R version getting downloaded or the previously installed version is older, check R version with "
},
{
"code": null,
"e": 3234,
"s": 3222,
"text": "R --version"
},
{
"code": null,
"e": 3297,
"s": 3234,
"text": "Now, Run the following commands in Terminal (Ctrl + Alt + T) "
},
{
"code": null,
"e": 3351,
"s": 3297,
"text": "Add the key to secure APT from the CRAN package list:"
},
{
"code": null,
"e": 3452,
"s": 3351,
"text": "sudo apt-key adv –keyserver keyserver.ubuntu.com –recv-keys E298A3A825C0D65DFD57CBB651716619E084DAB9"
},
{
"code": null,
"e": 3548,
"s": 3452,
"text": "Add the latest CRAN repository to the repository list. (This is for Ubuntu 18.04 specifically):"
},
{
"code": null,
"e": 3638,
"s": 3548,
"text": "sudo add-apt-repository ‘deb https://cloud.r-project.org/bin/linux/ubuntu bionic-cran35/’"
},
{
"code": null,
"e": 3664,
"s": 3638,
"text": "Update the package cache:"
},
{
"code": null,
"e": 3680,
"s": 3664,
"text": "sudo apt update"
},
{
"code": null,
"e": 3708,
"s": 3680,
"text": "Install the r-base package:"
},
{
"code": null,
"e": 3732,
"s": 3708,
"text": "sudo apt install r-base"
},
{
"code": null,
"e": 3748,
"s": 3732,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 3761,
"s": 3748,
"text": "kumar_satyam"
},
{
"code": null,
"e": 3776,
"s": 3761,
"text": "how-to-install"
},
{
"code": null,
"e": 3783,
"s": 3776,
"text": "Picked"
},
{
"code": null,
"e": 3790,
"s": 3783,
"text": "How To"
},
{
"code": null,
"e": 3809,
"s": 3790,
"text": "Installation Guide"
},
{
"code": null,
"e": 3820,
"s": 3809,
"text": "R Language"
},
{
"code": null,
"e": 3836,
"s": 3820,
"text": "Write From Home"
},
{
"code": null,
"e": 3934,
"s": 3836,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3966,
"s": 3934,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 4019,
"s": 3966,
"text": "How to Find the Wi-Fi Password Using CMD in Windows?"
},
{
"code": null,
"e": 4063,
"s": 4019,
"text": "How to install Jupyter Notebook on Windows?"
},
{
"code": null,
"e": 4077,
"s": 4063,
"text": "Java Tutorial"
},
{
"code": null,
"e": 4104,
"s": 4077,
"text": "How to Align Text in HTML?"
},
{
"code": null,
"e": 4136,
"s": 4104,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 4169,
"s": 4136,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 4213,
"s": 4169,
"text": "How to install Jupyter Notebook on Windows?"
},
{
"code": null,
"e": 4258,
"s": 4213,
"text": "How to Install OpenCV for Python on Windows?"
}
] |
Extended Access-List
|
15 Mar, 2022
Prerequisite – Access-lists (ACL), Standard Access-list Access-list (ACL) is a set of rules defined for controlling network traffic and reducing network attacks. ACLs are used to filter traffic based on the set of rules defined for the incoming or outgoing of the network.
Extended Access-list – It is one of the types of Access-list which is mostly used as it can distinguish IP traffic therefore the whole traffic will not be permitted or denied like in standard access-list. These are the ACL that uses both source and destination IP addresses and also the port numbers to distinguish IP traffic. In this type of ACL, we can also mention which IP traffic should be allowed or denied. These use range 100-199 and 2000-2699.
Features –
Extended access-list is generally applied close to the source but not always.In the Extended access list, packet filtering takes place on the basis of source IP address, destination IP address, port numbers.In an extended access list, particular services will be permitted or denied.Extended ACL is created from 100 – 199 & extended range 2000 – 2699.If numbered with extended Access-list is used then remember rules can’t be deleted. If one of the rules is deleted then the whole access list will be deleted.If named with extended Access-list is used then we have the flexibility to delete a rule from the access list.
Extended access-list is generally applied close to the source but not always.
In the Extended access list, packet filtering takes place on the basis of source IP address, destination IP address, port numbers.
In an extended access list, particular services will be permitted or denied.
Extended ACL is created from 100 – 199 & extended range 2000 – 2699.
If numbered with extended Access-list is used then remember rules can’t be deleted. If one of the rules is deleted then the whole access list will be deleted.
If named with extended Access-list is used then we have the flexibility to delete a rule from the access list.
Configuration –
Here is a small topology in which there are 3 departments namely sales, finance, and marketing. The sales department has a network of 172.16.10.40/24, the Finance department has a network of 172.16.50.0/24, and the marketing department has a network of 172.16.60.0/24. Now, we want to deny the FTP connection from the sales department to the finance department and deny telnet to the Finance department from both the sales and marketing departments.
Now, first configuring numbered extended access – list for denying FTP connection from sales to finance department.
R1# config terminal
R1(config)# access-list 110
deny tcp 172.16.40.0 0.0.0.255 172.16.50.0 0.0.0.255 eq 21
Here, we first create a numbered Access-list in which we use 110 (used from extended access-list range) and deny the sales network (172.16.40.0) to make an FTP connection to the finance network (172.16.50.0).
Note – Here, as FTP uses TCP and port number 21. Therefore, we have to specify the permit or deny the condition according to the need. Also, after eq, we have to use the port number for the specified application layer protocol.
Now, we have to deny telnet connection to finance department from both sales and Marketing department which means no one should telnet to finance department. Configuring for the same.
R1(config)# access-list 110
deny tcp any 172.16.50.0 0.0.0.255 eq 23
Here, we have used the keyword any which means 0.0.0.0 0.0.0.0 i.e any IP address from any subnet mask. As telnet uses port number 23 therefore, we have to specify the port number 23 after eq.
R1(config)# access-list 110 permit ip any any
Now, this is the most important part. As we already know there is an implicit deny at the end of every access list which means that if the traffic doesn’t match any of the rules of Access-list then the traffic will be dropped.
By specifying any means that source having any IP address traffic will reach finance department except the traffic which it matches the above rules that we have made. Now, we have to apply the access-list on the interface of the router:
R1(config)# int fa0/1
R1(config-if)# ip access-group 110 out
As we remember, we have to apply the extended access-list as close as possible to source but here we have applied it to close to the destination because we have to block the traffic from both sales and marketing department, therefore, we have to apply it close to the destination here otherwise we have to make separate access-list for fa0/0 and fa1/0 inbound.
Named access-list example –
Now, considering the same topology, we will make a named extended access list.
R1(config)# ip access-list extended blockacl
By using this command we have made an access-list named blockacl.
R1(config-ext-nacl)# deny tcp 172.16.40.0 0.0.0.255 172.16.50.0 0.0.0.255 eq 21
R1(config-ext-nacl)# deny tcp any 172.16.50.0 0.0.0.255 eq 23
R1(config-ext-nacl)# permit ip any any
And then the same configuration we have done in numbered access-list.
R1(config)# int fa0/1
R1(config-if)# ip access-group blockacl out
vaibhavsinghtanwar3
marcosarcticseal
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Differences between IPv4 and IPv6
GSM in Wireless Communication
Wireless Application Protocol
Secure Socket Layer (SSL)
Mobile Internet Protocol (or Mobile IP)
UDP Server-Client implementation in C
User Datagram Protocol (UDP)
Advanced Encryption Standard (AES)
Introduction of Mobile Ad hoc Network (MANET)
Cryptography and its Types
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n15 Mar, 2022"
},
{
"code": null,
"e": 326,
"s": 52,
"text": "Prerequisite – Access-lists (ACL), Standard Access-list Access-list (ACL) is a set of rules defined for controlling network traffic and reducing network attacks. ACLs are used to filter traffic based on the set of rules defined for the incoming or outgoing of the network. "
},
{
"code": null,
"e": 780,
"s": 326,
"text": "Extended Access-list – It is one of the types of Access-list which is mostly used as it can distinguish IP traffic therefore the whole traffic will not be permitted or denied like in standard access-list. These are the ACL that uses both source and destination IP addresses and also the port numbers to distinguish IP traffic. In this type of ACL, we can also mention which IP traffic should be allowed or denied. These use range 100-199 and 2000-2699. "
},
{
"code": null,
"e": 793,
"s": 780,
"text": "Features – "
},
{
"code": null,
"e": 1415,
"s": 793,
"text": "Extended access-list is generally applied close to the source but not always.In the Extended access list, packet filtering takes place on the basis of source IP address, destination IP address, port numbers.In an extended access list, particular services will be permitted or denied.Extended ACL is created from 100 – 199 & extended range 2000 – 2699.If numbered with extended Access-list is used then remember rules can’t be deleted. If one of the rules is deleted then the whole access list will be deleted.If named with extended Access-list is used then we have the flexibility to delete a rule from the access list. "
},
{
"code": null,
"e": 1493,
"s": 1415,
"text": "Extended access-list is generally applied close to the source but not always."
},
{
"code": null,
"e": 1624,
"s": 1493,
"text": "In the Extended access list, packet filtering takes place on the basis of source IP address, destination IP address, port numbers."
},
{
"code": null,
"e": 1701,
"s": 1624,
"text": "In an extended access list, particular services will be permitted or denied."
},
{
"code": null,
"e": 1770,
"s": 1701,
"text": "Extended ACL is created from 100 – 199 & extended range 2000 – 2699."
},
{
"code": null,
"e": 1929,
"s": 1770,
"text": "If numbered with extended Access-list is used then remember rules can’t be deleted. If one of the rules is deleted then the whole access list will be deleted."
},
{
"code": null,
"e": 2042,
"s": 1929,
"text": "If named with extended Access-list is used then we have the flexibility to delete a rule from the access list. "
},
{
"code": null,
"e": 2059,
"s": 2042,
"text": "Configuration – "
},
{
"code": null,
"e": 2512,
"s": 2061,
"text": "Here is a small topology in which there are 3 departments namely sales, finance, and marketing. The sales department has a network of 172.16.10.40/24, the Finance department has a network of 172.16.50.0/24, and the marketing department has a network of 172.16.60.0/24. Now, we want to deny the FTP connection from the sales department to the finance department and deny telnet to the Finance department from both the sales and marketing departments. "
},
{
"code": null,
"e": 2630,
"s": 2512,
"text": "Now, first configuring numbered extended access – list for denying FTP connection from sales to finance department. "
},
{
"code": null,
"e": 2751,
"s": 2630,
"text": "R1# config terminal\nR1(config)# access-list 110 \n deny tcp 172.16.40.0 0.0.0.255 172.16.50.0 0.0.0.255 eq 21 "
},
{
"code": null,
"e": 2961,
"s": 2751,
"text": "Here, we first create a numbered Access-list in which we use 110 (used from extended access-list range) and deny the sales network (172.16.40.0) to make an FTP connection to the finance network (172.16.50.0). "
},
{
"code": null,
"e": 3190,
"s": 2961,
"text": "Note – Here, as FTP uses TCP and port number 21. Therefore, we have to specify the permit or deny the condition according to the need. Also, after eq, we have to use the port number for the specified application layer protocol. "
},
{
"code": null,
"e": 3376,
"s": 3190,
"text": "Now, we have to deny telnet connection to finance department from both sales and Marketing department which means no one should telnet to finance department. Configuring for the same. "
},
{
"code": null,
"e": 3458,
"s": 3376,
"text": "R1(config)# access-list 110 \n deny tcp any 172.16.50.0 0.0.0.255 eq 23"
},
{
"code": null,
"e": 3653,
"s": 3458,
"text": "Here, we have used the keyword any which means 0.0.0.0 0.0.0.0 i.e any IP address from any subnet mask. As telnet uses port number 23 therefore, we have to specify the port number 23 after eq. "
},
{
"code": null,
"e": 3699,
"s": 3653,
"text": "R1(config)# access-list 110 permit ip any any"
},
{
"code": null,
"e": 3927,
"s": 3699,
"text": "Now, this is the most important part. As we already know there is an implicit deny at the end of every access list which means that if the traffic doesn’t match any of the rules of Access-list then the traffic will be dropped. "
},
{
"code": null,
"e": 4166,
"s": 3927,
"text": "By specifying any means that source having any IP address traffic will reach finance department except the traffic which it matches the above rules that we have made. Now, we have to apply the access-list on the interface of the router: "
},
{
"code": null,
"e": 4227,
"s": 4166,
"text": "R1(config)# int fa0/1\nR1(config-if)# ip access-group 110 out"
},
{
"code": null,
"e": 4589,
"s": 4227,
"text": "As we remember, we have to apply the extended access-list as close as possible to source but here we have applied it to close to the destination because we have to block the traffic from both sales and marketing department, therefore, we have to apply it close to the destination here otherwise we have to make separate access-list for fa0/0 and fa1/0 inbound. "
},
{
"code": null,
"e": 4618,
"s": 4589,
"text": "Named access-list example – "
},
{
"code": null,
"e": 4701,
"s": 4620,
"text": "Now, considering the same topology, we will make a named extended access list. "
},
{
"code": null,
"e": 4746,
"s": 4701,
"text": "R1(config)# ip access-list extended blockacl"
},
{
"code": null,
"e": 4814,
"s": 4746,
"text": "By using this command we have made an access-list named blockacl. "
},
{
"code": null,
"e": 4996,
"s": 4814,
"text": "R1(config-ext-nacl)# deny tcp 172.16.40.0 0.0.0.255 172.16.50.0 0.0.0.255 eq 21 \nR1(config-ext-nacl)# deny tcp any 172.16.50.0 0.0.0.255 eq 23\nR1(config-ext-nacl)# permit ip any any"
},
{
"code": null,
"e": 5068,
"s": 4996,
"text": "And then the same configuration we have done in numbered access-list. "
},
{
"code": null,
"e": 5134,
"s": 5068,
"text": "R1(config)# int fa0/1\nR1(config-if)# ip access-group blockacl out"
},
{
"code": null,
"e": 5156,
"s": 5136,
"text": "vaibhavsinghtanwar3"
},
{
"code": null,
"e": 5173,
"s": 5156,
"text": "marcosarcticseal"
},
{
"code": null,
"e": 5191,
"s": 5173,
"text": "Computer Networks"
},
{
"code": null,
"e": 5209,
"s": 5191,
"text": "Computer Networks"
},
{
"code": null,
"e": 5307,
"s": 5209,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5341,
"s": 5307,
"text": "Differences between IPv4 and IPv6"
},
{
"code": null,
"e": 5371,
"s": 5341,
"text": "GSM in Wireless Communication"
},
{
"code": null,
"e": 5401,
"s": 5371,
"text": "Wireless Application Protocol"
},
{
"code": null,
"e": 5427,
"s": 5401,
"text": "Secure Socket Layer (SSL)"
},
{
"code": null,
"e": 5467,
"s": 5427,
"text": "Mobile Internet Protocol (or Mobile IP)"
},
{
"code": null,
"e": 5505,
"s": 5467,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 5534,
"s": 5505,
"text": "User Datagram Protocol (UDP)"
},
{
"code": null,
"e": 5569,
"s": 5534,
"text": "Advanced Encryption Standard (AES)"
},
{
"code": null,
"e": 5615,
"s": 5569,
"text": "Introduction of Mobile Ad hoc Network (MANET)"
}
] |
TypeScript | Array indexOf() Method
|
18 Jun, 2020
The Array.indexOf() is an inbuilt TypeScript function which is used to find the index of the first occurrence of the search element provided as the argument to the function. Syntax:
array.indexOf(searchElement[, fromIndex])
Parameter: This method accepts two parameter as mentioned above and described below:
searchElement : This parameter is the Element to locate in the array.
fromIndex : This parameter is the index at which to begin the search.
Return Value: This method returns the index of the found element. Below examples illustrate the Array indexOf() method in TypeScript.
Example 1:
JavaScript
<script> // Driver code var arr = [ 11, 89, 23, 7, 98 ]; // use of indexOf() method var val = arr.indexOf(7) // printing element console.log(val);</script>
Output:
3
Example 2:
JavaScript
<script> // Driver code var arr = [ 'a','b','c','a','e' ]; // use of indexOf() method var val = arr.indexOf('a',4) // printing element console.log(val);</script>
Output:
-1
TypeScript
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
Roadmap to Learn JavaScript For Beginners
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": 28,
"s": 0,
"text": "\n18 Jun, 2020"
},
{
"code": null,
"e": 211,
"s": 28,
"text": "The Array.indexOf() is an inbuilt TypeScript function which is used to find the index of the first occurrence of the search element provided as the argument to the function. Syntax:"
},
{
"code": null,
"e": 253,
"s": 211,
"text": "array.indexOf(searchElement[, fromIndex])"
},
{
"code": null,
"e": 339,
"s": 253,
"text": "Parameter: This method accepts two parameter as mentioned above and described below: "
},
{
"code": null,
"e": 409,
"s": 339,
"text": "searchElement : This parameter is the Element to locate in the array."
},
{
"code": null,
"e": 479,
"s": 409,
"text": "fromIndex : This parameter is the index at which to begin the search."
},
{
"code": null,
"e": 613,
"s": 479,
"text": "Return Value: This method returns the index of the found element. Below examples illustrate the Array indexOf() method in TypeScript."
},
{
"code": null,
"e": 625,
"s": 613,
"text": "Example 1: "
},
{
"code": null,
"e": 636,
"s": 625,
"text": "JavaScript"
},
{
"code": "<script> // Driver code var arr = [ 11, 89, 23, 7, 98 ]; // use of indexOf() method var val = arr.indexOf(7) // printing element console.log(val);</script>",
"e": 821,
"s": 636,
"text": null
},
{
"code": null,
"e": 830,
"s": 821,
"text": "Output: "
},
{
"code": null,
"e": 833,
"s": 830,
"text": "3\n"
},
{
"code": null,
"e": 845,
"s": 833,
"text": "Example 2: "
},
{
"code": null,
"e": 856,
"s": 845,
"text": "JavaScript"
},
{
"code": "<script> // Driver code var arr = [ 'a','b','c','a','e' ]; // use of indexOf() method var val = arr.indexOf('a',4) // printing element console.log(val);</script>",
"e": 1047,
"s": 856,
"text": null
},
{
"code": null,
"e": 1056,
"s": 1047,
"text": "Output: "
},
{
"code": null,
"e": 1060,
"s": 1056,
"text": "-1\n"
},
{
"code": null,
"e": 1071,
"s": 1060,
"text": "TypeScript"
},
{
"code": null,
"e": 1082,
"s": 1071,
"text": "JavaScript"
},
{
"code": null,
"e": 1099,
"s": 1082,
"text": "Web Technologies"
},
{
"code": null,
"e": 1197,
"s": 1099,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1258,
"s": 1197,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1330,
"s": 1258,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 1370,
"s": 1330,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 1412,
"s": 1370,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 1453,
"s": 1412,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 1486,
"s": 1453,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 1548,
"s": 1486,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 1609,
"s": 1548,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1659,
"s": 1609,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
How to Get the Shape of a Tensor as a List of int in Pytorch?
|
04 Jul, 2021
To get the shape of a tensor as a list in PyTorch, we can use two approaches. One using the size() method and another by using the shape attribute of a tensor in PyTorch. In this short article, we are going to see how to use both of the approaches.
The size() method returns the size of the self tensor. The returned value is a subclass of a tuple.
Python3
import torchtorch.empty(3, 4, 5).size()
Output:
torch.Size([3, 4, 5])
We cast this into a list using the list() method.
Example:
Python3
v = torch.tensor([[1,0],[0,1]])x = list(v.size())print(x)
Output:
[2, 2]
You can also use the Python interactive session as shown below:
The tensor.shape is an alias to tensor.size(), though the shape is an attribute, and size() is a method. To verify this we can run the following in the interactive session.
We can similarly cast this into a list using the list() method.
Example:
Python3
import torchv = torch.tensor([[1,0],[0,1]])x = list(v.shape)print(x)
Output:
[2,2]
Alternatively using the interactive session:
Picked
Python-PyTorch
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 Jul, 2021"
},
{
"code": null,
"e": 277,
"s": 28,
"text": "To get the shape of a tensor as a list in PyTorch, we can use two approaches. One using the size() method and another by using the shape attribute of a tensor in PyTorch. In this short article, we are going to see how to use both of the approaches."
},
{
"code": null,
"e": 377,
"s": 277,
"text": "The size() method returns the size of the self tensor. The returned value is a subclass of a tuple."
},
{
"code": null,
"e": 385,
"s": 377,
"text": "Python3"
},
{
"code": "import torchtorch.empty(3, 4, 5).size()",
"e": 425,
"s": 385,
"text": null
},
{
"code": null,
"e": 434,
"s": 425,
"text": "Output: "
},
{
"code": null,
"e": 456,
"s": 434,
"text": "torch.Size([3, 4, 5])"
},
{
"code": null,
"e": 507,
"s": 456,
"text": "We cast this into a list using the list() method. "
},
{
"code": null,
"e": 516,
"s": 507,
"text": "Example:"
},
{
"code": null,
"e": 524,
"s": 516,
"text": "Python3"
},
{
"code": "v = torch.tensor([[1,0],[0,1]])x = list(v.size())print(x)",
"e": 582,
"s": 524,
"text": null
},
{
"code": null,
"e": 590,
"s": 582,
"text": "Output:"
},
{
"code": null,
"e": 598,
"s": 590,
"text": "[2, 2] "
},
{
"code": null,
"e": 662,
"s": 598,
"text": "You can also use the Python interactive session as shown below:"
},
{
"code": null,
"e": 835,
"s": 662,
"text": "The tensor.shape is an alias to tensor.size(), though the shape is an attribute, and size() is a method. To verify this we can run the following in the interactive session."
},
{
"code": null,
"e": 900,
"s": 835,
"text": "We can similarly cast this into a list using the list() method. "
},
{
"code": null,
"e": 909,
"s": 900,
"text": "Example:"
},
{
"code": null,
"e": 917,
"s": 909,
"text": "Python3"
},
{
"code": "import torchv = torch.tensor([[1,0],[0,1]])x = list(v.shape)print(x)",
"e": 986,
"s": 917,
"text": null
},
{
"code": null,
"e": 995,
"s": 986,
"text": " Output:"
},
{
"code": null,
"e": 1002,
"s": 995,
"text": " [2,2]"
},
{
"code": null,
"e": 1047,
"s": 1002,
"text": "Alternatively using the interactive session:"
},
{
"code": null,
"e": 1054,
"s": 1047,
"text": "Picked"
},
{
"code": null,
"e": 1069,
"s": 1054,
"text": "Python-PyTorch"
},
{
"code": null,
"e": 1076,
"s": 1069,
"text": "Python"
}
] |
Python | Scramble words from a text file
|
11 Oct, 2021
Given some data in a text file, the task is to scramble the text and output in a separate text file. So, we need to write a Python program that reads a text file, scrambles the words in the file and writes the output to a new text file.
Rules to be followed:
Words less than or equal to 3 characters need not be scrambled.
Don’t scramble first and last char, so Scrambling can become Srbmnacilg or Srbmnailcg or Snmbracilg, i.e. letters except first and last can be scrambled in any order.
Punctuation at the end of the word to be maintained as is i.e. “Surprising, ” could become “Spsirnirug, ” but not “Spsirn, irug”.
Following punctuation marks are to be supported – Comma Question mark, Full stop, Semicolon, Exclamation.
Do this for a file and maintain sequences of lines.
On executing the program, it should prompt the user to enter input file name and generate an output file with scrambled text. The output file should be named by appending the word “Scrambled” to the input file name.
Example:
Input : MyFile.txt ->
Scrambling words is very
interesting. Because even
if they are scrambled, it
doesn't impact our
reading. Because we don't
read letter by letter, we
read the word as a whole.
Output : MyFileScrambled.txt ->
Srbmnacilg words is very
itrensientg. Bscauee even
if tehy are srelabcmd, it
dosn'et ipcmat our
raidneg. Bacusee we dn'ot
raed lteetr by letetr, we
raed the word as a wolhe.
Below is the implementation :
Python3
import random punct = (".", ";", "!", "?", ",")count = 0new_word = "" inputfile = input("Enter input file name:") with open(inputfile, 'r') as fin: for line in fin.readlines(): # Read line by line in txt file for word in line.split(): # Read word by word in each line if len(word) > 3: # If word length >3 '''If word ends with punctuation Remove firstletter, lastletter and punctuation Shuffle the words Add the removed letters (first letter) Add the removed letters (last letter) Add the removed letters (punctuation mark)''' if word.endswith(punct): word1 = word[1:-2] word1 = random.sample(word1, len(word1)) word1.insert(0, word[0]) word1.append(word[-2]) word1.append(word[-1]) '''If there is no punctuation mark Remove first letter and last letter Shuffle the word Add the removed letters (first letter) Add the removed letters (last letter) Append the word and " " to the previous words''' else: word1 = word[1:-1] word1 = random.sample(word1, len(word1)) word1.insert(0, word[0]) word1.append(word[-1]) new_word = new_word + ''.join(word1) + " " '''If word length <3 just append the word and " " to the previous words''' else: new_word = new_word + word + " " # "Append to <filename>Scrambled.txt" with open((inputfile[:-4] + "Scrambled.txt"), 'a+') as fout: fout.write(new_word + "\n") new_word = ""
Output:
Smcinrablg wodrs very Bauscee eevn tehy dnoes't
icpamt Bcuesae d'not read lteter raed wrod whole.
singghakshay
Python
Python Programs
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Oct, 2021"
},
{
"code": null,
"e": 265,
"s": 28,
"text": "Given some data in a text file, the task is to scramble the text and output in a separate text file. So, we need to write a Python program that reads a text file, scrambles the words in the file and writes the output to a new text file."
},
{
"code": null,
"e": 288,
"s": 265,
"text": "Rules to be followed: "
},
{
"code": null,
"e": 352,
"s": 288,
"text": "Words less than or equal to 3 characters need not be scrambled."
},
{
"code": null,
"e": 519,
"s": 352,
"text": "Don’t scramble first and last char, so Scrambling can become Srbmnacilg or Srbmnailcg or Snmbracilg, i.e. letters except first and last can be scrambled in any order."
},
{
"code": null,
"e": 649,
"s": 519,
"text": "Punctuation at the end of the word to be maintained as is i.e. “Surprising, ” could become “Spsirnirug, ” but not “Spsirn, irug”."
},
{
"code": null,
"e": 755,
"s": 649,
"text": "Following punctuation marks are to be supported – Comma Question mark, Full stop, Semicolon, Exclamation."
},
{
"code": null,
"e": 807,
"s": 755,
"text": "Do this for a file and maintain sequences of lines."
},
{
"code": null,
"e": 1023,
"s": 807,
"text": "On executing the program, it should prompt the user to enter input file name and generate an output file with scrambled text. The output file should be named by appending the word “Scrambled” to the input file name."
},
{
"code": null,
"e": 1033,
"s": 1023,
"text": "Example: "
},
{
"code": null,
"e": 1468,
"s": 1033,
"text": "Input : MyFile.txt ->\n \nScrambling words is very \ninteresting. Because even \nif they are scrambled, it \ndoesn't impact our \nreading. Because we don't \nread letter by letter, we \nread the word as a whole. \n\nOutput : MyFileScrambled.txt ->\n \nSrbmnacilg words is very \nitrensientg. Bscauee even \nif tehy are srelabcmd, it \ndosn'et ipcmat our \nraidneg. Bacusee we dn'ot \nraed lteetr by letetr, we \nraed the word as a wolhe."
},
{
"code": null,
"e": 1500,
"s": 1468,
"text": "Below is the implementation : "
},
{
"code": null,
"e": 1508,
"s": 1500,
"text": "Python3"
},
{
"code": "import random punct = (\".\", \";\", \"!\", \"?\", \",\")count = 0new_word = \"\" inputfile = input(\"Enter input file name:\") with open(inputfile, 'r') as fin: for line in fin.readlines(): # Read line by line in txt file for word in line.split(): # Read word by word in each line if len(word) > 3: # If word length >3 '''If word ends with punctuation Remove firstletter, lastletter and punctuation Shuffle the words Add the removed letters (first letter) Add the removed letters (last letter) Add the removed letters (punctuation mark)''' if word.endswith(punct): word1 = word[1:-2] word1 = random.sample(word1, len(word1)) word1.insert(0, word[0]) word1.append(word[-2]) word1.append(word[-1]) '''If there is no punctuation mark Remove first letter and last letter Shuffle the word Add the removed letters (first letter) Add the removed letters (last letter) Append the word and \" \" to the previous words''' else: word1 = word[1:-1] word1 = random.sample(word1, len(word1)) word1.insert(0, word[0]) word1.append(word[-1]) new_word = new_word + ''.join(word1) + \" \" '''If word length <3 just append the word and \" \" to the previous words''' else: new_word = new_word + word + \" \" # \"Append to <filename>Scrambled.txt\" with open((inputfile[:-4] + \"Scrambled.txt\"), 'a+') as fout: fout.write(new_word + \"\\n\") new_word = \"\"",
"e": 3385,
"s": 1508,
"text": null
},
{
"code": null,
"e": 3394,
"s": 3385,
"text": "Output: "
},
{
"code": null,
"e": 3493,
"s": 3394,
"text": "Smcinrablg wodrs very Bauscee eevn tehy dnoes't\nicpamt Bcuesae d'not read lteter raed wrod whole. "
},
{
"code": null,
"e": 3508,
"s": 3495,
"text": "singghakshay"
},
{
"code": null,
"e": 3515,
"s": 3508,
"text": "Python"
},
{
"code": null,
"e": 3531,
"s": 3515,
"text": "Python Programs"
},
{
"code": null,
"e": 3550,
"s": 3531,
"text": "School Programming"
},
{
"code": null,
"e": 3648,
"s": 3550,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3690,
"s": 3648,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3712,
"s": 3690,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3738,
"s": 3712,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3770,
"s": 3738,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3799,
"s": 3770,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3821,
"s": 3799,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 3860,
"s": 3821,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 3898,
"s": 3860,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 3947,
"s": 3898,
"text": "Python | Convert string dictionary to dictionary"
}
] |
Microsoft Archives - GeeksforGeeks
|
Merge Sort
Largest Sum Contiguous Subarray
Reverse a linked list
Binary Search Tree | Set 1 (Search and Insertion)
Level Order Binary Tree Traversal
Stack Data Structure (Introduction and Program)
Topological Sorting
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Detect Cycle in a Directed Graph
K'th Smallest/Largest Element in Unsorted Array | Set 1
|
[
{
"code": null,
"e": 24141,
"s": 24130,
"text": "Merge Sort"
},
{
"code": null,
"e": 24173,
"s": 24141,
"text": "Largest Sum Contiguous Subarray"
},
{
"code": null,
"e": 24195,
"s": 24173,
"text": "Reverse a linked list"
},
{
"code": null,
"e": 24245,
"s": 24195,
"text": "Binary Search Tree | Set 1 (Search and Insertion)"
},
{
"code": null,
"e": 24279,
"s": 24245,
"text": "Level Order Binary Tree Traversal"
},
{
"code": null,
"e": 24327,
"s": 24279,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 24347,
"s": 24327,
"text": "Topological Sorting"
},
{
"code": null,
"e": 24432,
"s": 24347,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 24465,
"s": 24432,
"text": "Detect Cycle in a Directed Graph"
}
] |
Lodash _.toPairs() Method
|
09 Sep, 2020
The _.toPairs() method is used to create an array of own enumerable string key-value pairs for an object which can be consumed by the _.fromPairs() function. If the object is a map or set, its entries are returned.
Syntax:
_.toPairs(object)
Parameters: This method accepts a single parameter as mentioned above and described below:
object: This parameter holds the object to query.
Return Value: This method returns the array of key-value pairs.
Example 1:
Javascript
// Requiring the lodash library const _ = require("lodash"); function Fb() { this.id = 2045; this.username = 'fb_myself'; this.password = 'fb1234';} // This will not be included in the arrayFb.prototype.email = 'myself@gmail.com'; // Use of _.toPairs() method console.log(_.toPairs(new Fb));
Output:
[["id", 2045], ["username", "fb_myself"], ["password", "fb1234"]]
Example 2:
Javascript
// Requiring the lodash library const _ = require("lodash"); var GfG = { 'x': 1, 'y': 2 } // Use of _.toPairs() method console.log(_.toPairs(GfG));
Output:
[['x', 1], ['y', 2]]
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request
JavaScript | Promises
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 Sep, 2020"
},
{
"code": null,
"e": 243,
"s": 28,
"text": "The _.toPairs() method is used to create an array of own enumerable string key-value pairs for an object which can be consumed by the _.fromPairs() function. If the object is a map or set, its entries are returned."
},
{
"code": null,
"e": 251,
"s": 243,
"text": "Syntax:"
},
{
"code": null,
"e": 270,
"s": 251,
"text": "_.toPairs(object)\n"
},
{
"code": null,
"e": 361,
"s": 270,
"text": "Parameters: This method accepts a single parameter as mentioned above and described below:"
},
{
"code": null,
"e": 411,
"s": 361,
"text": "object: This parameter holds the object to query."
},
{
"code": null,
"e": 475,
"s": 411,
"text": "Return Value: This method returns the array of key-value pairs."
},
{
"code": null,
"e": 486,
"s": 475,
"text": "Example 1:"
},
{
"code": null,
"e": 497,
"s": 486,
"text": "Javascript"
},
{
"code": "// Requiring the lodash library const _ = require(\"lodash\"); function Fb() { this.id = 2045; this.username = 'fb_myself'; this.password = 'fb1234';} // This will not be included in the arrayFb.prototype.email = 'myself@gmail.com'; // Use of _.toPairs() method console.log(_.toPairs(new Fb));",
"e": 799,
"s": 497,
"text": null
},
{
"code": null,
"e": 807,
"s": 799,
"text": "Output:"
},
{
"code": null,
"e": 874,
"s": 807,
"text": "[[\"id\", 2045], [\"username\", \"fb_myself\"], [\"password\", \"fb1234\"]]\n"
},
{
"code": null,
"e": 887,
"s": 874,
"text": "Example 2: "
},
{
"code": null,
"e": 898,
"s": 887,
"text": "Javascript"
},
{
"code": "// Requiring the lodash library const _ = require(\"lodash\"); var GfG = { 'x': 1, 'y': 2 } // Use of _.toPairs() method console.log(_.toPairs(GfG));",
"e": 1061,
"s": 898,
"text": null
},
{
"code": null,
"e": 1069,
"s": 1061,
"text": "Output:"
},
{
"code": null,
"e": 1091,
"s": 1069,
"text": "[['x', 1], ['y', 2]]\n"
},
{
"code": null,
"e": 1109,
"s": 1091,
"text": "JavaScript-Lodash"
},
{
"code": null,
"e": 1120,
"s": 1109,
"text": "JavaScript"
},
{
"code": null,
"e": 1137,
"s": 1120,
"text": "Web Technologies"
},
{
"code": null,
"e": 1235,
"s": 1137,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1296,
"s": 1235,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1336,
"s": 1296,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 1378,
"s": 1336,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 1419,
"s": 1378,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 1441,
"s": 1419,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 1474,
"s": 1441,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 1536,
"s": 1474,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 1597,
"s": 1536,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1647,
"s": 1597,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
IBM Placement Paper | Logical Reasoning Set – 1
|
24 May, 2019
This is an IBM model placement paper on Logical Reasoning for placement preparation. This placement paper will cover logical reasoning questions that are asked in IBM recruitment drives and also strictly follows the pattern of questions asked in IBM interviews. It is recommended to solve each one of the following questions to increase your chances of clearing the IBM interview.
Logical Reasoning
What will be the next number? 3, 5, 7, 11, 13, 17.......21192320Answer:
19
Explanation:3, 5, 7, 11, 13, 17 is a prime number series.Hence next prime number in this series is 19Find wrong number in series: 12, 25, 49, 99, 187, 395, 78977891879949Answer:
187
Explanation:12*2+1 =2525*2-1 = 4949*2+1 = 99395*2-1 = 789Directions to solve Question 3 and 4: Each of the questions given below consists of a statement and/or a question and two statements numbered I and II given below it. You have to decide whether the data provided in the statement(s) is/are sufficient to answer the given question.Read both the statements and Give answer(a) if the data in Statement I alone is sufficient to answer the question, while the data in Statement II alone is not sufficient to answer the question.(b) if the data in Statement II alone is sufficient to answer the question, while the data in Statement I alone is not sufficient to answer the question.(c) if the data in each Statement I and Statement II alone is sufficient to answer the question.(d) if the data even in both Statements I and II together are not sufficient to answer the question.(e) if the data in both Statements I and II together are necessary to answer the question.If x, y are integers, then (x2 + y2)1/2 is an integer?Statement I – x2 + y2 is an integerStatement II – x2 – 3y2 = 0(a)(b)(c)(d)(e)Answer:
(b) data in Statement II alone is sufficient to answer the question, while the data in Statement I alone is not sufficient to answer the question.
Explanation:Given Statement II => x2 – 3y2 = 0=> x2 = 3y2Putting the above in the question=> (x2 + y2)1/2=> (3y2 + y2)1/2=> (4y2)1/2=> ((2y)2)1/2=> (2y)which is an integer as y is an integerWhat day is 14th of a month?Statement I – 3rd Saturday of the month is seventeenthStatement II – 2nd last day of the month is Tuesday(a)(b)(c)(d)(e)Answer:
(a) data in Statement I alone is sufficient to answer the question, while the data in Statement II alone is not sufficient to answer the question.
Explanation:Given Statement I, 17th, of the month, is Saturday.Therefore 14th will be WednesdayConsider the following phrase:Statement: A line from Ram’s appointment letter is “you are hereby appointed as a systems engineer with a probation period of two years and your performance will be reviewed at the end of the period for confirmation.”Assumptions:I. At the time of appointment, the performance of one generally is not well known.II. In the probation period, one tries to prove his worth generally.Choose the correct option given below.If only assumption I is implicitIf only assumption II is implicit.If either I or II is implicit.If neither I nor II is implicit.If both I and II are implicit.Answer:
(e) Both I and II are implicit.
Explanation:Both the statements are implicit because since Ram is newly appointed in this company, so at the time of appointment, the performance of Ram is not well known. Also, they have to test performance over a span of time. So Ram (systems engineer) tries to prove his worth generally in the probation period. So, option (E) is correct.Consider the following phrase:Statement: The price for safeda mango is terribly priced at Rs. 200/kg.Assumptions:I. The price for other types of mangoes are decently priced.II. Rs 200 is a very big amount to pay for a safeda mango.Choose the correct option given below.If only assumption I is implicitIf only assumption II is implicit.If either I or II is implicit.If neither I nor II is implicit.If both I and II are implicit.Answer:
(b) Only assumption II is implicit.
Explanation:The Assumption I might or might not be true according to the given Statement, but the Assumption II is definitely true. Hence only Assumption II is implicit.Statements:I – All mangoes are bananas.II – Some bananas are a globe.III – All globe are square.Conclusions:I. Some mangoes are square.II. No mango is square.Choose the correct option given below:only conclusion I is true.only conclusion II is true.either conclusion I or conclusion II is trueneither conclusion I nor conclusion II is trueboth conclusions I and II are true.Answer:
(c) either conclusion I or conclusion II is true
Explanation:Statements:I – Some C are TII – Some T are RIII – All R is MConclusions:I. Some M are TII. Some C are MChoose the correct option given below:only conclusion I is true.only conclusion II is true.either conclusion I or conclusion II is trueneither conclusion I nor conclusion II is trueboth conclusions I and II are true.Answer:
(a) only conclusion I is true.
Explanation:Some C might or might not be M. But some M are definitely T.Find wrong number in series: 23, 29, 31, 33, 41, 43, 4729334147Answer:
33
Explanation:The given series is prime numbers from 23Find wrong number in series: 8, 24, 12, 36, 18, 54, 2612241826Answer:
Explanation:Mixture of two alternate series:8*3=2424/2=1212*3=3636/2=1818*3=5454/2=27Find wrong number in series:2, 3, 6, 0, 8, -3, 14, -63083Answer:
C
Explanation:Two alternate series:2 + 4 = 6,3 – 3 = 06 + 4 = 10,0 – 3 = -310 + 4 = 14-3 – 3 = -69848 x 125 = ?1232000124200012310001233000Answer:
1231000
Explanation:9848 x 125= 9848 x 53= 9848 x (10 / 2) 3= 9848 x (103 / 23)= 9848 x (1000/8)= 1231000Directions to solve Question 13 and 14: Each of the questions given below consists of a statement and/or a question and two statements numbered I and II given below it. You have to decide whether the data provided in the statement(s) is/are sufficient to answer the given question.Read both the statements and Give answer(a) if the data in Statement I alone is sufficient to answer the question, while the data in Statement II alone is not sufficient to answer the question.(b) if the data in Statement II alone is sufficient to answer the question, while the data in Statement I alone is not sufficient to answer the question.(c) if the data in each Statement I and Statement II alone is sufficient to answer the question.(d) if the data even in both Statements I and II together are not sufficient to answer the question.(e) if the data in both Statements I and II together are necessary to answer the question.Is x + y = 0?Statement I – x.y < 0Statement II – x2 = y2(a)(b)(c)(d)(e)Answer:
(e) if the data in both Statements I and II together are necessary to answer the question.
Explanation:For x + y = 0, there are 2 cases:Case 1:x and y are of opposite sign.This can be inferred from x.y < 0Case 2:x = y = 0This can be inferred from x2 = y2Hence the data in both Statements I and II togetherare necessary to answer the question.What is the probability that x3 – 8 = 0 when x is selected from a set of 8 integers?Statement I. The smallest number in the set is -11Statement II. The arithmetic mean of the set is 1/8.(a)(b)(c)(d)(e)Answer:
(d) if the data even in both Statements I and II together are not sufficient to answer the question.
Consider the following phrase:Statement: All C are J.All J are B.No B is R.Conclusions:I. All B are C.II. Some J are CChoose the correct option given below:only conclusion I is true.only conclusion II is true.either conclusion I or conclusion II is trueneither conclusion I nor conclusion II is trueboth conclusions I and II are true.Answer:
(b) only conclusion II is true.
Explanation:All B are not CConsider the following phrase:Statement: It is advantageous to start schooling of child at the age of 5 or so.Assumptions:I. At the age of the child reaches appropriate level of development and is ready to learn.II. After 6 yrs of age schools do not admit childrenChoose the correct option given below.If only assumption I is implicitIf only assumption II is implicit.If either I or II is implicit.If neither I nor II is implicit.If both I and II are implicit.Answer:
(a) Only assumption I is implicit
Consider the following phrase:Statement: Medicine M is a drug which is causing ripples in the medical field.Assumptions:I. M is not a great drugII. No other drug is causing ripples in the medical fieldChoose the correct option given below.If only assumption I is implicitIf only assumption II is implicit.If either I or II is implicit.If neither I nor II is implicit.If both I and II are implicit.Answer:
(a) Only assumption I is implicit
Statements:I – Some S are LII – Some C are PIII – All P is RConclusions:I. Some P are LII. Some C are RChoose the correct option given below:only conclusion I is true.only conclusion II is true.either conclusion I or conclusion II is trueneither conclusion I nor conclusion II is trueboth conclusions I and II are true.Answer:
(d) neither conclusion I nor conclusion II is true
What will be the next number? 3, 5, 7, 11, 13, 17.......21192320Answer:
19
Explanation:3, 5, 7, 11, 13, 17 is a prime number series.Hence next prime number in this series is 19
21192320
21
19
23
20
Answer:
19
Explanation:
3, 5, 7, 11, 13, 17 is a prime number series.Hence next prime number in this series is 19
Find wrong number in series: 12, 25, 49, 99, 187, 395, 78977891879949Answer:
187
Explanation:12*2+1 =2525*2-1 = 4949*2+1 = 99395*2-1 = 789
77891879949
7789
187
99
49
Answer:
187
Explanation:
12*2+1 =2525*2-1 = 4949*2+1 = 99395*2-1 = 789
Directions to solve Question 3 and 4: Each of the questions given below consists of a statement and/or a question and two statements numbered I and II given below it. You have to decide whether the data provided in the statement(s) is/are sufficient to answer the given question.Read both the statements and Give answer(a) if the data in Statement I alone is sufficient to answer the question, while the data in Statement II alone is not sufficient to answer the question.(b) if the data in Statement II alone is sufficient to answer the question, while the data in Statement I alone is not sufficient to answer the question.(c) if the data in each Statement I and Statement II alone is sufficient to answer the question.(d) if the data even in both Statements I and II together are not sufficient to answer the question.(e) if the data in both Statements I and II together are necessary to answer the question.
If x, y are integers, then (x2 + y2)1/2 is an integer?Statement I – x2 + y2 is an integerStatement II – x2 – 3y2 = 0(a)(b)(c)(d)(e)Answer:
(b) data in Statement II alone is sufficient to answer the question, while the data in Statement I alone is not sufficient to answer the question.
Explanation:Given Statement II => x2 – 3y2 = 0=> x2 = 3y2Putting the above in the question=> (x2 + y2)1/2=> (3y2 + y2)1/2=> (4y2)1/2=> ((2y)2)1/2=> (2y)which is an integer as y is an integer
(a)(b)(c)(d)(e)
(a)
(b)
(c)
(d)
(e)
Answer:
(b) data in Statement II alone is sufficient to answer the question, while the data in Statement I alone is not sufficient to answer the question.
Explanation:
Given Statement II => x2 – 3y2 = 0=> x2 = 3y2
Putting the above in the question=> (x2 + y2)1/2=> (3y2 + y2)1/2=> (4y2)1/2=> ((2y)2)1/2=> (2y)which is an integer as y is an integer
What day is 14th of a month?Statement I – 3rd Saturday of the month is seventeenthStatement II – 2nd last day of the month is Tuesday(a)(b)(c)(d)(e)Answer:
(a) data in Statement I alone is sufficient to answer the question, while the data in Statement II alone is not sufficient to answer the question.
Explanation:Given Statement I, 17th, of the month, is Saturday.Therefore 14th will be Wednesday
(a)(b)(c)(d)(e)
(a)
(b)
(c)
(d)
(e)
Answer:
(a) data in Statement I alone is sufficient to answer the question, while the data in Statement II alone is not sufficient to answer the question.
Explanation:
Given Statement I, 17th, of the month, is Saturday.Therefore 14th will be Wednesday
Consider the following phrase:Statement: A line from Ram’s appointment letter is “you are hereby appointed as a systems engineer with a probation period of two years and your performance will be reviewed at the end of the period for confirmation.”Assumptions:I. At the time of appointment, the performance of one generally is not well known.II. In the probation period, one tries to prove his worth generally.Choose the correct option given below.If only assumption I is implicitIf only assumption II is implicit.If either I or II is implicit.If neither I nor II is implicit.If both I and II are implicit.Answer:
(e) Both I and II are implicit.
Explanation:Both the statements are implicit because since Ram is newly appointed in this company, so at the time of appointment, the performance of Ram is not well known. Also, they have to test performance over a span of time. So Ram (systems engineer) tries to prove his worth generally in the probation period. So, option (E) is correct.
If only assumption I is implicitIf only assumption II is implicit.If either I or II is implicit.If neither I nor II is implicit.If both I and II are implicit.
If only assumption I is implicit
If only assumption II is implicit.
If either I or II is implicit.
If neither I nor II is implicit.
If both I and II are implicit.
Answer:
(e) Both I and II are implicit.
Explanation:
Both the statements are implicit because since Ram is newly appointed in this company, so at the time of appointment, the performance of Ram is not well known. Also, they have to test performance over a span of time. So Ram (systems engineer) tries to prove his worth generally in the probation period. So, option (E) is correct.
Consider the following phrase:Statement: The price for safeda mango is terribly priced at Rs. 200/kg.Assumptions:I. The price for other types of mangoes are decently priced.II. Rs 200 is a very big amount to pay for a safeda mango.Choose the correct option given below.If only assumption I is implicitIf only assumption II is implicit.If either I or II is implicit.If neither I nor II is implicit.If both I and II are implicit.Answer:
(b) Only assumption II is implicit.
Explanation:The Assumption I might or might not be true according to the given Statement, but the Assumption II is definitely true. Hence only Assumption II is implicit.
If only assumption I is implicitIf only assumption II is implicit.If either I or II is implicit.If neither I nor II is implicit.If both I and II are implicit.
If only assumption I is implicit
If only assumption II is implicit.
If either I or II is implicit.
If neither I nor II is implicit.
If both I and II are implicit.
Answer:
(b) Only assumption II is implicit.
Explanation:
The Assumption I might or might not be true according to the given Statement, but the Assumption II is definitely true. Hence only Assumption II is implicit.
Statements:I – All mangoes are bananas.II – Some bananas are a globe.III – All globe are square.Conclusions:I. Some mangoes are square.II. No mango is square.Choose the correct option given below:only conclusion I is true.only conclusion II is true.either conclusion I or conclusion II is trueneither conclusion I nor conclusion II is trueboth conclusions I and II are true.Answer:
(c) either conclusion I or conclusion II is true
Explanation:
only conclusion I is true.only conclusion II is true.either conclusion I or conclusion II is trueneither conclusion I nor conclusion II is trueboth conclusions I and II are true.
only conclusion I is true.
only conclusion II is true.
either conclusion I or conclusion II is true
neither conclusion I nor conclusion II is true
both conclusions I and II are true.
Answer:
(c) either conclusion I or conclusion II is true
Explanation:
Statements:I – Some C are TII – Some T are RIII – All R is MConclusions:I. Some M are TII. Some C are MChoose the correct option given below:only conclusion I is true.only conclusion II is true.either conclusion I or conclusion II is trueneither conclusion I nor conclusion II is trueboth conclusions I and II are true.Answer:
(a) only conclusion I is true.
Explanation:Some C might or might not be M. But some M are definitely T.
only conclusion I is true.only conclusion II is true.either conclusion I or conclusion II is trueneither conclusion I nor conclusion II is trueboth conclusions I and II are true.
only conclusion I is true.
only conclusion II is true.
either conclusion I or conclusion II is true
neither conclusion I nor conclusion II is true
both conclusions I and II are true.
Answer:
(a) only conclusion I is true.
Explanation:
Some C might or might not be M. But some M are definitely T.
Find wrong number in series: 23, 29, 31, 33, 41, 43, 4729334147Answer:
33
Explanation:The given series is prime numbers from 23
29334147
29
33
41
47
Answer:
33
Explanation:
The given series is prime numbers from 23
Find wrong number in series: 8, 24, 12, 36, 18, 54, 2612241826Answer:
Explanation:Mixture of two alternate series:8*3=2424/2=1212*3=3636/2=1818*3=5454/2=27
12241826
12
24
18
26
Answer:
Explanation:
Mixture of two alternate series:8*3=2424/2=1212*3=3636/2=1818*3=5454/2=27
Find wrong number in series:2, 3, 6, 0, 8, -3, 14, -63083Answer:
C
Explanation:Two alternate series:2 + 4 = 6,3 – 3 = 06 + 4 = 10,0 – 3 = -310 + 4 = 14-3 – 3 = -6
3083
3
0
8
3
Answer:
C
Explanation:
Two alternate series:2 + 4 = 6,3 – 3 = 06 + 4 = 10,0 – 3 = -310 + 4 = 14-3 – 3 = -6
9848 x 125 = ?1232000124200012310001233000Answer:
1231000
Explanation:9848 x 125= 9848 x 53= 9848 x (10 / 2) 3= 9848 x (103 / 23)= 9848 x (1000/8)= 1231000
1232000124200012310001233000
1232000
1242000
1231000
1233000
Answer:
1231000
Explanation:
9848 x 125= 9848 x 53= 9848 x (10 / 2) 3= 9848 x (103 / 23)= 9848 x (1000/8)= 1231000
Directions to solve Question 13 and 14: Each of the questions given below consists of a statement and/or a question and two statements numbered I and II given below it. You have to decide whether the data provided in the statement(s) is/are sufficient to answer the given question.Read both the statements and Give answer(a) if the data in Statement I alone is sufficient to answer the question, while the data in Statement II alone is not sufficient to answer the question.(b) if the data in Statement II alone is sufficient to answer the question, while the data in Statement I alone is not sufficient to answer the question.(c) if the data in each Statement I and Statement II alone is sufficient to answer the question.(d) if the data even in both Statements I and II together are not sufficient to answer the question.(e) if the data in both Statements I and II together are necessary to answer the question.
Is x + y = 0?Statement I – x.y < 0Statement II – x2 = y2(a)(b)(c)(d)(e)Answer:
(e) if the data in both Statements I and II together are necessary to answer the question.
Explanation:For x + y = 0, there are 2 cases:Case 1:x and y are of opposite sign.This can be inferred from x.y < 0Case 2:x = y = 0This can be inferred from x2 = y2Hence the data in both Statements I and II togetherare necessary to answer the question.
(a)(b)(c)(d)(e)
(a)
(b)
(c)
(d)
(e)
Answer:
(e) if the data in both Statements I and II together are necessary to answer the question.
Explanation:
For x + y = 0, there are 2 cases:
Case 1:x and y are of opposite sign.This can be inferred from x.y < 0
Case 2:x = y = 0This can be inferred from x2 = y2
Hence the data in both Statements I and II togetherare necessary to answer the question.
What is the probability that x3 – 8 = 0 when x is selected from a set of 8 integers?Statement I. The smallest number in the set is -11Statement II. The arithmetic mean of the set is 1/8.(a)(b)(c)(d)(e)Answer:
(d) if the data even in both Statements I and II together are not sufficient to answer the question.
(a)(b)(c)(d)(e)
(a)
(b)
(c)
(d)
(e)
Answer:
(d) if the data even in both Statements I and II together are not sufficient to answer the question.
Consider the following phrase:Statement: All C are J.All J are B.No B is R.Conclusions:I. All B are C.II. Some J are CChoose the correct option given below:only conclusion I is true.only conclusion II is true.either conclusion I or conclusion II is trueneither conclusion I nor conclusion II is trueboth conclusions I and II are true.Answer:
(b) only conclusion II is true.
Explanation:All B are not C
only conclusion I is true.only conclusion II is true.either conclusion I or conclusion II is trueneither conclusion I nor conclusion II is trueboth conclusions I and II are true.
only conclusion I is true.
only conclusion II is true.
either conclusion I or conclusion II is true
neither conclusion I nor conclusion II is true
both conclusions I and II are true.
Answer:
(b) only conclusion II is true.
Explanation:
All B are not C
Consider the following phrase:Statement: It is advantageous to start schooling of child at the age of 5 or so.Assumptions:I. At the age of the child reaches appropriate level of development and is ready to learn.II. After 6 yrs of age schools do not admit childrenChoose the correct option given below.If only assumption I is implicitIf only assumption II is implicit.If either I or II is implicit.If neither I nor II is implicit.If both I and II are implicit.Answer:
(a) Only assumption I is implicit
If only assumption I is implicitIf only assumption II is implicit.If either I or II is implicit.If neither I nor II is implicit.If both I and II are implicit.
If only assumption I is implicit
If only assumption II is implicit.
If either I or II is implicit.
If neither I nor II is implicit.
If both I and II are implicit.
Answer:
(a) Only assumption I is implicit
Consider the following phrase:Statement: Medicine M is a drug which is causing ripples in the medical field.Assumptions:I. M is not a great drugII. No other drug is causing ripples in the medical fieldChoose the correct option given below.If only assumption I is implicitIf only assumption II is implicit.If either I or II is implicit.If neither I nor II is implicit.If both I and II are implicit.Answer:
(a) Only assumption I is implicit
If only assumption I is implicitIf only assumption II is implicit.If either I or II is implicit.If neither I nor II is implicit.If both I and II are implicit.
If only assumption I is implicit
If only assumption II is implicit.
If either I or II is implicit.
If neither I nor II is implicit.
If both I and II are implicit.
Answer:
(a) Only assumption I is implicit
Statements:I – Some S are LII – Some C are PIII – All P is RConclusions:I. Some P are LII. Some C are RChoose the correct option given below:only conclusion I is true.only conclusion II is true.either conclusion I or conclusion II is trueneither conclusion I nor conclusion II is trueboth conclusions I and II are true.Answer:
(d) neither conclusion I nor conclusion II is true
only conclusion I is true.only conclusion II is true.either conclusion I or conclusion II is trueneither conclusion I nor conclusion II is trueboth conclusions I and II are true.
only conclusion I is true.
only conclusion II is true.
either conclusion I or conclusion II is true
neither conclusion I nor conclusion II is true
both conclusions I and II are true.
Answer:
(d) neither conclusion I nor conclusion II is true
shubham_singh
IBM
IBM-Placement-Papers
Placements
IBM
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 20 Puzzles Commonly Asked During SDE Interviews
Programming Language For Placement - C++, Java or Python?
Print the longest path from root to leaf in a Binary tree
Interview Preparation
Problem on Numbers
Percentages
Puzzle | 50 red marbles and 50 blue marbles
Codenation Recruitment Process
Profit and Loss
Mixture and Alligation
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n24 May, 2019"
},
{
"code": null,
"e": 434,
"s": 53,
"text": "This is an IBM model placement paper on Logical Reasoning for placement preparation. This placement paper will cover logical reasoning questions that are asked in IBM recruitment drives and also strictly follows the pattern of questions asked in IBM interviews. It is recommended to solve each one of the following questions to increase your chances of clearing the IBM interview."
},
{
"code": null,
"e": 452,
"s": 434,
"text": "Logical Reasoning"
},
{
"code": null,
"e": 9015,
"s": 452,
"text": "What will be the next number? 3, 5, 7, 11, 13, 17.......21192320Answer:\n19\nExplanation:3, 5, 7, 11, 13, 17 is a prime number series.Hence next prime number in this series is 19Find wrong number in series: 12, 25, 49, 99, 187, 395, 78977891879949Answer:\n187\nExplanation:12*2+1 =2525*2-1 = 4949*2+1 = 99395*2-1 = 789Directions to solve Question 3 and 4: Each of the questions given below consists of a statement and/or a question and two statements numbered I and II given below it. You have to decide whether the data provided in the statement(s) is/are sufficient to answer the given question.Read both the statements and Give answer(a) if the data in Statement I alone is sufficient to answer the question, while the data in Statement II alone is not sufficient to answer the question.(b) if the data in Statement II alone is sufficient to answer the question, while the data in Statement I alone is not sufficient to answer the question.(c) if the data in each Statement I and Statement II alone is sufficient to answer the question.(d) if the data even in both Statements I and II together are not sufficient to answer the question.(e) if the data in both Statements I and II together are necessary to answer the question.If x, y are integers, then (x2 + y2)1/2 is an integer?Statement I – x2 + y2 is an integerStatement II – x2 – 3y2 = 0(a)(b)(c)(d)(e)Answer:\n(b) data in Statement II alone is sufficient to answer the question, while the data in Statement I alone is not sufficient to answer the question.\nExplanation:Given Statement II => x2 – 3y2 = 0=> x2 = 3y2Putting the above in the question=> (x2 + y2)1/2=> (3y2 + y2)1/2=> (4y2)1/2=> ((2y)2)1/2=> (2y)which is an integer as y is an integerWhat day is 14th of a month?Statement I – 3rd Saturday of the month is seventeenthStatement II – 2nd last day of the month is Tuesday(a)(b)(c)(d)(e)Answer:\n(a) data in Statement I alone is sufficient to answer the question, while the data in Statement II alone is not sufficient to answer the question.\nExplanation:Given Statement I, 17th, of the month, is Saturday.Therefore 14th will be WednesdayConsider the following phrase:Statement: A line from Ram’s appointment letter is “you are hereby appointed as a systems engineer with a probation period of two years and your performance will be reviewed at the end of the period for confirmation.”Assumptions:I. At the time of appointment, the performance of one generally is not well known.II. In the probation period, one tries to prove his worth generally.Choose the correct option given below.If only assumption I is implicitIf only assumption II is implicit.If either I or II is implicit.If neither I nor II is implicit.If both I and II are implicit.Answer:\n(e) Both I and II are implicit.\nExplanation:Both the statements are implicit because since Ram is newly appointed in this company, so at the time of appointment, the performance of Ram is not well known. Also, they have to test performance over a span of time. So Ram (systems engineer) tries to prove his worth generally in the probation period. So, option (E) is correct.Consider the following phrase:Statement: The price for safeda mango is terribly priced at Rs. 200/kg.Assumptions:I. The price for other types of mangoes are decently priced.II. Rs 200 is a very big amount to pay for a safeda mango.Choose the correct option given below.If only assumption I is implicitIf only assumption II is implicit.If either I or II is implicit.If neither I nor II is implicit.If both I and II are implicit.Answer:\n(b) Only assumption II is implicit.\nExplanation:The Assumption I might or might not be true according to the given Statement, but the Assumption II is definitely true. Hence only Assumption II is implicit.Statements:I – All mangoes are bananas.II – Some bananas are a globe.III – All globe are square.Conclusions:I. Some mangoes are square.II. No mango is square.Choose the correct option given below:only conclusion I is true.only conclusion II is true.either conclusion I or conclusion II is trueneither conclusion I nor conclusion II is trueboth conclusions I and II are true.Answer:\n(c) either conclusion I or conclusion II is true\nExplanation:Statements:I – Some C are TII – Some T are RIII – All R is MConclusions:I. Some M are TII. Some C are MChoose the correct option given below:only conclusion I is true.only conclusion II is true.either conclusion I or conclusion II is trueneither conclusion I nor conclusion II is trueboth conclusions I and II are true.Answer:\n(a) only conclusion I is true.\nExplanation:Some C might or might not be M. But some M are definitely T.Find wrong number in series: 23, 29, 31, 33, 41, 43, 4729334147Answer:\n33\nExplanation:The given series is prime numbers from 23Find wrong number in series: 8, 24, 12, 36, 18, 54, 2612241826Answer:\n\nExplanation:Mixture of two alternate series:8*3=2424/2=1212*3=3636/2=1818*3=5454/2=27Find wrong number in series:2, 3, 6, 0, 8, -3, 14, -63083Answer:\nC\nExplanation:Two alternate series:2 + 4 = 6,3 – 3 = 06 + 4 = 10,0 – 3 = -310 + 4 = 14-3 – 3 = -69848 x 125 = ?1232000124200012310001233000Answer:\n1231000\nExplanation:9848 x 125= 9848 x 53= 9848 x (10 / 2) 3= 9848 x (103 / 23)= 9848 x (1000/8)= 1231000Directions to solve Question 13 and 14: Each of the questions given below consists of a statement and/or a question and two statements numbered I and II given below it. You have to decide whether the data provided in the statement(s) is/are sufficient to answer the given question.Read both the statements and Give answer(a) if the data in Statement I alone is sufficient to answer the question, while the data in Statement II alone is not sufficient to answer the question.(b) if the data in Statement II alone is sufficient to answer the question, while the data in Statement I alone is not sufficient to answer the question.(c) if the data in each Statement I and Statement II alone is sufficient to answer the question.(d) if the data even in both Statements I and II together are not sufficient to answer the question.(e) if the data in both Statements I and II together are necessary to answer the question.Is x + y = 0?Statement I – x.y < 0Statement II – x2 = y2(a)(b)(c)(d)(e)Answer:\n(e) if the data in both Statements I and II together are necessary to answer the question.\nExplanation:For x + y = 0, there are 2 cases:Case 1:x and y are of opposite sign.This can be inferred from x.y < 0Case 2:x = y = 0This can be inferred from x2 = y2Hence the data in both Statements I and II togetherare necessary to answer the question.What is the probability that x3 – 8 = 0 when x is selected from a set of 8 integers?Statement I. The smallest number in the set is -11Statement II. The arithmetic mean of the set is 1/8.(a)(b)(c)(d)(e)Answer:\n(d) if the data even in both Statements I and II together are not sufficient to answer the question.\nConsider the following phrase:Statement: All C are J.All J are B.No B is R.Conclusions:I. All B are C.II. Some J are CChoose the correct option given below:only conclusion I is true.only conclusion II is true.either conclusion I or conclusion II is trueneither conclusion I nor conclusion II is trueboth conclusions I and II are true.Answer:\n(b) only conclusion II is true.\nExplanation:All B are not CConsider the following phrase:Statement: It is advantageous to start schooling of child at the age of 5 or so.Assumptions:I. At the age of the child reaches appropriate level of development and is ready to learn.II. After 6 yrs of age schools do not admit childrenChoose the correct option given below.If only assumption I is implicitIf only assumption II is implicit.If either I or II is implicit.If neither I nor II is implicit.If both I and II are implicit.Answer:\n(a) Only assumption I is implicit\nConsider the following phrase:Statement: Medicine M is a drug which is causing ripples in the medical field.Assumptions:I. M is not a great drugII. No other drug is causing ripples in the medical fieldChoose the correct option given below.If only assumption I is implicitIf only assumption II is implicit.If either I or II is implicit.If neither I nor II is implicit.If both I and II are implicit.Answer:\n(a) Only assumption I is implicit\nStatements:I – Some S are LII – Some C are PIII – All P is RConclusions:I. Some P are LII. Some C are RChoose the correct option given below:only conclusion I is true.only conclusion II is true.either conclusion I or conclusion II is trueneither conclusion I nor conclusion II is trueboth conclusions I and II are true.Answer:\n(d) neither conclusion I nor conclusion II is true\n"
},
{
"code": null,
"e": 9192,
"s": 9015,
"text": "What will be the next number? 3, 5, 7, 11, 13, 17.......21192320Answer:\n19\nExplanation:3, 5, 7, 11, 13, 17 is a prime number series.Hence next prime number in this series is 19"
},
{
"code": null,
"e": 9201,
"s": 9192,
"text": "21192320"
},
{
"code": null,
"e": 9204,
"s": 9201,
"text": "21"
},
{
"code": null,
"e": 9207,
"s": 9204,
"text": "19"
},
{
"code": null,
"e": 9210,
"s": 9207,
"text": "23"
},
{
"code": null,
"e": 9213,
"s": 9210,
"text": "20"
},
{
"code": null,
"e": 9221,
"s": 9213,
"text": "Answer:"
},
{
"code": null,
"e": 9226,
"s": 9221,
"text": "\n19\n"
},
{
"code": null,
"e": 9239,
"s": 9226,
"text": "Explanation:"
},
{
"code": null,
"e": 9329,
"s": 9239,
"text": "3, 5, 7, 11, 13, 17 is a prime number series.Hence next prime number in this series is 19"
},
{
"code": null,
"e": 9468,
"s": 9329,
"text": "Find wrong number in series: 12, 25, 49, 99, 187, 395, 78977891879949Answer:\n187\nExplanation:12*2+1 =2525*2-1 = 4949*2+1 = 99395*2-1 = 789"
},
{
"code": null,
"e": 9480,
"s": 9468,
"text": "77891879949"
},
{
"code": null,
"e": 9485,
"s": 9480,
"text": "7789"
},
{
"code": null,
"e": 9489,
"s": 9485,
"text": "187"
},
{
"code": null,
"e": 9492,
"s": 9489,
"text": "99"
},
{
"code": null,
"e": 9495,
"s": 9492,
"text": "49"
},
{
"code": null,
"e": 9503,
"s": 9495,
"text": "Answer:"
},
{
"code": null,
"e": 9509,
"s": 9503,
"text": "\n187\n"
},
{
"code": null,
"e": 9522,
"s": 9509,
"text": "Explanation:"
},
{
"code": null,
"e": 9568,
"s": 9522,
"text": "12*2+1 =2525*2-1 = 4949*2+1 = 99395*2-1 = 789"
},
{
"code": null,
"e": 10480,
"s": 9568,
"text": "Directions to solve Question 3 and 4: Each of the questions given below consists of a statement and/or a question and two statements numbered I and II given below it. You have to decide whether the data provided in the statement(s) is/are sufficient to answer the given question.Read both the statements and Give answer(a) if the data in Statement I alone is sufficient to answer the question, while the data in Statement II alone is not sufficient to answer the question.(b) if the data in Statement II alone is sufficient to answer the question, while the data in Statement I alone is not sufficient to answer the question.(c) if the data in each Statement I and Statement II alone is sufficient to answer the question.(d) if the data even in both Statements I and II together are not sufficient to answer the question.(e) if the data in both Statements I and II together are necessary to answer the question."
},
{
"code": null,
"e": 10957,
"s": 10480,
"text": "If x, y are integers, then (x2 + y2)1/2 is an integer?Statement I – x2 + y2 is an integerStatement II – x2 – 3y2 = 0(a)(b)(c)(d)(e)Answer:\n(b) data in Statement II alone is sufficient to answer the question, while the data in Statement I alone is not sufficient to answer the question.\nExplanation:Given Statement II => x2 – 3y2 = 0=> x2 = 3y2Putting the above in the question=> (x2 + y2)1/2=> (3y2 + y2)1/2=> (4y2)1/2=> ((2y)2)1/2=> (2y)which is an integer as y is an integer"
},
{
"code": null,
"e": 10973,
"s": 10957,
"text": "(a)(b)(c)(d)(e)"
},
{
"code": null,
"e": 10977,
"s": 10973,
"text": "(a)"
},
{
"code": null,
"e": 10981,
"s": 10977,
"text": "(b)"
},
{
"code": null,
"e": 10985,
"s": 10981,
"text": "(c)"
},
{
"code": null,
"e": 10989,
"s": 10985,
"text": "(d)"
},
{
"code": null,
"e": 10993,
"s": 10989,
"text": "(e)"
},
{
"code": null,
"e": 11001,
"s": 10993,
"text": "Answer:"
},
{
"code": null,
"e": 11150,
"s": 11001,
"text": "\n(b) data in Statement II alone is sufficient to answer the question, while the data in Statement I alone is not sufficient to answer the question.\n"
},
{
"code": null,
"e": 11163,
"s": 11150,
"text": "Explanation:"
},
{
"code": null,
"e": 11209,
"s": 11163,
"text": "Given Statement II => x2 – 3y2 = 0=> x2 = 3y2"
},
{
"code": null,
"e": 11343,
"s": 11209,
"text": "Putting the above in the question=> (x2 + y2)1/2=> (3y2 + y2)1/2=> (4y2)1/2=> ((2y)2)1/2=> (2y)which is an integer as y is an integer"
},
{
"code": null,
"e": 11742,
"s": 11343,
"text": "What day is 14th of a month?Statement I – 3rd Saturday of the month is seventeenthStatement II – 2nd last day of the month is Tuesday(a)(b)(c)(d)(e)Answer:\n(a) data in Statement I alone is sufficient to answer the question, while the data in Statement II alone is not sufficient to answer the question.\nExplanation:Given Statement I, 17th, of the month, is Saturday.Therefore 14th will be Wednesday"
},
{
"code": null,
"e": 11758,
"s": 11742,
"text": "(a)(b)(c)(d)(e)"
},
{
"code": null,
"e": 11762,
"s": 11758,
"text": "(a)"
},
{
"code": null,
"e": 11766,
"s": 11762,
"text": "(b)"
},
{
"code": null,
"e": 11770,
"s": 11766,
"text": "(c)"
},
{
"code": null,
"e": 11774,
"s": 11770,
"text": "(d)"
},
{
"code": null,
"e": 11778,
"s": 11774,
"text": "(e)"
},
{
"code": null,
"e": 11786,
"s": 11778,
"text": "Answer:"
},
{
"code": null,
"e": 11935,
"s": 11786,
"text": "\n(a) data in Statement I alone is sufficient to answer the question, while the data in Statement II alone is not sufficient to answer the question.\n"
},
{
"code": null,
"e": 11948,
"s": 11935,
"text": "Explanation:"
},
{
"code": null,
"e": 12032,
"s": 11948,
"text": "Given Statement I, 17th, of the month, is Saturday.Therefore 14th will be Wednesday"
},
{
"code": null,
"e": 13019,
"s": 12032,
"text": "Consider the following phrase:Statement: A line from Ram’s appointment letter is “you are hereby appointed as a systems engineer with a probation period of two years and your performance will be reviewed at the end of the period for confirmation.”Assumptions:I. At the time of appointment, the performance of one generally is not well known.II. In the probation period, one tries to prove his worth generally.Choose the correct option given below.If only assumption I is implicitIf only assumption II is implicit.If either I or II is implicit.If neither I nor II is implicit.If both I and II are implicit.Answer:\n(e) Both I and II are implicit.\nExplanation:Both the statements are implicit because since Ram is newly appointed in this company, so at the time of appointment, the performance of Ram is not well known. Also, they have to test performance over a span of time. So Ram (systems engineer) tries to prove his worth generally in the probation period. So, option (E) is correct."
},
{
"code": null,
"e": 13178,
"s": 13019,
"text": "If only assumption I is implicitIf only assumption II is implicit.If either I or II is implicit.If neither I nor II is implicit.If both I and II are implicit."
},
{
"code": null,
"e": 13211,
"s": 13178,
"text": "If only assumption I is implicit"
},
{
"code": null,
"e": 13246,
"s": 13211,
"text": "If only assumption II is implicit."
},
{
"code": null,
"e": 13277,
"s": 13246,
"text": "If either I or II is implicit."
},
{
"code": null,
"e": 13310,
"s": 13277,
"text": "If neither I nor II is implicit."
},
{
"code": null,
"e": 13341,
"s": 13310,
"text": "If both I and II are implicit."
},
{
"code": null,
"e": 13349,
"s": 13341,
"text": "Answer:"
},
{
"code": null,
"e": 13383,
"s": 13349,
"text": "\n(e) Both I and II are implicit.\n"
},
{
"code": null,
"e": 13396,
"s": 13383,
"text": "Explanation:"
},
{
"code": null,
"e": 13726,
"s": 13396,
"text": "Both the statements are implicit because since Ram is newly appointed in this company, so at the time of appointment, the performance of Ram is not well known. Also, they have to test performance over a span of time. So Ram (systems engineer) tries to prove his worth generally in the probation period. So, option (E) is correct."
},
{
"code": null,
"e": 14367,
"s": 13726,
"text": "Consider the following phrase:Statement: The price for safeda mango is terribly priced at Rs. 200/kg.Assumptions:I. The price for other types of mangoes are decently priced.II. Rs 200 is a very big amount to pay for a safeda mango.Choose the correct option given below.If only assumption I is implicitIf only assumption II is implicit.If either I or II is implicit.If neither I nor II is implicit.If both I and II are implicit.Answer:\n(b) Only assumption II is implicit.\nExplanation:The Assumption I might or might not be true according to the given Statement, but the Assumption II is definitely true. Hence only Assumption II is implicit."
},
{
"code": null,
"e": 14526,
"s": 14367,
"text": "If only assumption I is implicitIf only assumption II is implicit.If either I or II is implicit.If neither I nor II is implicit.If both I and II are implicit."
},
{
"code": null,
"e": 14559,
"s": 14526,
"text": "If only assumption I is implicit"
},
{
"code": null,
"e": 14594,
"s": 14559,
"text": "If only assumption II is implicit."
},
{
"code": null,
"e": 14625,
"s": 14594,
"text": "If either I or II is implicit."
},
{
"code": null,
"e": 14658,
"s": 14625,
"text": "If neither I nor II is implicit."
},
{
"code": null,
"e": 14689,
"s": 14658,
"text": "If both I and II are implicit."
},
{
"code": null,
"e": 14697,
"s": 14689,
"text": "Answer:"
},
{
"code": null,
"e": 14735,
"s": 14697,
"text": "\n(b) Only assumption II is implicit.\n"
},
{
"code": null,
"e": 14748,
"s": 14735,
"text": "Explanation:"
},
{
"code": null,
"e": 14906,
"s": 14748,
"text": "The Assumption I might or might not be true according to the given Statement, but the Assumption II is definitely true. Hence only Assumption II is implicit."
},
{
"code": null,
"e": 15350,
"s": 14906,
"text": "Statements:I – All mangoes are bananas.II – Some bananas are a globe.III – All globe are square.Conclusions:I. Some mangoes are square.II. No mango is square.Choose the correct option given below:only conclusion I is true.only conclusion II is true.either conclusion I or conclusion II is trueneither conclusion I nor conclusion II is trueboth conclusions I and II are true.Answer:\n(c) either conclusion I or conclusion II is true\nExplanation:"
},
{
"code": null,
"e": 15529,
"s": 15350,
"text": "only conclusion I is true.only conclusion II is true.either conclusion I or conclusion II is trueneither conclusion I nor conclusion II is trueboth conclusions I and II are true."
},
{
"code": null,
"e": 15556,
"s": 15529,
"text": "only conclusion I is true."
},
{
"code": null,
"e": 15584,
"s": 15556,
"text": "only conclusion II is true."
},
{
"code": null,
"e": 15629,
"s": 15584,
"text": "either conclusion I or conclusion II is true"
},
{
"code": null,
"e": 15676,
"s": 15629,
"text": "neither conclusion I nor conclusion II is true"
},
{
"code": null,
"e": 15712,
"s": 15676,
"text": "both conclusions I and II are true."
},
{
"code": null,
"e": 15720,
"s": 15712,
"text": "Answer:"
},
{
"code": null,
"e": 15771,
"s": 15720,
"text": "\n(c) either conclusion I or conclusion II is true\n"
},
{
"code": null,
"e": 15784,
"s": 15771,
"text": "Explanation:"
},
{
"code": null,
"e": 16215,
"s": 15784,
"text": "Statements:I – Some C are TII – Some T are RIII – All R is MConclusions:I. Some M are TII. Some C are MChoose the correct option given below:only conclusion I is true.only conclusion II is true.either conclusion I or conclusion II is trueneither conclusion I nor conclusion II is trueboth conclusions I and II are true.Answer:\n(a) only conclusion I is true.\nExplanation:Some C might or might not be M. But some M are definitely T."
},
{
"code": null,
"e": 16394,
"s": 16215,
"text": "only conclusion I is true.only conclusion II is true.either conclusion I or conclusion II is trueneither conclusion I nor conclusion II is trueboth conclusions I and II are true."
},
{
"code": null,
"e": 16421,
"s": 16394,
"text": "only conclusion I is true."
},
{
"code": null,
"e": 16449,
"s": 16421,
"text": "only conclusion II is true."
},
{
"code": null,
"e": 16494,
"s": 16449,
"text": "either conclusion I or conclusion II is true"
},
{
"code": null,
"e": 16541,
"s": 16494,
"text": "neither conclusion I nor conclusion II is true"
},
{
"code": null,
"e": 16577,
"s": 16541,
"text": "both conclusions I and II are true."
},
{
"code": null,
"e": 16585,
"s": 16577,
"text": "Answer:"
},
{
"code": null,
"e": 16618,
"s": 16585,
"text": "\n(a) only conclusion I is true.\n"
},
{
"code": null,
"e": 16631,
"s": 16618,
"text": "Explanation:"
},
{
"code": null,
"e": 16692,
"s": 16631,
"text": "Some C might or might not be M. But some M are definitely T."
},
{
"code": null,
"e": 16820,
"s": 16692,
"text": "Find wrong number in series: 23, 29, 31, 33, 41, 43, 4729334147Answer:\n33\nExplanation:The given series is prime numbers from 23"
},
{
"code": null,
"e": 16829,
"s": 16820,
"text": "29334147"
},
{
"code": null,
"e": 16832,
"s": 16829,
"text": "29"
},
{
"code": null,
"e": 16835,
"s": 16832,
"text": "33"
},
{
"code": null,
"e": 16838,
"s": 16835,
"text": "41"
},
{
"code": null,
"e": 16841,
"s": 16838,
"text": "47"
},
{
"code": null,
"e": 16849,
"s": 16841,
"text": "Answer:"
},
{
"code": null,
"e": 16854,
"s": 16849,
"text": "\n33\n"
},
{
"code": null,
"e": 16867,
"s": 16854,
"text": "Explanation:"
},
{
"code": null,
"e": 16909,
"s": 16867,
"text": "The given series is prime numbers from 23"
},
{
"code": null,
"e": 17066,
"s": 16909,
"text": "Find wrong number in series: 8, 24, 12, 36, 18, 54, 2612241826Answer:\n\nExplanation:Mixture of two alternate series:8*3=2424/2=1212*3=3636/2=1818*3=5454/2=27"
},
{
"code": null,
"e": 17075,
"s": 17066,
"text": "12241826"
},
{
"code": null,
"e": 17078,
"s": 17075,
"text": "12"
},
{
"code": null,
"e": 17081,
"s": 17078,
"text": "24"
},
{
"code": null,
"e": 17084,
"s": 17081,
"text": "18"
},
{
"code": null,
"e": 17087,
"s": 17084,
"text": "26"
},
{
"code": null,
"e": 17095,
"s": 17087,
"text": "Answer:"
},
{
"code": null,
"e": 17111,
"s": 17098,
"text": "Explanation:"
},
{
"code": null,
"e": 17185,
"s": 17111,
"text": "Mixture of two alternate series:8*3=2424/2=1212*3=3636/2=1818*3=5454/2=27"
},
{
"code": null,
"e": 17348,
"s": 17185,
"text": "Find wrong number in series:2, 3, 6, 0, 8, -3, 14, -63083Answer:\nC\nExplanation:Two alternate series:2 + 4 = 6,3 – 3 = 06 + 4 = 10,0 – 3 = -310 + 4 = 14-3 – 3 = -6"
},
{
"code": null,
"e": 17353,
"s": 17348,
"text": "3083"
},
{
"code": null,
"e": 17355,
"s": 17353,
"text": "3"
},
{
"code": null,
"e": 17357,
"s": 17355,
"text": "0"
},
{
"code": null,
"e": 17359,
"s": 17357,
"text": "8"
},
{
"code": null,
"e": 17361,
"s": 17359,
"text": "3"
},
{
"code": null,
"e": 17369,
"s": 17361,
"text": "Answer:"
},
{
"code": null,
"e": 17373,
"s": 17369,
"text": "\nC\n"
},
{
"code": null,
"e": 17386,
"s": 17373,
"text": "Explanation:"
},
{
"code": null,
"e": 17470,
"s": 17386,
"text": "Two alternate series:2 + 4 = 6,3 – 3 = 06 + 4 = 10,0 – 3 = -310 + 4 = 14-3 – 3 = -6"
},
{
"code": null,
"e": 17626,
"s": 17470,
"text": "9848 x 125 = ?1232000124200012310001233000Answer:\n1231000\nExplanation:9848 x 125= 9848 x 53= 9848 x (10 / 2) 3= 9848 x (103 / 23)= 9848 x (1000/8)= 1231000"
},
{
"code": null,
"e": 17655,
"s": 17626,
"text": "1232000124200012310001233000"
},
{
"code": null,
"e": 17663,
"s": 17655,
"text": "1232000"
},
{
"code": null,
"e": 17671,
"s": 17663,
"text": "1242000"
},
{
"code": null,
"e": 17679,
"s": 17671,
"text": "1231000"
},
{
"code": null,
"e": 17687,
"s": 17679,
"text": "1233000"
},
{
"code": null,
"e": 17695,
"s": 17687,
"text": "Answer:"
},
{
"code": null,
"e": 17705,
"s": 17695,
"text": "\n1231000\n"
},
{
"code": null,
"e": 17718,
"s": 17705,
"text": "Explanation:"
},
{
"code": null,
"e": 17804,
"s": 17718,
"text": "9848 x 125= 9848 x 53= 9848 x (10 / 2) 3= 9848 x (103 / 23)= 9848 x (1000/8)= 1231000"
},
{
"code": null,
"e": 18718,
"s": 17804,
"text": "Directions to solve Question 13 and 14: Each of the questions given below consists of a statement and/or a question and two statements numbered I and II given below it. You have to decide whether the data provided in the statement(s) is/are sufficient to answer the given question.Read both the statements and Give answer(a) if the data in Statement I alone is sufficient to answer the question, while the data in Statement II alone is not sufficient to answer the question.(b) if the data in Statement II alone is sufficient to answer the question, while the data in Statement I alone is not sufficient to answer the question.(c) if the data in each Statement I and Statement II alone is sufficient to answer the question.(d) if the data even in both Statements I and II together are not sufficient to answer the question.(e) if the data in both Statements I and II together are necessary to answer the question."
},
{
"code": null,
"e": 19140,
"s": 18718,
"text": "Is x + y = 0?Statement I – x.y < 0Statement II – x2 = y2(a)(b)(c)(d)(e)Answer:\n(e) if the data in both Statements I and II together are necessary to answer the question.\nExplanation:For x + y = 0, there are 2 cases:Case 1:x and y are of opposite sign.This can be inferred from x.y < 0Case 2:x = y = 0This can be inferred from x2 = y2Hence the data in both Statements I and II togetherare necessary to answer the question."
},
{
"code": null,
"e": 19156,
"s": 19140,
"text": "(a)(b)(c)(d)(e)"
},
{
"code": null,
"e": 19160,
"s": 19156,
"text": "(a)"
},
{
"code": null,
"e": 19164,
"s": 19160,
"text": "(b)"
},
{
"code": null,
"e": 19168,
"s": 19164,
"text": "(c)"
},
{
"code": null,
"e": 19172,
"s": 19168,
"text": "(d)"
},
{
"code": null,
"e": 19176,
"s": 19172,
"text": "(e)"
},
{
"code": null,
"e": 19184,
"s": 19176,
"text": "Answer:"
},
{
"code": null,
"e": 19277,
"s": 19184,
"text": "\n(e) if the data in both Statements I and II together are necessary to answer the question.\n"
},
{
"code": null,
"e": 19290,
"s": 19277,
"text": "Explanation:"
},
{
"code": null,
"e": 19324,
"s": 19290,
"text": "For x + y = 0, there are 2 cases:"
},
{
"code": null,
"e": 19394,
"s": 19324,
"text": "Case 1:x and y are of opposite sign.This can be inferred from x.y < 0"
},
{
"code": null,
"e": 19444,
"s": 19394,
"text": "Case 2:x = y = 0This can be inferred from x2 = y2"
},
{
"code": null,
"e": 19533,
"s": 19444,
"text": "Hence the data in both Statements I and II togetherare necessary to answer the question."
},
{
"code": null,
"e": 19844,
"s": 19533,
"text": "What is the probability that x3 – 8 = 0 when x is selected from a set of 8 integers?Statement I. The smallest number in the set is -11Statement II. The arithmetic mean of the set is 1/8.(a)(b)(c)(d)(e)Answer:\n(d) if the data even in both Statements I and II together are not sufficient to answer the question.\n"
},
{
"code": null,
"e": 19860,
"s": 19844,
"text": "(a)(b)(c)(d)(e)"
},
{
"code": null,
"e": 19864,
"s": 19860,
"text": "(a)"
},
{
"code": null,
"e": 19868,
"s": 19864,
"text": "(b)"
},
{
"code": null,
"e": 19872,
"s": 19868,
"text": "(c)"
},
{
"code": null,
"e": 19876,
"s": 19872,
"text": "(d)"
},
{
"code": null,
"e": 19880,
"s": 19876,
"text": "(e)"
},
{
"code": null,
"e": 19888,
"s": 19880,
"text": "Answer:"
},
{
"code": null,
"e": 19991,
"s": 19888,
"text": "\n(d) if the data even in both Statements I and II together are not sufficient to answer the question.\n"
},
{
"code": null,
"e": 20393,
"s": 19991,
"text": "Consider the following phrase:Statement: All C are J.All J are B.No B is R.Conclusions:I. All B are C.II. Some J are CChoose the correct option given below:only conclusion I is true.only conclusion II is true.either conclusion I or conclusion II is trueneither conclusion I nor conclusion II is trueboth conclusions I and II are true.Answer:\n(b) only conclusion II is true.\nExplanation:All B are not C"
},
{
"code": null,
"e": 20572,
"s": 20393,
"text": "only conclusion I is true.only conclusion II is true.either conclusion I or conclusion II is trueneither conclusion I nor conclusion II is trueboth conclusions I and II are true."
},
{
"code": null,
"e": 20599,
"s": 20572,
"text": "only conclusion I is true."
},
{
"code": null,
"e": 20627,
"s": 20599,
"text": "only conclusion II is true."
},
{
"code": null,
"e": 20672,
"s": 20627,
"text": "either conclusion I or conclusion II is true"
},
{
"code": null,
"e": 20719,
"s": 20672,
"text": "neither conclusion I nor conclusion II is true"
},
{
"code": null,
"e": 20755,
"s": 20719,
"text": "both conclusions I and II are true."
},
{
"code": null,
"e": 20763,
"s": 20755,
"text": "Answer:"
},
{
"code": null,
"e": 20797,
"s": 20763,
"text": "\n(b) only conclusion II is true.\n"
},
{
"code": null,
"e": 20810,
"s": 20797,
"text": "Explanation:"
},
{
"code": null,
"e": 20826,
"s": 20810,
"text": "All B are not C"
},
{
"code": null,
"e": 21329,
"s": 20826,
"text": "Consider the following phrase:Statement: It is advantageous to start schooling of child at the age of 5 or so.Assumptions:I. At the age of the child reaches appropriate level of development and is ready to learn.II. After 6 yrs of age schools do not admit childrenChoose the correct option given below.If only assumption I is implicitIf only assumption II is implicit.If either I or II is implicit.If neither I nor II is implicit.If both I and II are implicit.Answer:\n(a) Only assumption I is implicit\n"
},
{
"code": null,
"e": 21488,
"s": 21329,
"text": "If only assumption I is implicitIf only assumption II is implicit.If either I or II is implicit.If neither I nor II is implicit.If both I and II are implicit."
},
{
"code": null,
"e": 21521,
"s": 21488,
"text": "If only assumption I is implicit"
},
{
"code": null,
"e": 21556,
"s": 21521,
"text": "If only assumption II is implicit."
},
{
"code": null,
"e": 21587,
"s": 21556,
"text": "If either I or II is implicit."
},
{
"code": null,
"e": 21620,
"s": 21587,
"text": "If neither I nor II is implicit."
},
{
"code": null,
"e": 21651,
"s": 21620,
"text": "If both I and II are implicit."
},
{
"code": null,
"e": 21659,
"s": 21651,
"text": "Answer:"
},
{
"code": null,
"e": 21695,
"s": 21659,
"text": "\n(a) Only assumption I is implicit\n"
},
{
"code": null,
"e": 22135,
"s": 21695,
"text": "Consider the following phrase:Statement: Medicine M is a drug which is causing ripples in the medical field.Assumptions:I. M is not a great drugII. No other drug is causing ripples in the medical fieldChoose the correct option given below.If only assumption I is implicitIf only assumption II is implicit.If either I or II is implicit.If neither I nor II is implicit.If both I and II are implicit.Answer:\n(a) Only assumption I is implicit\n"
},
{
"code": null,
"e": 22294,
"s": 22135,
"text": "If only assumption I is implicitIf only assumption II is implicit.If either I or II is implicit.If neither I nor II is implicit.If both I and II are implicit."
},
{
"code": null,
"e": 22327,
"s": 22294,
"text": "If only assumption I is implicit"
},
{
"code": null,
"e": 22362,
"s": 22327,
"text": "If only assumption II is implicit."
},
{
"code": null,
"e": 22393,
"s": 22362,
"text": "If either I or II is implicit."
},
{
"code": null,
"e": 22426,
"s": 22393,
"text": "If neither I nor II is implicit."
},
{
"code": null,
"e": 22457,
"s": 22426,
"text": "If both I and II are implicit."
},
{
"code": null,
"e": 22465,
"s": 22457,
"text": "Answer:"
},
{
"code": null,
"e": 22501,
"s": 22465,
"text": "\n(a) Only assumption I is implicit\n"
},
{
"code": null,
"e": 22880,
"s": 22501,
"text": "Statements:I – Some S are LII – Some C are PIII – All P is RConclusions:I. Some P are LII. Some C are RChoose the correct option given below:only conclusion I is true.only conclusion II is true.either conclusion I or conclusion II is trueneither conclusion I nor conclusion II is trueboth conclusions I and II are true.Answer:\n(d) neither conclusion I nor conclusion II is true\n"
},
{
"code": null,
"e": 23059,
"s": 22880,
"text": "only conclusion I is true.only conclusion II is true.either conclusion I or conclusion II is trueneither conclusion I nor conclusion II is trueboth conclusions I and II are true."
},
{
"code": null,
"e": 23086,
"s": 23059,
"text": "only conclusion I is true."
},
{
"code": null,
"e": 23114,
"s": 23086,
"text": "only conclusion II is true."
},
{
"code": null,
"e": 23159,
"s": 23114,
"text": "either conclusion I or conclusion II is true"
},
{
"code": null,
"e": 23206,
"s": 23159,
"text": "neither conclusion I nor conclusion II is true"
},
{
"code": null,
"e": 23242,
"s": 23206,
"text": "both conclusions I and II are true."
},
{
"code": null,
"e": 23250,
"s": 23242,
"text": "Answer:"
},
{
"code": null,
"e": 23303,
"s": 23250,
"text": "\n(d) neither conclusion I nor conclusion II is true\n"
},
{
"code": null,
"e": 23317,
"s": 23303,
"text": "shubham_singh"
},
{
"code": null,
"e": 23321,
"s": 23317,
"text": "IBM"
},
{
"code": null,
"e": 23342,
"s": 23321,
"text": "IBM-Placement-Papers"
},
{
"code": null,
"e": 23353,
"s": 23342,
"text": "Placements"
},
{
"code": null,
"e": 23357,
"s": 23353,
"text": "IBM"
},
{
"code": null,
"e": 23455,
"s": 23357,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 23507,
"s": 23455,
"text": "Top 20 Puzzles Commonly Asked During SDE Interviews"
},
{
"code": null,
"e": 23565,
"s": 23507,
"text": "Programming Language For Placement - C++, Java or Python?"
},
{
"code": null,
"e": 23623,
"s": 23565,
"text": "Print the longest path from root to leaf in a Binary tree"
},
{
"code": null,
"e": 23645,
"s": 23623,
"text": "Interview Preparation"
},
{
"code": null,
"e": 23664,
"s": 23645,
"text": "Problem on Numbers"
},
{
"code": null,
"e": 23676,
"s": 23664,
"text": "Percentages"
},
{
"code": null,
"e": 23720,
"s": 23676,
"text": "Puzzle | 50 red marbles and 50 blue marbles"
},
{
"code": null,
"e": 23751,
"s": 23720,
"text": "Codenation Recruitment Process"
},
{
"code": null,
"e": 23767,
"s": 23751,
"text": "Profit and Loss"
}
] |
PLSQL | TRUNC Function
|
01 Nov, 2019
The TRUNC function is an inbuilt function in PLSQL which is used to return a number truncated to a particular number of decimal places.
Syntax:
TRUNC( number, decimal_places )
Parameters Used:This function accepts two parameters which are illustrated below:-
number – This is the input number which is going to be truncated to a certain number.
decimal_places – This is also a input number which specifies that up to what number after decimal point should be the output of this function.
Return Value:This function returns a numeric value truncated to a particular number of decimal places.
Supported Versions of Oracle/PLSQL:
Oracle 12cOracle 11gOracle 10gOracle 9iOracle 8i
Oracle 12c
Oracle 11g
Oracle 10g
Oracle 9i
Oracle 8i
Let’s see some examples which illustrate the TRUNC function:
Example-1:
DECLARE
Test_Number number := 5.5;
BEGIN
dbms_output.put_line(TRUNC(Test_Number number));
END;
Output:
5
In the above example, the truncated value of 5.5 is 5
Example-2:
DECLARE
Test_Number number1 := 5;
Test_Number number2 := 0;
BEGIN
dbms_output.put_line(TRUNC(Test_Number number1,
Test_Number number2));
END;
Output:
5
In the above example, the truncated value of (5, 0) is 5 because 5 is not having any decimal point and hence it returns 5 as the output.
Example-3:
DECLARE
Test_Number number1 := 15.3123;
Test_Number number2 := 2;
BEGIN
dbms_output.put_line(TRUNC(Test_Number number1,
Test_Number number2));
END;
Output:
15.31
In the above example, the truncated value of 15.3123 is 15.31 because here 2 is at the place of decimal_place parameter and it shows that the output value must contain 2 decimal number after the decimal point.
Advantage:This function is used to return a number truncated to a particular number of decimal places.
SQL-PL/SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Nov, 2019"
},
{
"code": null,
"e": 164,
"s": 28,
"text": "The TRUNC function is an inbuilt function in PLSQL which is used to return a number truncated to a particular number of decimal places."
},
{
"code": null,
"e": 172,
"s": 164,
"text": "Syntax:"
},
{
"code": null,
"e": 204,
"s": 172,
"text": "TRUNC( number, decimal_places )"
},
{
"code": null,
"e": 287,
"s": 204,
"text": "Parameters Used:This function accepts two parameters which are illustrated below:-"
},
{
"code": null,
"e": 373,
"s": 287,
"text": "number – This is the input number which is going to be truncated to a certain number."
},
{
"code": null,
"e": 516,
"s": 373,
"text": "decimal_places – This is also a input number which specifies that up to what number after decimal point should be the output of this function."
},
{
"code": null,
"e": 619,
"s": 516,
"text": "Return Value:This function returns a numeric value truncated to a particular number of decimal places."
},
{
"code": null,
"e": 655,
"s": 619,
"text": "Supported Versions of Oracle/PLSQL:"
},
{
"code": null,
"e": 704,
"s": 655,
"text": "Oracle 12cOracle 11gOracle 10gOracle 9iOracle 8i"
},
{
"code": null,
"e": 715,
"s": 704,
"text": "Oracle 12c"
},
{
"code": null,
"e": 726,
"s": 715,
"text": "Oracle 11g"
},
{
"code": null,
"e": 737,
"s": 726,
"text": "Oracle 10g"
},
{
"code": null,
"e": 747,
"s": 737,
"text": "Oracle 9i"
},
{
"code": null,
"e": 757,
"s": 747,
"text": "Oracle 8i"
},
{
"code": null,
"e": 818,
"s": 757,
"text": "Let’s see some examples which illustrate the TRUNC function:"
},
{
"code": null,
"e": 829,
"s": 818,
"text": "Example-1:"
},
{
"code": null,
"e": 943,
"s": 829,
"text": "DECLARE \n Test_Number number := 5.5;\n \nBEGIN \n dbms_output.put_line(TRUNC(Test_Number number)); \n \nEND; "
},
{
"code": null,
"e": 951,
"s": 943,
"text": "Output:"
},
{
"code": null,
"e": 953,
"s": 951,
"text": "5"
},
{
"code": null,
"e": 1007,
"s": 953,
"text": "In the above example, the truncated value of 5.5 is 5"
},
{
"code": null,
"e": 1018,
"s": 1007,
"text": "Example-2:"
},
{
"code": null,
"e": 1213,
"s": 1018,
"text": "DECLARE \n Test_Number number1 := 5;\n Test_Number number2 := 0;\n \nBEGIN \n dbms_output.put_line(TRUNC(Test_Number number1, \n Test_Number number2)); \n \nEND; "
},
{
"code": null,
"e": 1221,
"s": 1213,
"text": "Output:"
},
{
"code": null,
"e": 1223,
"s": 1221,
"text": "5"
},
{
"code": null,
"e": 1360,
"s": 1223,
"text": "In the above example, the truncated value of (5, 0) is 5 because 5 is not having any decimal point and hence it returns 5 as the output."
},
{
"code": null,
"e": 1371,
"s": 1360,
"text": "Example-3:"
},
{
"code": null,
"e": 1572,
"s": 1371,
"text": "DECLARE \n Test_Number number1 := 15.3123;\n Test_Number number2 := 2;\n \nBEGIN \n dbms_output.put_line(TRUNC(Test_Number number1, \n Test_Number number2)); \n \nEND; "
},
{
"code": null,
"e": 1580,
"s": 1572,
"text": "Output:"
},
{
"code": null,
"e": 1586,
"s": 1580,
"text": "15.31"
},
{
"code": null,
"e": 1796,
"s": 1586,
"text": "In the above example, the truncated value of 15.3123 is 15.31 because here 2 is at the place of decimal_place parameter and it shows that the output value must contain 2 decimal number after the decimal point."
},
{
"code": null,
"e": 1899,
"s": 1796,
"text": "Advantage:This function is used to return a number truncated to a particular number of decimal places."
},
{
"code": null,
"e": 1910,
"s": 1899,
"text": "SQL-PL/SQL"
},
{
"code": null,
"e": 1914,
"s": 1910,
"text": "SQL"
},
{
"code": null,
"e": 1918,
"s": 1914,
"text": "SQL"
}
] |
Output of python program | Set 14 (Dictionary)
|
23 Jun, 2021
Prerequisite: Dictionary Note: Output of all these programs is tested on Python31) What is the output of the following program?
PYTHON3
D = dict()for x in enumerate(range(2)): D[x[0]] = x[1] D[x[1]+7] = x[0]print(D)
a) KeyError b) {0: 1, 7: 0, 1: 1, 8: 0} c) {0: 0, 7: 0, 1: 1, 8: 1} d) {1: 1, 7: 2, 0: 1, 8: 1} Ans. (c) Explanation: enumerate() will return a tuple, the loop will have x = (0, 0), (1, 1). Thus D[0] = 0, D[1] = 1, D[0 + 7] = D[7] = 0 and D[1 + 7] = D[8] = 1. Note: Dictionary is unordered, so the sequence of the key-value pair may differ in each output.2) What is the output of the following program?
PYTHON3
D = {1 : 1, 2 : '2', '1' : 2, '2' : 3}D['1'] = 2print(D[D[D[str(D[1])]]])
a) 2 b) 3 c) ‘2’ d) KeyError Ans. (b) Explanation: Simple key-value pair is used recursively, D[1] = 1, str(1) = ‘1’. So, D[str(D[1])] = D[‘1’] = 2, D[2] = ‘2’ and D[‘2’] = 3.3) What is the output of the following program?
PYTHON3
D = {1 : {'A' : {1 : "A"}, 2 : "B"}, 3 :"C", 'B' : "D", "D": 'E'}print(D[D[D[1][2]]], end = " ")print(D[D[1]["A"][2]])
a) D C b) E B c) D B d) E KeyError Ans. (d) Explanation: Key-Value Indexing is used in the example above. D[1] = {‘A’ : {1 : “A”}, 2 : “B”}, D[1][2] = “B”, D[D[1][2]] = D[“B”] = “D” and D[“D”] = “E”. D[1] = {‘A’ : {1 : “A”}, 2 : “B”}, D[1][“A”] = {1 : “A”} and D[1][“A”][2] doesn’t exists, thus KeyError.4) What is the output of the following program?
PYTHON3
D = dict()for i in range (3): for j in range(2): D[i] = jprint(D)
a) {0: 0, 1: 0, 2: 0} b) {0: 1, 1: 1, 2: 1} c) {0: 0, 1: 0, 2: 0, 0: 1, 1: 1, 2: 1} d) TypeError: Immutable object Ans. (b) Explanation: 1st loop will give 3 values to i 0, 1 and 2. In the empty dictionary, valued are added and overwrited in j loop, for eg. D[0] = [0] becomes D[0] = 1, due to overwriting.5) Which of the options below could possibly be the output of the following program?
PYTHON3
D = {1 : [1, 2, 3], 2: (4, 6, 8)}D[1].append(4)print(D[1], end = " ")L = [D[2]]L.append(10)D[2] = tuple(L)print(D[2])
a) [1, 2, 3, 4] [4, 6, 8, 10] b) [1, 2, 3, 4] ((4, 6, 8), 10) c) ‘[1, 2, 3, 4] TypeError: tuples are immutable d) [1, 2, 3, 4] (4, 6, 8, 10) Ans. (b) Explanation: In the first part key-value indexing is used and 4 is appended into the list. As tuples are immutable, in the second part the tuple is converted into a list, and value 10 is added finally to the new list ‘L’ then converted back to a tuple.This article is contributed by Piyush Doorwar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
kkvidyarthi98
Python-Output
Program Output
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n23 Jun, 2021"
},
{
"code": null,
"e": 184,
"s": 54,
"text": "Prerequisite: Dictionary Note: Output of all these programs is tested on Python31) What is the output of the following program? "
},
{
"code": null,
"e": 192,
"s": 184,
"text": "PYTHON3"
},
{
"code": "D = dict()for x in enumerate(range(2)): D[x[0]] = x[1] D[x[1]+7] = x[0]print(D)",
"e": 278,
"s": 192,
"text": null
},
{
"code": null,
"e": 683,
"s": 278,
"text": "a) KeyError b) {0: 1, 7: 0, 1: 1, 8: 0} c) {0: 0, 7: 0, 1: 1, 8: 1} d) {1: 1, 7: 2, 0: 1, 8: 1} Ans. (c) Explanation: enumerate() will return a tuple, the loop will have x = (0, 0), (1, 1). Thus D[0] = 0, D[1] = 1, D[0 + 7] = D[7] = 0 and D[1 + 7] = D[8] = 1. Note: Dictionary is unordered, so the sequence of the key-value pair may differ in each output.2) What is the output of the following program? "
},
{
"code": null,
"e": 691,
"s": 683,
"text": "PYTHON3"
},
{
"code": "D = {1 : 1, 2 : '2', '1' : 2, '2' : 3}D['1'] = 2print(D[D[D[str(D[1])]]])",
"e": 765,
"s": 691,
"text": null
},
{
"code": null,
"e": 990,
"s": 765,
"text": "a) 2 b) 3 c) ‘2’ d) KeyError Ans. (b) Explanation: Simple key-value pair is used recursively, D[1] = 1, str(1) = ‘1’. So, D[str(D[1])] = D[‘1’] = 2, D[2] = ‘2’ and D[‘2’] = 3.3) What is the output of the following program? "
},
{
"code": null,
"e": 998,
"s": 990,
"text": "PYTHON3"
},
{
"code": "D = {1 : {'A' : {1 : \"A\"}, 2 : \"B\"}, 3 :\"C\", 'B' : \"D\", \"D\": 'E'}print(D[D[D[1][2]]], end = \" \")print(D[D[1][\"A\"][2]])",
"e": 1117,
"s": 998,
"text": null
},
{
"code": null,
"e": 1471,
"s": 1117,
"text": "a) D C b) E B c) D B d) E KeyError Ans. (d) Explanation: Key-Value Indexing is used in the example above. D[1] = {‘A’ : {1 : “A”}, 2 : “B”}, D[1][2] = “B”, D[D[1][2]] = D[“B”] = “D” and D[“D”] = “E”. D[1] = {‘A’ : {1 : “A”}, 2 : “B”}, D[1][“A”] = {1 : “A”} and D[1][“A”][2] doesn’t exists, thus KeyError.4) What is the output of the following program? "
},
{
"code": null,
"e": 1479,
"s": 1471,
"text": "PYTHON3"
},
{
"code": "D = dict()for i in range (3): for j in range(2): D[i] = jprint(D)",
"e": 1555,
"s": 1479,
"text": null
},
{
"code": null,
"e": 1948,
"s": 1555,
"text": "a) {0: 0, 1: 0, 2: 0} b) {0: 1, 1: 1, 2: 1} c) {0: 0, 1: 0, 2: 0, 0: 1, 1: 1, 2: 1} d) TypeError: Immutable object Ans. (b) Explanation: 1st loop will give 3 values to i 0, 1 and 2. In the empty dictionary, valued are added and overwrited in j loop, for eg. D[0] = [0] becomes D[0] = 1, due to overwriting.5) Which of the options below could possibly be the output of the following program? "
},
{
"code": null,
"e": 1956,
"s": 1948,
"text": "PYTHON3"
},
{
"code": "D = {1 : [1, 2, 3], 2: (4, 6, 8)}D[1].append(4)print(D[1], end = \" \")L = [D[2]]L.append(10)D[2] = tuple(L)print(D[2])",
"e": 2074,
"s": 1956,
"text": null
},
{
"code": null,
"e": 2900,
"s": 2074,
"text": "a) [1, 2, 3, 4] [4, 6, 8, 10] b) [1, 2, 3, 4] ((4, 6, 8), 10) c) ‘[1, 2, 3, 4] TypeError: tuples are immutable d) [1, 2, 3, 4] (4, 6, 8, 10) Ans. (b) Explanation: In the first part key-value indexing is used and 4 is appended into the list. As tuples are immutable, in the second part the tuple is converted into a list, and value 10 is added finally to the new list ‘L’ then converted back to a tuple.This article is contributed by Piyush Doorwar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 2914,
"s": 2900,
"text": "kkvidyarthi98"
},
{
"code": null,
"e": 2928,
"s": 2914,
"text": "Python-Output"
},
{
"code": null,
"e": 2943,
"s": 2928,
"text": "Program Output"
}
] |
Contiguous unique substrings with the given length L
|
28 Dec, 2021
Given a string str and an integer L. The task is to print all the unique substring of length L from string str.
Examples:
Input: str = “abca”, L=3Output: “abc”, “bca”
Input: str = “aaaa”, L=3Output: “aaa”
Approach:Firstly generate all the substring of length L and then by using set we can insert unique sub-string till the length L and then print the result.
Below is the implementation of the above approach:
C++
Java
Python3
C#
// C++ implementation#include <bits/stdc++.h>using namespace std; // Function to print the// unique sub-string of length nvoid result(string s, int n){ // set to store the strings unordered_set<string> st; for (int i = 0; i < (int)s.size(); i++) { string ans = ""; for (int j = i; j < (int)s.size(); j++) { ans += s[j]; // if the size of the string // is equal to 1 then insert if (ans.size() == n) { // inserting unique // sub-string of length L st.insert(ans); break; } } } // Printing the set of strings for (auto it : st) cout << it << " ";} // Driver Codeint main(){ string s = "abca"; int n = 3; // Function calling result(s, n); return 0;}
// Java implementation of above approachimport java.util.*;class GFG { // Function to print the// unique sub-String of length nstatic void result(String s, int n){ // set to store the Strings HashSet<String> st = new HashSet<String>(); for (int i = 0; i < (int)s.length(); i++) { String ans = ""; for (int j = i; j < (int)s.length(); j++) { ans += s.charAt(j); // if the size of the String // is equal to 1 then insert if (ans.length()== n) { // inserting unique // sub-String of length L st.add(ans); break; } } } // Printing the set of Strings for (String it : st) System.out.print(it + " ");} // Driver Codepublic static void main(String[] args){ String s = "abca"; int n = 3; // Function calling result(s, n);}} // This code is contributed by 29AjayKumar
# Python3 implementation of the above approach # Function to print the # unique sub-string of length n def result(s, n) : # set to store the strings st = set(); for i in range(len(s)) : ans = ""; for j in range(i, len(s)) : ans += s[j]; # if the size of the string # is equal to 1 then insert if (len(ans) == n) : # inserting unique # sub-string of length L st.add(ans); break; # Printing the set of strings for it in st : print(it, end = " "); # Driver Code if __name__ == "__main__" : s = "abca"; n = 3; # Function calling result(s, n); # This code is contributed by AnkitRai01
// C# implementation for above approachusing System;using System.Collections.Generic; class GFG { // Function to print the// unique sub-String of length nstatic void result(String s, int n){ // set to store the Strings HashSet<String> st = new HashSet<String>(); for (int i = 0; i < s.Length; i++) { String ans = ""; for (int j = i; j < s.Length; j++) { ans += s[j]; // if the size of the String // is equal to 1 then insert if (ans.Length == n) { // inserting unique // sub-String of length L st.Add(ans); break; } } } // Printing the set of Strings foreach (String it in st) Console.Write(it + " ");} // Driver Codepublic static void Main(String[] args){ String s = "abca"; int n = 3; // Function calling result(s, n);}} // This code is contributed by 29AjayKumar
bca abc
29AjayKumar
ankthon
sumitgumber28
substring
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Dec, 2021"
},
{
"code": null,
"e": 140,
"s": 28,
"text": "Given a string str and an integer L. The task is to print all the unique substring of length L from string str."
},
{
"code": null,
"e": 150,
"s": 140,
"text": "Examples:"
},
{
"code": null,
"e": 195,
"s": 150,
"text": "Input: str = “abca”, L=3Output: “abc”, “bca”"
},
{
"code": null,
"e": 233,
"s": 195,
"text": "Input: str = “aaaa”, L=3Output: “aaa”"
},
{
"code": null,
"e": 388,
"s": 233,
"text": "Approach:Firstly generate all the substring of length L and then by using set we can insert unique sub-string till the length L and then print the result."
},
{
"code": null,
"e": 439,
"s": 388,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 443,
"s": 439,
"text": "C++"
},
{
"code": null,
"e": 448,
"s": 443,
"text": "Java"
},
{
"code": null,
"e": 456,
"s": 448,
"text": "Python3"
},
{
"code": null,
"e": 459,
"s": 456,
"text": "C#"
},
{
"code": "// C++ implementation#include <bits/stdc++.h>using namespace std; // Function to print the// unique sub-string of length nvoid result(string s, int n){ // set to store the strings unordered_set<string> st; for (int i = 0; i < (int)s.size(); i++) { string ans = \"\"; for (int j = i; j < (int)s.size(); j++) { ans += s[j]; // if the size of the string // is equal to 1 then insert if (ans.size() == n) { // inserting unique // sub-string of length L st.insert(ans); break; } } } // Printing the set of strings for (auto it : st) cout << it << \" \";} // Driver Codeint main(){ string s = \"abca\"; int n = 3; // Function calling result(s, n); return 0;}",
"e": 1298,
"s": 459,
"text": null
},
{
"code": "// Java implementation of above approachimport java.util.*;class GFG { // Function to print the// unique sub-String of length nstatic void result(String s, int n){ // set to store the Strings HashSet<String> st = new HashSet<String>(); for (int i = 0; i < (int)s.length(); i++) { String ans = \"\"; for (int j = i; j < (int)s.length(); j++) { ans += s.charAt(j); // if the size of the String // is equal to 1 then insert if (ans.length()== n) { // inserting unique // sub-String of length L st.add(ans); break; } } } // Printing the set of Strings for (String it : st) System.out.print(it + \" \");} // Driver Codepublic static void main(String[] args){ String s = \"abca\"; int n = 3; // Function calling result(s, n);}} // This code is contributed by 29AjayKumar",
"e": 2265,
"s": 1298,
"text": null
},
{
"code": "# Python3 implementation of the above approach # Function to print the # unique sub-string of length n def result(s, n) : # set to store the strings st = set(); for i in range(len(s)) : ans = \"\"; for j in range(i, len(s)) : ans += s[j]; # if the size of the string # is equal to 1 then insert if (len(ans) == n) : # inserting unique # sub-string of length L st.add(ans); break; # Printing the set of strings for it in st : print(it, end = \" \"); # Driver Code if __name__ == \"__main__\" : s = \"abca\"; n = 3; # Function calling result(s, n); # This code is contributed by AnkitRai01",
"e": 3038,
"s": 2265,
"text": null
},
{
"code": "// C# implementation for above approachusing System;using System.Collections.Generic; class GFG { // Function to print the// unique sub-String of length nstatic void result(String s, int n){ // set to store the Strings HashSet<String> st = new HashSet<String>(); for (int i = 0; i < s.Length; i++) { String ans = \"\"; for (int j = i; j < s.Length; j++) { ans += s[j]; // if the size of the String // is equal to 1 then insert if (ans.Length == n) { // inserting unique // sub-String of length L st.Add(ans); break; } } } // Printing the set of Strings foreach (String it in st) Console.Write(it + \" \");} // Driver Codepublic static void Main(String[] args){ String s = \"abca\"; int n = 3; // Function calling result(s, n);}} // This code is contributed by 29AjayKumar",
"e": 4018,
"s": 3038,
"text": null
},
{
"code": null,
"e": 4027,
"s": 4018,
"text": "bca abc\n"
},
{
"code": null,
"e": 4039,
"s": 4027,
"text": "29AjayKumar"
},
{
"code": null,
"e": 4047,
"s": 4039,
"text": "ankthon"
},
{
"code": null,
"e": 4061,
"s": 4047,
"text": "sumitgumber28"
},
{
"code": null,
"e": 4071,
"s": 4061,
"text": "substring"
},
{
"code": null,
"e": 4079,
"s": 4071,
"text": "Strings"
},
{
"code": null,
"e": 4087,
"s": 4079,
"text": "Strings"
}
] |
A Quickstart Guide to TensorBoard | by Rohan Jagtap | Towards Data Science
|
Everyone agrees that “visuals are better than text”. Visualizations offer feasibility and interactivity in any kind of interpretation. Same goes for ML modeling. One may wish to monitor the training losses or weights and biases to improve the model performance. This can be visualized using TensorBoard.
TensorBoard is TensorFlow’s visualization toolkit. It provides various functionalities to plot/display various aspects of a machine learning pipeline.
In this article, we will cover the basics of TensorBoard, and see how to visualize some of the essentials in various machine learning tasks.
First things first, we need to see how to import and launch TensorBoard using command line/notebook. We load the TensorBoard notebook extension using this magic command:
%load_ext tensorboard
Launch TensorBoard through the command line or within a notebook. In notebooks, use the %tensorboard line magic. On the command line, run the same command without "%".
%tensorboard --logdir <log_directory>
We will see what a log directory is and what significance it holds in the coming sections.
A model should be generic and must make accurate predictions on unseen data as well. For this, we monitor the losses and other metrics on validation (or dev) data and ensure that the losses don’t differ much. This can be done in a more insightful manner by visualizing these metrics over the training time.
Aforementioned is the TensorBoard’s interactive visualization of Train (orange) and Val (blue) losses and accuracies respectively (top to bottom). It can be clearly observed that the train and val losses have been decreasing over the course of training (horizontal axis is epochs), which gives an intuition that the model is achieving generalization as well as low bias. Read bias-variance tradeoff.
So, how do we do this?
When training a model using the keras API, we create a tensorboard callback which ensures that the metrics are logged in the specified directories.
When defining training loops manually, we need to log the losses manually. The tf.summary API facilitates this. First, we define a file writer for the specified log directories (separate for train and test), then with this file writer instance, we log the quantities as scalars after every epoch. Hence, we can observe trends in these metrics over the course of training, step by step.
In the previous section, while creating a tensorboard callback, we set the histogram_freq parameter to 1.
tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=log_dir, histogram_freq=1)
The Histograms and Distributions dashboards allow us to visualize the distribution of a tensor over time. Using these, we can monitor the weights, biases, activations, and more.
histogram_freq tells tensorflow to compute the distributions after every epoch. If it is set to 0, then it won’t plot any distributions.
Above is a Histogram plot of the distribution of weights of a dense (fully connected) layer from a model. To the left, is the offset view, while to the right, is the overlay view of the same distribution.
Observe that the distribution is similar to a normal distribution.
In the offset view, we have a 3-dimensional figure:
The horizontal axis corresponds to the values of the weights; basically the range of values taken by the weights of this layer. In this case, [-0.6 to 0.6].The vertical axis corresponds to the distribution. Intuitively, these values show the number of occurrences of the corresponding weight value in the layer, relative to other values. So for example, in the image above, we can see a spike of 685 at the value 0.0626, it superficially means that 685 inputs assume the value 0.0626.The depth axis is essentially the steps (or epochs). We can observe the changes in weight distribution over these steps.
The horizontal axis corresponds to the values of the weights; basically the range of values taken by the weights of this layer. In this case, [-0.6 to 0.6].
The vertical axis corresponds to the distribution. Intuitively, these values show the number of occurrences of the corresponding weight value in the layer, relative to other values. So for example, in the image above, we can see a spike of 685 at the value 0.0626, it superficially means that 685 inputs assume the value 0.0626.
The depth axis is essentially the steps (or epochs). We can observe the changes in weight distribution over these steps.
The overlay view is essentially a 2-dimensional representation of the same histogram. Here, the depth (epoch) axis is squeezed to get a direct comparison between the distributions. We can hover over the plots to have a particular step’s distribution highlighted.
There is another way of visualizing the distribution of weights over the epochs.
This is the Distributions tab of the tensorboard’s interactive toolkit.
The adjacent graph is essentially the plot between the depth and horizontal axis from the previous histogram.
The plot essentially depicts the changes in the range of the weight values of a layer over the epochs.
Using TensorBoard, along with the previously discussed default metrics, we can also log and visualize any custom metrics that we have used in our modeling. In this example, we will visualize the learning rate which would be adjusted by a custom learning rate scheduler.
We first define a custom learning rate schedule. Then we create a callback for it which ensures that the scheduler gets called while defining the learning rate for each epoch. We have logged the learning rate using the tf.summary API which we discussed in the previous sections.
It can be observed that there is a drop in the learning rate wherever we have defined so in our scheduler (See epochs 10, 20, and 50).
We can easily view a conceptual graph of our model’s structure and ensure it matches our intended design using the Graphs dashboard. This also is quite an insight into how TensorFlow construes the model.
Each expanded view shows an extra level of insight into the model’s computation workflow.
In the case of Keras models, no special effort is required except for creating a tensorboard callback to view the graphs dashboard.
However, in a situation where one may have to define a custom computation, the tf.function annotation transforms the python computation function into a TensorFlow graph. This graph can be traced and logged using the tf.summary trace API.
As mentioned in the docs, to use the Summary Trace API:
Use tf.summary.trace_on() immediately before your function call site.
Add profile information (memory, CPU time) to graph by passing profiler=True
With a Summary file writer, call tf.summary.trace_export() to save the log data
Plotting images is like plotting any other scalar value. However, to visualize matplotlib’s plots with TensorBoard, they need to be converted to images first. For this, we have a boilerplate code for converting a pyplot figure to an image:
Here, we take an example of plotting a visually vibing version of confusion matrix using tensorboard.
First, we add a LambdaCallback that would be called after every epoch, which computes the confusion matrix and logs it.
Then, we create a visual of the confusion matrix using pyplot.
This returns a pyplot figure which we convert to an image using the previously discussed boilerplate code.
Embeddings are essentially the representation of a very complex quantity in terms of vectors, wherein the values in the vectors have a notion of belonging with respect to other related quantities. We can use TensorBoard’s Embedding Projector to visualize high-dimensional embeddings. This can be useful for monitoring the keras Embedding layer.
We take an example of sequence classification task to classify imdb movie reviews as positive or negative. We build a simple model with an Embedding layer and a couple of fully connected layers.
For logging and visualizing, we first write the words from the vocabulary to a file.
Then, we checkpoint the trained embedding weights into a variable and then to a file.
Finally, we set up the projector config and project the embeddings:
We saw what TensorBoard is and explored some basic stuff in it. However, there are some special mentions I’d like to make, that I haven’t covered here.
Hyper-parameter TuningThe What-If ToolProfilingFairness Indicators (Beta)
Hyper-parameter Tuning
The What-If Tool
Profiling
Fairness Indicators (Beta)
You can check these out here if interested.
Here is the link to the complete code for the topics covered in this article, feel free to fork it.
The code used in this guide is referred from the following official TensorFlow Documentation:
|
[
{
"code": null,
"e": 476,
"s": 172,
"text": "Everyone agrees that “visuals are better than text”. Visualizations offer feasibility and interactivity in any kind of interpretation. Same goes for ML modeling. One may wish to monitor the training losses or weights and biases to improve the model performance. This can be visualized using TensorBoard."
},
{
"code": null,
"e": 627,
"s": 476,
"text": "TensorBoard is TensorFlow’s visualization toolkit. It provides various functionalities to plot/display various aspects of a machine learning pipeline."
},
{
"code": null,
"e": 768,
"s": 627,
"text": "In this article, we will cover the basics of TensorBoard, and see how to visualize some of the essentials in various machine learning tasks."
},
{
"code": null,
"e": 938,
"s": 768,
"text": "First things first, we need to see how to import and launch TensorBoard using command line/notebook. We load the TensorBoard notebook extension using this magic command:"
},
{
"code": null,
"e": 960,
"s": 938,
"text": "%load_ext tensorboard"
},
{
"code": null,
"e": 1128,
"s": 960,
"text": "Launch TensorBoard through the command line or within a notebook. In notebooks, use the %tensorboard line magic. On the command line, run the same command without \"%\"."
},
{
"code": null,
"e": 1166,
"s": 1128,
"text": "%tensorboard --logdir <log_directory>"
},
{
"code": null,
"e": 1257,
"s": 1166,
"text": "We will see what a log directory is and what significance it holds in the coming sections."
},
{
"code": null,
"e": 1564,
"s": 1257,
"text": "A model should be generic and must make accurate predictions on unseen data as well. For this, we monitor the losses and other metrics on validation (or dev) data and ensure that the losses don’t differ much. This can be done in a more insightful manner by visualizing these metrics over the training time."
},
{
"code": null,
"e": 1964,
"s": 1564,
"text": "Aforementioned is the TensorBoard’s interactive visualization of Train (orange) and Val (blue) losses and accuracies respectively (top to bottom). It can be clearly observed that the train and val losses have been decreasing over the course of training (horizontal axis is epochs), which gives an intuition that the model is achieving generalization as well as low bias. Read bias-variance tradeoff."
},
{
"code": null,
"e": 1987,
"s": 1964,
"text": "So, how do we do this?"
},
{
"code": null,
"e": 2135,
"s": 1987,
"text": "When training a model using the keras API, we create a tensorboard callback which ensures that the metrics are logged in the specified directories."
},
{
"code": null,
"e": 2521,
"s": 2135,
"text": "When defining training loops manually, we need to log the losses manually. The tf.summary API facilitates this. First, we define a file writer for the specified log directories (separate for train and test), then with this file writer instance, we log the quantities as scalars after every epoch. Hence, we can observe trends in these metrics over the course of training, step by step."
},
{
"code": null,
"e": 2627,
"s": 2521,
"text": "In the previous section, while creating a tensorboard callback, we set the histogram_freq parameter to 1."
},
{
"code": null,
"e": 2716,
"s": 2627,
"text": "tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=log_dir, histogram_freq=1)"
},
{
"code": null,
"e": 2894,
"s": 2716,
"text": "The Histograms and Distributions dashboards allow us to visualize the distribution of a tensor over time. Using these, we can monitor the weights, biases, activations, and more."
},
{
"code": null,
"e": 3031,
"s": 2894,
"text": "histogram_freq tells tensorflow to compute the distributions after every epoch. If it is set to 0, then it won’t plot any distributions."
},
{
"code": null,
"e": 3236,
"s": 3031,
"text": "Above is a Histogram plot of the distribution of weights of a dense (fully connected) layer from a model. To the left, is the offset view, while to the right, is the overlay view of the same distribution."
},
{
"code": null,
"e": 3303,
"s": 3236,
"text": "Observe that the distribution is similar to a normal distribution."
},
{
"code": null,
"e": 3355,
"s": 3303,
"text": "In the offset view, we have a 3-dimensional figure:"
},
{
"code": null,
"e": 3960,
"s": 3355,
"text": "The horizontal axis corresponds to the values of the weights; basically the range of values taken by the weights of this layer. In this case, [-0.6 to 0.6].The vertical axis corresponds to the distribution. Intuitively, these values show the number of occurrences of the corresponding weight value in the layer, relative to other values. So for example, in the image above, we can see a spike of 685 at the value 0.0626, it superficially means that 685 inputs assume the value 0.0626.The depth axis is essentially the steps (or epochs). We can observe the changes in weight distribution over these steps."
},
{
"code": null,
"e": 4117,
"s": 3960,
"text": "The horizontal axis corresponds to the values of the weights; basically the range of values taken by the weights of this layer. In this case, [-0.6 to 0.6]."
},
{
"code": null,
"e": 4446,
"s": 4117,
"text": "The vertical axis corresponds to the distribution. Intuitively, these values show the number of occurrences of the corresponding weight value in the layer, relative to other values. So for example, in the image above, we can see a spike of 685 at the value 0.0626, it superficially means that 685 inputs assume the value 0.0626."
},
{
"code": null,
"e": 4567,
"s": 4446,
"text": "The depth axis is essentially the steps (or epochs). We can observe the changes in weight distribution over these steps."
},
{
"code": null,
"e": 4830,
"s": 4567,
"text": "The overlay view is essentially a 2-dimensional representation of the same histogram. Here, the depth (epoch) axis is squeezed to get a direct comparison between the distributions. We can hover over the plots to have a particular step’s distribution highlighted."
},
{
"code": null,
"e": 4911,
"s": 4830,
"text": "There is another way of visualizing the distribution of weights over the epochs."
},
{
"code": null,
"e": 4983,
"s": 4911,
"text": "This is the Distributions tab of the tensorboard’s interactive toolkit."
},
{
"code": null,
"e": 5093,
"s": 4983,
"text": "The adjacent graph is essentially the plot between the depth and horizontal axis from the previous histogram."
},
{
"code": null,
"e": 5196,
"s": 5093,
"text": "The plot essentially depicts the changes in the range of the weight values of a layer over the epochs."
},
{
"code": null,
"e": 5466,
"s": 5196,
"text": "Using TensorBoard, along with the previously discussed default metrics, we can also log and visualize any custom metrics that we have used in our modeling. In this example, we will visualize the learning rate which would be adjusted by a custom learning rate scheduler."
},
{
"code": null,
"e": 5745,
"s": 5466,
"text": "We first define a custom learning rate schedule. Then we create a callback for it which ensures that the scheduler gets called while defining the learning rate for each epoch. We have logged the learning rate using the tf.summary API which we discussed in the previous sections."
},
{
"code": null,
"e": 5880,
"s": 5745,
"text": "It can be observed that there is a drop in the learning rate wherever we have defined so in our scheduler (See epochs 10, 20, and 50)."
},
{
"code": null,
"e": 6084,
"s": 5880,
"text": "We can easily view a conceptual graph of our model’s structure and ensure it matches our intended design using the Graphs dashboard. This also is quite an insight into how TensorFlow construes the model."
},
{
"code": null,
"e": 6174,
"s": 6084,
"text": "Each expanded view shows an extra level of insight into the model’s computation workflow."
},
{
"code": null,
"e": 6306,
"s": 6174,
"text": "In the case of Keras models, no special effort is required except for creating a tensorboard callback to view the graphs dashboard."
},
{
"code": null,
"e": 6544,
"s": 6306,
"text": "However, in a situation where one may have to define a custom computation, the tf.function annotation transforms the python computation function into a TensorFlow graph. This graph can be traced and logged using the tf.summary trace API."
},
{
"code": null,
"e": 6600,
"s": 6544,
"text": "As mentioned in the docs, to use the Summary Trace API:"
},
{
"code": null,
"e": 6670,
"s": 6600,
"text": "Use tf.summary.trace_on() immediately before your function call site."
},
{
"code": null,
"e": 6747,
"s": 6670,
"text": "Add profile information (memory, CPU time) to graph by passing profiler=True"
},
{
"code": null,
"e": 6827,
"s": 6747,
"text": "With a Summary file writer, call tf.summary.trace_export() to save the log data"
},
{
"code": null,
"e": 7067,
"s": 6827,
"text": "Plotting images is like plotting any other scalar value. However, to visualize matplotlib’s plots with TensorBoard, they need to be converted to images first. For this, we have a boilerplate code for converting a pyplot figure to an image:"
},
{
"code": null,
"e": 7169,
"s": 7067,
"text": "Here, we take an example of plotting a visually vibing version of confusion matrix using tensorboard."
},
{
"code": null,
"e": 7289,
"s": 7169,
"text": "First, we add a LambdaCallback that would be called after every epoch, which computes the confusion matrix and logs it."
},
{
"code": null,
"e": 7352,
"s": 7289,
"text": "Then, we create a visual of the confusion matrix using pyplot."
},
{
"code": null,
"e": 7459,
"s": 7352,
"text": "This returns a pyplot figure which we convert to an image using the previously discussed boilerplate code."
},
{
"code": null,
"e": 7804,
"s": 7459,
"text": "Embeddings are essentially the representation of a very complex quantity in terms of vectors, wherein the values in the vectors have a notion of belonging with respect to other related quantities. We can use TensorBoard’s Embedding Projector to visualize high-dimensional embeddings. This can be useful for monitoring the keras Embedding layer."
},
{
"code": null,
"e": 7999,
"s": 7804,
"text": "We take an example of sequence classification task to classify imdb movie reviews as positive or negative. We build a simple model with an Embedding layer and a couple of fully connected layers."
},
{
"code": null,
"e": 8084,
"s": 7999,
"text": "For logging and visualizing, we first write the words from the vocabulary to a file."
},
{
"code": null,
"e": 8170,
"s": 8084,
"text": "Then, we checkpoint the trained embedding weights into a variable and then to a file."
},
{
"code": null,
"e": 8238,
"s": 8170,
"text": "Finally, we set up the projector config and project the embeddings:"
},
{
"code": null,
"e": 8390,
"s": 8238,
"text": "We saw what TensorBoard is and explored some basic stuff in it. However, there are some special mentions I’d like to make, that I haven’t covered here."
},
{
"code": null,
"e": 8464,
"s": 8390,
"text": "Hyper-parameter TuningThe What-If ToolProfilingFairness Indicators (Beta)"
},
{
"code": null,
"e": 8487,
"s": 8464,
"text": "Hyper-parameter Tuning"
},
{
"code": null,
"e": 8504,
"s": 8487,
"text": "The What-If Tool"
},
{
"code": null,
"e": 8514,
"s": 8504,
"text": "Profiling"
},
{
"code": null,
"e": 8541,
"s": 8514,
"text": "Fairness Indicators (Beta)"
},
{
"code": null,
"e": 8585,
"s": 8541,
"text": "You can check these out here if interested."
},
{
"code": null,
"e": 8685,
"s": 8585,
"text": "Here is the link to the complete code for the topics covered in this article, feel free to fork it."
}
] |
Yii - Fields
|
By overriding fields() and extraFields() methods, you can define what data can be put into a response. The difference between these two methods is that the former defines the default set of fields, which should be included in the response while the latter defines additional fields, which may be included in the response if an end user requests for them via the expand query parameter.
Step 1 − Modify the MyUser model this way.
<?php
namespace app\models;
use app\components\UppercaseBehavior;
use Yii;
/**
* This is the model class for table "user".
*@property integer $id
* @property string $name
* @property string $email
*/
class MyUser extends \yii\db\ActiveRecord {
public function fields() {
return [
'id',
'name',
//PHP callback
'datetime' => function($model) {
return date("d:m:Y H:i:s");
}
];
}
/**
* @inheritdoc
*/
public static function tableName() {
return 'user';
}
/**
* @inheritdoc
*/
public function rules() {
return [
[['name', 'email'], 'string', 'max' => 255]
];
}
/**
* @inheritdoc
*/
public function attributeLabels() {
return [
'id' => 'ID',
'name' => 'Name',
'email' => 'Email',
];
}
}
?>
Besides default fields: id and name, we have added a custom field – datetime.
Step 2 − In Postman, run the URL http://localhost:8080/users.
Step 3 − Now, modify the MyUser model this way.
<?php
namespace app\models;
use app\components\UppercaseBehavior;
use Yii;
/**
* This is the model class for table "user".
*
* @property integer $id
* @property string $name
* @property string $email
*/
class MyUser extends \yii\db\ActiveRecord {
public function fields() {
return [
'id',
'name',
];
}
public function extraFields() {
return ['email'];
}
/**
* @inheritdoc
*/
public static function tableName() {
return 'user';
}
/**
* @inheritdoc
*/
public function rules() {
return [
[['name', 'email'], 'string', 'max' => 255]
];
}
/**
* @inheritdoc
*/
public function attributeLabels() {
return [
'id' => 'ID',
'name' => 'Name',
'email' => 'Email',
];
}
}
?>
Notice, that the email field is returned by the extraFields() method.
Step 4 − To get data with this field, run http://localhost:8080/users?expand=email.
The yii\rest\ActiveController class provides the following actions −
Index − Lists resources page by page
Index − Lists resources page by page
View − Returns the details of a specified resource
View − Returns the details of a specified resource
Create − Creates a new resource
Create − Creates a new resource
Update − Updates an existing resource
Update − Updates an existing resource
Delete − Deletes the specified resource
Delete − Deletes the specified resource
Options − Returns the supported HTTP methods
Options − Returns the supported HTTP methods
All above actions are declared in the actions method().
To disable the “delete” and “create” actions, modify the UserController this way −
<?php
namespace app\controllers;
use yii\rest\ActiveController;
class UserController extends ActiveController {
public $modelClass = 'app\models\MyUser';
public function actions() {
$actions = parent::actions();
// disable the "delete" and "create" actions
unset($actions['delete'], $actions['create']);
return $actions;
}
}
?>
When obtaining a RESTful API request, if there is an error in the request or something unexpected happens on the server, you may simply throw an exception. If you can identify the cause of the error, you should throw an exception along with a proper HTTP status code. Yii REST uses the following statuses −
200 − OK.
200 − OK.
201 − A resource was successfully created in response to a POST request. The Location header contains the URL pointing to the newly created resource.
201 − A resource was successfully created in response to a POST request. The Location header contains the URL pointing to the newly created resource.
204 − The request was handled successfully and the response contains no content.
204 − The request was handled successfully and the response contains no content.
304 − The resource was not modified.
304 − The resource was not modified.
400 − Bad request.
400 − Bad request.
401 − Authentication failed.
401 − Authentication failed.
403 − The authenticated user is not allowed to access the specified API endpoint.
403 − The authenticated user is not allowed to access the specified API endpoint.
404 − The resource does not exist.
404 − The resource does not exist.
405 − Method not allowed.
405 − Method not allowed.
415 − Unsupported media type.
415 − Unsupported media type.
422 − Data validation failed.
422 − Data validation failed.
429 − Too many requests.
429 − Too many requests.
500 − Internal server error.
500 − Internal server error.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3219,
"s": 2833,
"text": "By overriding fields() and extraFields() methods, you can define what data can be put into a response. The difference between these two methods is that the former defines the default set of fields, which should be included in the response while the latter defines additional fields, which may be included in the response if an end user requests for them via the expand query parameter."
},
{
"code": null,
"e": 3262,
"s": 3219,
"text": "Step 1 − Modify the MyUser model this way."
},
{
"code": null,
"e": 4268,
"s": 3262,
"text": "<?php\n namespace app\\models;\n use app\\components\\UppercaseBehavior;\n use Yii;\n /**\n * This is the model class for table \"user\".\n *@property integer $id\n * @property string $name\n * @property string $email\n */\n class MyUser extends \\yii\\db\\ActiveRecord {\n public function fields() {\n return [\n 'id',\n 'name',\n //PHP callback\n 'datetime' => function($model) {\n return date(\"d:m:Y H:i:s\");\n }\n ];\n }\n /**\n * @inheritdoc\n */\n public static function tableName() {\n return 'user';\n }\n /**\n * @inheritdoc\n */\n public function rules() {\n return [\n [['name', 'email'], 'string', 'max' => 255]\n ];\n }\n /**\n * @inheritdoc\n */\n public function attributeLabels() {\n return [\n 'id' => 'ID',\n 'name' => 'Name',\n 'email' => 'Email',\n ];\n }\n }\n?>"
},
{
"code": null,
"e": 4346,
"s": 4268,
"text": "Besides default fields: id and name, we have added a custom field – datetime."
},
{
"code": null,
"e": 4408,
"s": 4346,
"text": "Step 2 − In Postman, run the URL http://localhost:8080/users."
},
{
"code": null,
"e": 4456,
"s": 4408,
"text": "Step 3 − Now, modify the MyUser model this way."
},
{
"code": null,
"e": 5415,
"s": 4456,
"text": "<?php\n namespace app\\models;\n use app\\components\\UppercaseBehavior;\n use Yii;\n /**\n * This is the model class for table \"user\".\n *\n * @property integer $id\n * @property string $name\n * @property string $email\n */\n class MyUser extends \\yii\\db\\ActiveRecord {\n public function fields() {\n return [\n 'id',\n 'name',\n ];\n }\n public function extraFields() {\n return ['email'];\n }\n /**\n * @inheritdoc\n */\n public static function tableName() {\n return 'user';\n }\n /**\n * @inheritdoc\n */\n public function rules() { \n return [\n [['name', 'email'], 'string', 'max' => 255]\n ];\n }\n /**\n * @inheritdoc\n */\n public function attributeLabels() { \n return [\n 'id' => 'ID',\n 'name' => 'Name',\n 'email' => 'Email',\n ];\n }\n } \n?>"
},
{
"code": null,
"e": 5485,
"s": 5415,
"text": "Notice, that the email field is returned by the extraFields() method."
},
{
"code": null,
"e": 5569,
"s": 5485,
"text": "Step 4 − To get data with this field, run http://localhost:8080/users?expand=email."
},
{
"code": null,
"e": 5638,
"s": 5569,
"text": "The yii\\rest\\ActiveController class provides the following actions −"
},
{
"code": null,
"e": 5675,
"s": 5638,
"text": "Index − Lists resources page by page"
},
{
"code": null,
"e": 5712,
"s": 5675,
"text": "Index − Lists resources page by page"
},
{
"code": null,
"e": 5763,
"s": 5712,
"text": "View − Returns the details of a specified resource"
},
{
"code": null,
"e": 5814,
"s": 5763,
"text": "View − Returns the details of a specified resource"
},
{
"code": null,
"e": 5846,
"s": 5814,
"text": "Create − Creates a new resource"
},
{
"code": null,
"e": 5878,
"s": 5846,
"text": "Create − Creates a new resource"
},
{
"code": null,
"e": 5916,
"s": 5878,
"text": "Update − Updates an existing resource"
},
{
"code": null,
"e": 5954,
"s": 5916,
"text": "Update − Updates an existing resource"
},
{
"code": null,
"e": 5994,
"s": 5954,
"text": "Delete − Deletes the specified resource"
},
{
"code": null,
"e": 6034,
"s": 5994,
"text": "Delete − Deletes the specified resource"
},
{
"code": null,
"e": 6079,
"s": 6034,
"text": "Options − Returns the supported HTTP methods"
},
{
"code": null,
"e": 6124,
"s": 6079,
"text": "Options − Returns the supported HTTP methods"
},
{
"code": null,
"e": 6180,
"s": 6124,
"text": "All above actions are declared in the actions method()."
},
{
"code": null,
"e": 6263,
"s": 6180,
"text": "To disable the “delete” and “create” actions, modify the UserController this way −"
},
{
"code": null,
"e": 6657,
"s": 6263,
"text": "<?php\n namespace app\\controllers;\n use yii\\rest\\ActiveController;\n class UserController extends ActiveController {\n public $modelClass = 'app\\models\\MyUser';\n public function actions() {\n $actions = parent::actions();\n // disable the \"delete\" and \"create\" actions\n unset($actions['delete'], $actions['create']);\n return $actions;\n }\n }\n?>"
},
{
"code": null,
"e": 6964,
"s": 6657,
"text": "When obtaining a RESTful API request, if there is an error in the request or something unexpected happens on the server, you may simply throw an exception. If you can identify the cause of the error, you should throw an exception along with a proper HTTP status code. Yii REST uses the following statuses −"
},
{
"code": null,
"e": 6974,
"s": 6964,
"text": "200 − OK."
},
{
"code": null,
"e": 6984,
"s": 6974,
"text": "200 − OK."
},
{
"code": null,
"e": 7134,
"s": 6984,
"text": "201 − A resource was successfully created in response to a POST request. The Location header contains the URL pointing to the newly created resource."
},
{
"code": null,
"e": 7284,
"s": 7134,
"text": "201 − A resource was successfully created in response to a POST request. The Location header contains the URL pointing to the newly created resource."
},
{
"code": null,
"e": 7365,
"s": 7284,
"text": "204 − The request was handled successfully and the response contains no content."
},
{
"code": null,
"e": 7446,
"s": 7365,
"text": "204 − The request was handled successfully and the response contains no content."
},
{
"code": null,
"e": 7483,
"s": 7446,
"text": "304 − The resource was not modified."
},
{
"code": null,
"e": 7520,
"s": 7483,
"text": "304 − The resource was not modified."
},
{
"code": null,
"e": 7539,
"s": 7520,
"text": "400 − Bad request."
},
{
"code": null,
"e": 7558,
"s": 7539,
"text": "400 − Bad request."
},
{
"code": null,
"e": 7587,
"s": 7558,
"text": "401 − Authentication failed."
},
{
"code": null,
"e": 7616,
"s": 7587,
"text": "401 − Authentication failed."
},
{
"code": null,
"e": 7698,
"s": 7616,
"text": "403 − The authenticated user is not allowed to access the specified API endpoint."
},
{
"code": null,
"e": 7780,
"s": 7698,
"text": "403 − The authenticated user is not allowed to access the specified API endpoint."
},
{
"code": null,
"e": 7815,
"s": 7780,
"text": "404 − The resource does not exist."
},
{
"code": null,
"e": 7850,
"s": 7815,
"text": "404 − The resource does not exist."
},
{
"code": null,
"e": 7876,
"s": 7850,
"text": "405 − Method not allowed."
},
{
"code": null,
"e": 7902,
"s": 7876,
"text": "405 − Method not allowed."
},
{
"code": null,
"e": 7932,
"s": 7902,
"text": "415 − Unsupported media type."
},
{
"code": null,
"e": 7962,
"s": 7932,
"text": "415 − Unsupported media type."
},
{
"code": null,
"e": 7992,
"s": 7962,
"text": "422 − Data validation failed."
},
{
"code": null,
"e": 8022,
"s": 7992,
"text": "422 − Data validation failed."
},
{
"code": null,
"e": 8047,
"s": 8022,
"text": "429 − Too many requests."
},
{
"code": null,
"e": 8072,
"s": 8047,
"text": "429 − Too many requests."
},
{
"code": null,
"e": 8101,
"s": 8072,
"text": "500 − Internal server error."
},
{
"code": null,
"e": 8130,
"s": 8101,
"text": "500 − Internal server error."
},
{
"code": null,
"e": 8137,
"s": 8130,
"text": " Print"
},
{
"code": null,
"e": 8148,
"s": 8137,
"text": " Add Notes"
}
] |
Query Metabase data in Python. Metabase rest API and Python API | by Sophia Yang | Towards Data Science
|
Metabase is an open-source BI tool, where you can store data, connect to outside data sources, query, and visualizing data. This article talks about when we have data stored in Metabase, how do we query the data and get results in Python. The first part of this article talks about how to use the Metabase rest API to query data. The second part tries out a Python API. Let’s get started.
To use the Metabase rest API, we first need to get a session token. In the command line type the following:
The output will be your token. Then save this token in your Python script or Jupyter Notebooks.
token = "YOUR_TOKEN"
Alternatively, you can run the following in your Python script to get the token:
Query card
There are two ways to query Metabase data. The first option is to query data from a card, or a question you asked on the UI. In the UI, we can ask a question and query the data directly through the UI:
Once we have created the question, we can check if this question shows up in the api/card:
The output shows a list of dictionaries, each of which corresponds to a question user asked through the UI. Then we can find the ID number of the card and get the result of the card with the following code. This basically queries the database with the query you defined in the card (question).
Query database directly
Instead of defining the card first and querying the card, the second option is to query the database directly.
Let’s assume we want to query the table users from the database 1 and output all the rows that are created after 2020–10–15. Here we need to define this query in the SQL native query. And then added the query to the requests.post function. The resulting res.json() is a dictionary. To read in the data and the columns. We can get all the data from res.json()['data']['row'] , and then get the column names from res.json()['data']['results_metadata']['columns'] .
Now you should be able to see the results of your query in df.
I also tried out a Python API metabasepy. Similar to the Query card section we mentioned above, here we can query card 1 with the following code:
from metabasepy import Client, MetabaseTableParsercli = Client(username=username, password=password, base_url=endpoint)cli.authenticate()query_response = cli.cards.query(card_id="1")data_table = MetabaseTableParser.get_table(metabase_response=query_response)df = pd.DataFrame(data_table.__dict__['rows'])df
I feel like the Python API is less flexible. But you are certainly welcome to try it out.
Here I showed you three ways to query data from Metabase: query from the card using Metabase rest API, query directly from the database with a user-defined query using Metabase rest API, and query from the card using a Python API metabasepy.
I prefer querying directly from the database with a user-defined query using Metabase rest API. With this method, we can have all our queries in the Python script and we know exactly what we are querying.
There are also many other API calls available in Metabase we did not cover. The code in this article should be a good starting point for you to learn and explore other API functions. Hope you enjoy it! Thanks!
|
[
{
"code": null,
"e": 561,
"s": 172,
"text": "Metabase is an open-source BI tool, where you can store data, connect to outside data sources, query, and visualizing data. This article talks about when we have data stored in Metabase, how do we query the data and get results in Python. The first part of this article talks about how to use the Metabase rest API to query data. The second part tries out a Python API. Let’s get started."
},
{
"code": null,
"e": 669,
"s": 561,
"text": "To use the Metabase rest API, we first need to get a session token. In the command line type the following:"
},
{
"code": null,
"e": 765,
"s": 669,
"text": "The output will be your token. Then save this token in your Python script or Jupyter Notebooks."
},
{
"code": null,
"e": 786,
"s": 765,
"text": "token = \"YOUR_TOKEN\""
},
{
"code": null,
"e": 867,
"s": 786,
"text": "Alternatively, you can run the following in your Python script to get the token:"
},
{
"code": null,
"e": 878,
"s": 867,
"text": "Query card"
},
{
"code": null,
"e": 1080,
"s": 878,
"text": "There are two ways to query Metabase data. The first option is to query data from a card, or a question you asked on the UI. In the UI, we can ask a question and query the data directly through the UI:"
},
{
"code": null,
"e": 1171,
"s": 1080,
"text": "Once we have created the question, we can check if this question shows up in the api/card:"
},
{
"code": null,
"e": 1465,
"s": 1171,
"text": "The output shows a list of dictionaries, each of which corresponds to a question user asked through the UI. Then we can find the ID number of the card and get the result of the card with the following code. This basically queries the database with the query you defined in the card (question)."
},
{
"code": null,
"e": 1489,
"s": 1465,
"text": "Query database directly"
},
{
"code": null,
"e": 1600,
"s": 1489,
"text": "Instead of defining the card first and querying the card, the second option is to query the database directly."
},
{
"code": null,
"e": 2063,
"s": 1600,
"text": "Let’s assume we want to query the table users from the database 1 and output all the rows that are created after 2020–10–15. Here we need to define this query in the SQL native query. And then added the query to the requests.post function. The resulting res.json() is a dictionary. To read in the data and the columns. We can get all the data from res.json()['data']['row'] , and then get the column names from res.json()['data']['results_metadata']['columns'] ."
},
{
"code": null,
"e": 2126,
"s": 2063,
"text": "Now you should be able to see the results of your query in df."
},
{
"code": null,
"e": 2272,
"s": 2126,
"text": "I also tried out a Python API metabasepy. Similar to the Query card section we mentioned above, here we can query card 1 with the following code:"
},
{
"code": null,
"e": 2579,
"s": 2272,
"text": "from metabasepy import Client, MetabaseTableParsercli = Client(username=username, password=password, base_url=endpoint)cli.authenticate()query_response = cli.cards.query(card_id=\"1\")data_table = MetabaseTableParser.get_table(metabase_response=query_response)df = pd.DataFrame(data_table.__dict__['rows'])df"
},
{
"code": null,
"e": 2669,
"s": 2579,
"text": "I feel like the Python API is less flexible. But you are certainly welcome to try it out."
},
{
"code": null,
"e": 2911,
"s": 2669,
"text": "Here I showed you three ways to query data from Metabase: query from the card using Metabase rest API, query directly from the database with a user-defined query using Metabase rest API, and query from the card using a Python API metabasepy."
},
{
"code": null,
"e": 3116,
"s": 2911,
"text": "I prefer querying directly from the database with a user-defined query using Metabase rest API. With this method, we can have all our queries in the Python script and we know exactly what we are querying."
}
] |
How to convert JSON to CSV file using PowerShell?
|
To convert the JSON to the CSV format we need to first use the ConvertFrom-JSON command. For example, we have already JSON file present with us at the C:\temp\VMinfo.JSON location. We will first import this file and then convert it to CSV as shown below.
Get-Content C:\Temp\VMInfo.json | ConvertFrom-Json | Export-Csv C:\Temp\vminfo.csv -NoTypeInformation
Suppose you have cmdlet that produces output in the hash table format as shown below.
PS C:\> Get-AzVM -VMName TestMachine2k16 | Select -ExpandProperty Tags
Key Value
--- -----
For Ansible
Patching_Day Sunday
Application SecretTag
Owner Chirag
So we first need to convert the hash output to the JSON format and then from the JSON, we can save the output to excel.
PS C:\> Get-AzVM -VMName TestMachine2k16 | Select -ExpandProperty Tags | ConvertTo-Json | ConvertFrom-Json | Export-Csv C:\temp\Vmtags.csv -NoTypeIn
formation
|
[
{
"code": null,
"e": 1317,
"s": 1062,
"text": "To convert the JSON to the CSV format we need to first use the ConvertFrom-JSON command. For example, we have already JSON file present with us at the C:\\temp\\VMinfo.JSON location. We will first import this file and then convert it to CSV as shown below."
},
{
"code": null,
"e": 1419,
"s": 1317,
"text": "Get-Content C:\\Temp\\VMInfo.json | ConvertFrom-Json | Export-Csv C:\\Temp\\vminfo.csv -NoTypeInformation"
},
{
"code": null,
"e": 1505,
"s": 1419,
"text": "Suppose you have cmdlet that produces output in the hash table format as shown below."
},
{
"code": null,
"e": 1717,
"s": 1505,
"text": "PS C:\\> Get-AzVM -VMName TestMachine2k16 | Select -ExpandProperty Tags\n\nKey Value\n--- -----\nFor Ansible\nPatching_Day Sunday\nApplication SecretTag\nOwner Chirag"
},
{
"code": null,
"e": 1837,
"s": 1717,
"text": "So we first need to convert the hash output to the JSON format and then from the JSON, we can save the output to excel."
},
{
"code": null,
"e": 1996,
"s": 1837,
"text": "PS C:\\> Get-AzVM -VMName TestMachine2k16 | Select -ExpandProperty Tags | ConvertTo-Json | ConvertFrom-Json | Export-Csv C:\\temp\\Vmtags.csv -NoTypeIn\nformation"
}
] |
Software Testing and Machine Learning | by Scott Lindeman | Towards Data Science
|
Let’s face it, machine learning (ML) is becoming a standard part of many software systems. A trained model in your system may be surfacing predictions directly to users to help them make a human decision, or it may be making automatic decisions within the software system itself. Whether the ML in a system is developed in-house or is retrieved from a 3rd party’s pre-trained model API, if production software utilizing a trained model’s predictions is being used, it needs to be rigorously tested like you would any other aspect of your software. In this article, we will go over a rule-of-thumb framework on how to test your software when ML is involved, and identify what some common traps could be.
Author’s Note: Testing and change management in ML is a massive subject. This article is not intended to help evaluate how robust a model’s accuracy and performance is through testing, but to understand a model’s prediction interface and behavior. That said, you may find common model shortcomings and limitations through testing your software system in this manner.
Before we dig into how the introduction of ML changes systems, let’s quickly discuss the reasons for testing a software system. Testing helps developers ensure the behavior of a system is working as specified. Programs and software are constantly changing systems and if there are no automated tests that catch changes in behavior due to any number of reasons, systems are prone to errors, failures and bugs.
That said, what do we mean by testing? While there are many ways to unit test a piece of code, one common way to think about testing is through invariants. What universal truths about a function can we test?
def is_above_threshold(value): return value > THRESHOLD
Here is a very basic example of a function we can test. Three test cases that immediately come to mind are checking a number below THRESHOLD, a number above THRESHOLD and the THRESHOLD value itself.
def test_over_threshold(): assert is_above_threshold(THRESHOLD + 1)def test_under_threshold(): assert not is_above_threshold(THRESHOLD — 1)def test_threshold_edge(): assert not is_above_threshold(THRESHOLD)
Great. Now because this is Python, we may also want a few tests that try a few different input types. Do we accept floats, ints, numpy floats, infinity? Those examples should be fairly straightforward. The only time we should have to change these tests is if the invariant of the function changes. Say we change > to >=. That will cause one or more of these tests to fail because the invariant we were testing against changed.
However, we know that this isn’t all the testing that is needed for a software system. Systems are more than just one or two Python functions calling each other; they often consist of large interconnected layers of functions, which talk to other software systems over a network protocol. To handle that level of complexity, we need integration testing.
Like unit testing, different developers have different definitions of what exactly integration testing entails. For the purposes of this example, we want to test that our code works with another component of our system. This component could be reading from a database, or calling a rest API and getting information back. Here’s a simple example using our is_above_threshold function from earlier:
def make_decision(user_input): collected_value = component.get(user_input) if is_above_threshold(collected_value): return “Do it!” else: return “Don’t do it!”
What are the attributes of this function we want to test?
First and foremost, we want to make sure that we are using component.get’s interface correctly. We will need to provide enough different inputs to make_decision to exercise the various outputs of component.get, ensuring we haven’t missed any possible outcomes of its interface. Some examples of this:
Given the documentation, what values can be passed in as input? Just like our unit test example, try out edge cases to capture the behavior of non-normal situations.
Will component.get raise an error if given bad input? If so, do we handle that in this function or raise it to the caller of make_decision?
What if component.get sometimes returns a non-numeric value? In a more complex case, what if component.get returns a different data type depending on the input being passed in?
These are all valid tests we can perform because we are testing if our code is prepared for component.get’s interface, but not digging any deeper than we have to into the function’s implementation.
We also want to test that our code is working correctly. To do that, we can take a few shining examples of user_input and make sure we get the expected decision out at the end.
In most software systems, when we are using a library or component, we can expect that the component has gone through its own suite of invariant and integration testing. Therefore, we should only have to test the validity of the intersection.
What would cause these tests to change? If we updated the code in any way that altered the outcome for some of our shining examples of user_input, then we would have to update the tests to accommodate for the new behavior.
Now say we update the major version of the library component comes from and the interface has changed. The get function is no longer the method we want to use. We don’t want the behavior of our make_decision function to change. We can alter make_decision to accommodate the new API and, if we wrote the tests correctly, they should not have to change.
Now that we’ve gone through some testing basics, the real question is what is different when we add ML to our software system?
Right off the bat, let’s make it clear that many of the libraries used to build ML models are well tested. [1] However, using ML in your software system is usually not using those well tested library functions directly, but an artifact that was created from the library, your trained model.
When your code calls model.predict, you have assurances that all of the layers of methods and functions calling each other work at an invariant level, but you do not have any assurance that the library knows what the data you feed the model looks like. In our invariant testing example earlier, we spoke about testing for variable types like floats, ints, inf, etc. The same applies to testing a trained model, but the data types may be much more complex. For example, the number 3 is much simpler to test than a categorical feature that has 30 levels. So, does the three to eight tests we developed earlier for invariant testing hold up when we are talking about a much larger set of input data? Not quite.
A trained ML model is much more complex than our earlier example of comparing two numbers with the > sign. What invariants should we hold true when making predictions with a trained model artifact then? Let’s start with some basics:
The model’s predictions should be deterministic. That means when I pass in a single, compliant row of data for a prediction, I should get the same prediction back every time. Similarly, prediction consistency should hold true when making single row predictions and batch predictions. For example, the prediction for row 3 should be the same whether row 3 is alone or in batch with rows 1–10.Extending from a single compliant row, we should be able to reproduce the same error metric score on the same test data used to evaluate the model. Ignoring the fact whether the metric score is good or not, we want to be able to test that it doesn’t change.The model should make predictions under a certain amount of time. Some complex input data may cause a model to take longer to make a prediction than less complex inputs, but there should be an upper limit you can measure.
The model’s predictions should be deterministic. That means when I pass in a single, compliant row of data for a prediction, I should get the same prediction back every time. Similarly, prediction consistency should hold true when making single row predictions and batch predictions. For example, the prediction for row 3 should be the same whether row 3 is alone or in batch with rows 1–10.
Extending from a single compliant row, we should be able to reproduce the same error metric score on the same test data used to evaluate the model. Ignoring the fact whether the metric score is good or not, we want to be able to test that it doesn’t change.
The model should make predictions under a certain amount of time. Some complex input data may cause a model to take longer to make a prediction than less complex inputs, but there should be an upper limit you can measure.
Models make predictions, but they should be consistent about their predictions. Much like people, unless the model learns something new, it can only produce a result with currently known information. There is a time and place for online machine learning, but I will not be going in depth on this topic for this article.
In order to test consistency, we need our test cases to look at many more types of input data. Consider using the entire out-of-sample set of data that was used to evaluate the model. This is data that was not included when training the model, but has actual outcomes that you can compare against model predictions. To ensure the model is deterministic, we won’t be comparing the model’s predictions with actual outcomes, but with the original predictions this model made on the same set of data. If you make predictions on this data every time your tests run, whether as part of automation on merge requests or your integration pipelines, you will ensure that the model is producing consistent predictions.
Maybe you are worried your original out-of-sample data doesn’t cover enough of the potential inputs that could feed into your model. You can calculate the total number of rows needed to exhaustively test your model. Let’s look at a toy example:
Say your model was trained on five features with 1000 rows of data. Three of those features were categorical with 5, 10 and 30 levels respectively. The other two columns were numeric, with 500 unique values each. To calculate the total number of rows to exhaustively test the prediction behavior of your model on every combination of data, you would need to provide 5 * 10 * 30 * 500 * 500 = 375 million rows. This level of testing would tell you exactly how your model would behave in every possible situation, but only for the data the model has learned.
The exhaustive test above is impractical for the CI pipelines of a software system. If this model could make a single prediction in one tenth of a second, the test would still take more than ten thousand hours to complete. This is ignoring the hardware and infrastructure needed to load, predict and assert that large amount of data.
With the out-of-sample data and their outcomes, you have a good sample of data you can test your model on, as this was the criteria the model builders and evaluators used for evaluation purposes. It should be enough to catch invariant changes in the model. In this case, the tests should change to accommodate the invariant change. Do not forget to test “edge” cases such as null values and numeric data or categories that were not part of the training data for the model.
If a library or dependency upgrade in your system causes predictions to change, these tests will also fail. However as we mentioned earlier, generally library and dependency upgrades should not affect the external behavior of our system, so likely the model code will need to be altered in a way to ensure consistent predictions in this case. There are also many testing considerations around the storage format of trained models and their runtime environment. Some storage formats, like pickle, can cause runtime errors when trying to load the model into memory if the environment dependencies are updated. [2]
We’ve gone over some very basic invariants needed to test a software system that uses ML models. At the integration level, we luckily can keep some of the same concepts we had earlier. Let’s see what our make_decision function looks like if we replace component.get with model.predict:
def make_decision(user_input): prediction = model.predict(user_input) if is_above_threshold(prediction): return “Do it!” else: return “Don’t do it!”
The model.predict call functions analogously to component.get, taking in data from a user and producing a value we need to evaluate. To satisfy integration testing, you will similarly need to test that you are covering the model.predict interface correctly, catching or raising errors when necessary. If we know that a null feature in one value will cause predict to raise an error, test that case and have your function handle it accordingly. Again provide a few shining examples of input into the system.
We’ve reviewed some basic concerns you need to take into consideration when adding ML to your system. This initial suite of tests is a reasonable baseline, but there is much more you could do. [3]
For example, monitoring your model after it has been deployed. Production software systems do require monitoring to ensure they are working as intended. While our tests assert that the model’s behavior doesn’t change, we cannot test how the real world inputs to our model are changing and causing poor predictions to be made. This is an important step in model change management.
Testing the prediction interface and behavior of a model will ensure developers understand a model’s behavior and keep systems bug-resistant. ML models will be used more, so common best practices of how to test them will be critical for future software development.
[1] Not all libraries are perfect. You’ll eventually encounter bugs and find the limitations of a library’s interface. In these cases it is a good opportunity to find the repository, look through issues to see if others have found the bug, offer a minimal reproducible case and possibly suggest a fix.
[2] See documentation on pickling
[3] D. Sculley, Gary Holt, Daniel Golovin, Eugene Davydov, Todd Phillips, Dietmar Ebner, Vinay Chaudhary, Michael Young, Jean-Franc ̧ois Crespo, Dan Dennison, Hidden Technical Debt in Machine Learning Systems (2014), NIPS’15
|
[
{
"code": null,
"e": 875,
"s": 172,
"text": "Let’s face it, machine learning (ML) is becoming a standard part of many software systems. A trained model in your system may be surfacing predictions directly to users to help them make a human decision, or it may be making automatic decisions within the software system itself. Whether the ML in a system is developed in-house or is retrieved from a 3rd party’s pre-trained model API, if production software utilizing a trained model’s predictions is being used, it needs to be rigorously tested like you would any other aspect of your software. In this article, we will go over a rule-of-thumb framework on how to test your software when ML is involved, and identify what some common traps could be."
},
{
"code": null,
"e": 1242,
"s": 875,
"text": "Author’s Note: Testing and change management in ML is a massive subject. This article is not intended to help evaluate how robust a model’s accuracy and performance is through testing, but to understand a model’s prediction interface and behavior. That said, you may find common model shortcomings and limitations through testing your software system in this manner."
},
{
"code": null,
"e": 1651,
"s": 1242,
"text": "Before we dig into how the introduction of ML changes systems, let’s quickly discuss the reasons for testing a software system. Testing helps developers ensure the behavior of a system is working as specified. Programs and software are constantly changing systems and if there are no automated tests that catch changes in behavior due to any number of reasons, systems are prone to errors, failures and bugs."
},
{
"code": null,
"e": 1859,
"s": 1651,
"text": "That said, what do we mean by testing? While there are many ways to unit test a piece of code, one common way to think about testing is through invariants. What universal truths about a function can we test?"
},
{
"code": null,
"e": 1918,
"s": 1859,
"text": "def is_above_threshold(value): return value > THRESHOLD"
},
{
"code": null,
"e": 2117,
"s": 1918,
"text": "Here is a very basic example of a function we can test. Three test cases that immediately come to mind are checking a number below THRESHOLD, a number above THRESHOLD and the THRESHOLD value itself."
},
{
"code": null,
"e": 2333,
"s": 2117,
"text": "def test_over_threshold(): assert is_above_threshold(THRESHOLD + 1)def test_under_threshold(): assert not is_above_threshold(THRESHOLD — 1)def test_threshold_edge(): assert not is_above_threshold(THRESHOLD)"
},
{
"code": null,
"e": 2760,
"s": 2333,
"text": "Great. Now because this is Python, we may also want a few tests that try a few different input types. Do we accept floats, ints, numpy floats, infinity? Those examples should be fairly straightforward. The only time we should have to change these tests is if the invariant of the function changes. Say we change > to >=. That will cause one or more of these tests to fail because the invariant we were testing against changed."
},
{
"code": null,
"e": 3113,
"s": 2760,
"text": "However, we know that this isn’t all the testing that is needed for a software system. Systems are more than just one or two Python functions calling each other; they often consist of large interconnected layers of functions, which talk to other software systems over a network protocol. To handle that level of complexity, we need integration testing."
},
{
"code": null,
"e": 3510,
"s": 3113,
"text": "Like unit testing, different developers have different definitions of what exactly integration testing entails. For the purposes of this example, we want to test that our code works with another component of our system. This component could be reading from a database, or calling a rest API and getting information back. Here’s a simple example using our is_above_threshold function from earlier:"
},
{
"code": null,
"e": 3692,
"s": 3510,
"text": "def make_decision(user_input): collected_value = component.get(user_input) if is_above_threshold(collected_value): return “Do it!” else: return “Don’t do it!”"
},
{
"code": null,
"e": 3750,
"s": 3692,
"text": "What are the attributes of this function we want to test?"
},
{
"code": null,
"e": 4051,
"s": 3750,
"text": "First and foremost, we want to make sure that we are using component.get’s interface correctly. We will need to provide enough different inputs to make_decision to exercise the various outputs of component.get, ensuring we haven’t missed any possible outcomes of its interface. Some examples of this:"
},
{
"code": null,
"e": 4217,
"s": 4051,
"text": "Given the documentation, what values can be passed in as input? Just like our unit test example, try out edge cases to capture the behavior of non-normal situations."
},
{
"code": null,
"e": 4357,
"s": 4217,
"text": "Will component.get raise an error if given bad input? If so, do we handle that in this function or raise it to the caller of make_decision?"
},
{
"code": null,
"e": 4534,
"s": 4357,
"text": "What if component.get sometimes returns a non-numeric value? In a more complex case, what if component.get returns a different data type depending on the input being passed in?"
},
{
"code": null,
"e": 4732,
"s": 4534,
"text": "These are all valid tests we can perform because we are testing if our code is prepared for component.get’s interface, but not digging any deeper than we have to into the function’s implementation."
},
{
"code": null,
"e": 4909,
"s": 4732,
"text": "We also want to test that our code is working correctly. To do that, we can take a few shining examples of user_input and make sure we get the expected decision out at the end."
},
{
"code": null,
"e": 5152,
"s": 4909,
"text": "In most software systems, when we are using a library or component, we can expect that the component has gone through its own suite of invariant and integration testing. Therefore, we should only have to test the validity of the intersection."
},
{
"code": null,
"e": 5375,
"s": 5152,
"text": "What would cause these tests to change? If we updated the code in any way that altered the outcome for some of our shining examples of user_input, then we would have to update the tests to accommodate for the new behavior."
},
{
"code": null,
"e": 5727,
"s": 5375,
"text": "Now say we update the major version of the library component comes from and the interface has changed. The get function is no longer the method we want to use. We don’t want the behavior of our make_decision function to change. We can alter make_decision to accommodate the new API and, if we wrote the tests correctly, they should not have to change."
},
{
"code": null,
"e": 5854,
"s": 5727,
"text": "Now that we’ve gone through some testing basics, the real question is what is different when we add ML to our software system?"
},
{
"code": null,
"e": 6145,
"s": 5854,
"text": "Right off the bat, let’s make it clear that many of the libraries used to build ML models are well tested. [1] However, using ML in your software system is usually not using those well tested library functions directly, but an artifact that was created from the library, your trained model."
},
{
"code": null,
"e": 6853,
"s": 6145,
"text": "When your code calls model.predict, you have assurances that all of the layers of methods and functions calling each other work at an invariant level, but you do not have any assurance that the library knows what the data you feed the model looks like. In our invariant testing example earlier, we spoke about testing for variable types like floats, ints, inf, etc. The same applies to testing a trained model, but the data types may be much more complex. For example, the number 3 is much simpler to test than a categorical feature that has 30 levels. So, does the three to eight tests we developed earlier for invariant testing hold up when we are talking about a much larger set of input data? Not quite."
},
{
"code": null,
"e": 7086,
"s": 6853,
"text": "A trained ML model is much more complex than our earlier example of comparing two numbers with the > sign. What invariants should we hold true when making predictions with a trained model artifact then? Let’s start with some basics:"
},
{
"code": null,
"e": 7956,
"s": 7086,
"text": "The model’s predictions should be deterministic. That means when I pass in a single, compliant row of data for a prediction, I should get the same prediction back every time. Similarly, prediction consistency should hold true when making single row predictions and batch predictions. For example, the prediction for row 3 should be the same whether row 3 is alone or in batch with rows 1–10.Extending from a single compliant row, we should be able to reproduce the same error metric score on the same test data used to evaluate the model. Ignoring the fact whether the metric score is good or not, we want to be able to test that it doesn’t change.The model should make predictions under a certain amount of time. Some complex input data may cause a model to take longer to make a prediction than less complex inputs, but there should be an upper limit you can measure."
},
{
"code": null,
"e": 8348,
"s": 7956,
"text": "The model’s predictions should be deterministic. That means when I pass in a single, compliant row of data for a prediction, I should get the same prediction back every time. Similarly, prediction consistency should hold true when making single row predictions and batch predictions. For example, the prediction for row 3 should be the same whether row 3 is alone or in batch with rows 1–10."
},
{
"code": null,
"e": 8606,
"s": 8348,
"text": "Extending from a single compliant row, we should be able to reproduce the same error metric score on the same test data used to evaluate the model. Ignoring the fact whether the metric score is good or not, we want to be able to test that it doesn’t change."
},
{
"code": null,
"e": 8828,
"s": 8606,
"text": "The model should make predictions under a certain amount of time. Some complex input data may cause a model to take longer to make a prediction than less complex inputs, but there should be an upper limit you can measure."
},
{
"code": null,
"e": 9148,
"s": 8828,
"text": "Models make predictions, but they should be consistent about their predictions. Much like people, unless the model learns something new, it can only produce a result with currently known information. There is a time and place for online machine learning, but I will not be going in depth on this topic for this article."
},
{
"code": null,
"e": 9856,
"s": 9148,
"text": "In order to test consistency, we need our test cases to look at many more types of input data. Consider using the entire out-of-sample set of data that was used to evaluate the model. This is data that was not included when training the model, but has actual outcomes that you can compare against model predictions. To ensure the model is deterministic, we won’t be comparing the model’s predictions with actual outcomes, but with the original predictions this model made on the same set of data. If you make predictions on this data every time your tests run, whether as part of automation on merge requests or your integration pipelines, you will ensure that the model is producing consistent predictions."
},
{
"code": null,
"e": 10101,
"s": 9856,
"text": "Maybe you are worried your original out-of-sample data doesn’t cover enough of the potential inputs that could feed into your model. You can calculate the total number of rows needed to exhaustively test your model. Let’s look at a toy example:"
},
{
"code": null,
"e": 10658,
"s": 10101,
"text": "Say your model was trained on five features with 1000 rows of data. Three of those features were categorical with 5, 10 and 30 levels respectively. The other two columns were numeric, with 500 unique values each. To calculate the total number of rows to exhaustively test the prediction behavior of your model on every combination of data, you would need to provide 5 * 10 * 30 * 500 * 500 = 375 million rows. This level of testing would tell you exactly how your model would behave in every possible situation, but only for the data the model has learned."
},
{
"code": null,
"e": 10992,
"s": 10658,
"text": "The exhaustive test above is impractical for the CI pipelines of a software system. If this model could make a single prediction in one tenth of a second, the test would still take more than ten thousand hours to complete. This is ignoring the hardware and infrastructure needed to load, predict and assert that large amount of data."
},
{
"code": null,
"e": 11465,
"s": 10992,
"text": "With the out-of-sample data and their outcomes, you have a good sample of data you can test your model on, as this was the criteria the model builders and evaluators used for evaluation purposes. It should be enough to catch invariant changes in the model. In this case, the tests should change to accommodate the invariant change. Do not forget to test “edge” cases such as null values and numeric data or categories that were not part of the training data for the model."
},
{
"code": null,
"e": 12077,
"s": 11465,
"text": "If a library or dependency upgrade in your system causes predictions to change, these tests will also fail. However as we mentioned earlier, generally library and dependency upgrades should not affect the external behavior of our system, so likely the model code will need to be altered in a way to ensure consistent predictions in this case. There are also many testing considerations around the storage format of trained models and their runtime environment. Some storage formats, like pickle, can cause runtime errors when trying to load the model into memory if the environment dependencies are updated. [2]"
},
{
"code": null,
"e": 12363,
"s": 12077,
"text": "We’ve gone over some very basic invariants needed to test a software system that uses ML models. At the integration level, we luckily can keep some of the same concepts we had earlier. Let’s see what our make_decision function looks like if we replace component.get with model.predict:"
},
{
"code": null,
"e": 12535,
"s": 12363,
"text": "def make_decision(user_input): prediction = model.predict(user_input) if is_above_threshold(prediction): return “Do it!” else: return “Don’t do it!”"
},
{
"code": null,
"e": 13042,
"s": 12535,
"text": "The model.predict call functions analogously to component.get, taking in data from a user and producing a value we need to evaluate. To satisfy integration testing, you will similarly need to test that you are covering the model.predict interface correctly, catching or raising errors when necessary. If we know that a null feature in one value will cause predict to raise an error, test that case and have your function handle it accordingly. Again provide a few shining examples of input into the system."
},
{
"code": null,
"e": 13239,
"s": 13042,
"text": "We’ve reviewed some basic concerns you need to take into consideration when adding ML to your system. This initial suite of tests is a reasonable baseline, but there is much more you could do. [3]"
},
{
"code": null,
"e": 13619,
"s": 13239,
"text": "For example, monitoring your model after it has been deployed. Production software systems do require monitoring to ensure they are working as intended. While our tests assert that the model’s behavior doesn’t change, we cannot test how the real world inputs to our model are changing and causing poor predictions to be made. This is an important step in model change management."
},
{
"code": null,
"e": 13885,
"s": 13619,
"text": "Testing the prediction interface and behavior of a model will ensure developers understand a model’s behavior and keep systems bug-resistant. ML models will be used more, so common best practices of how to test them will be critical for future software development."
},
{
"code": null,
"e": 14187,
"s": 13885,
"text": "[1] Not all libraries are perfect. You’ll eventually encounter bugs and find the limitations of a library’s interface. In these cases it is a good opportunity to find the repository, look through issues to see if others have found the bug, offer a minimal reproducible case and possibly suggest a fix."
},
{
"code": null,
"e": 14221,
"s": 14187,
"text": "[2] See documentation on pickling"
}
] |
Tryit Editor v3.7
|
Table Colspan & Rowspan
Tryit: HTML table - rowspan
|
[
{
"code": null,
"e": 46,
"s": 22,
"text": "Table Colspan & Rowspan"
}
] |
How to validate expiry date on a MySQL query?
|
You can use NOW() for this. Following is the syntax −
select * from yourTableName
where yourColumnName> now();
Let us first create a table −
mysql> create table DemoTable
(
Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
expiryDateOfMedicine datetime
);
Query OK, 0 rows affected (0.55 sec)
Insert records in the table using insert command −
mysql> insert into DemoTable(expiryDateOfMedicine) values('2019-04-27 11:29:00');
Query OK, 1 row affected (0.36 sec)
mysql> insert into DemoTable(expiryDateOfMedicine) values('2019-04-26 10:39:21');
Query OK, 1 row affected (0.41 sec)
mysql> insert into DemoTable(expiryDateOfMedicine) values('2019-04-28 11:30:10');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable(expiryDateOfMedicine) values('2019-04-29 12:44:11');
Query OK, 1 row affected (0.18 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable;
This will produce the following output −
+----+----------------------+
| Id | expiryDateOfMedicine |
+----+----------------------+
| 1 | 2019-04-27 11:29:00 |
| 2 | 2019-04-26 10:39:21 |
| 3 | 2019-04-28 11:30:10 |
| 4 | 2019-04-29 12:44:11 |
+----+----------------------+
4 rows in set (0.00 sec)
Following is the query to validate expiry date on a MySQL query −
mysql> select * from DemoTable
where expiryDateOfMedicine > now();
This will produce the following output −
+----+----------------------+
| Id | expiryDateOfMedicine |
+----+----------------------+
| 3 | 2019-04-28 11:30:10 |
| 4 | 2019-04-29 12:44:11 |
+----+----------------------+
2 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1116,
"s": 1062,
"text": "You can use NOW() for this. Following is the syntax −"
},
{
"code": null,
"e": 1173,
"s": 1116,
"text": "select * from yourTableName\nwhere yourColumnName> now();"
},
{
"code": null,
"e": 1203,
"s": 1173,
"text": "Let us first create a table −"
},
{
"code": null,
"e": 1361,
"s": 1203,
"text": "mysql> create table DemoTable\n (\n Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n expiryDateOfMedicine datetime\n );\nQuery OK, 0 rows affected (0.55 sec)"
},
{
"code": null,
"e": 1412,
"s": 1361,
"text": "Insert records in the table using insert command −"
},
{
"code": null,
"e": 1884,
"s": 1412,
"text": "mysql> insert into DemoTable(expiryDateOfMedicine) values('2019-04-27 11:29:00');\nQuery OK, 1 row affected (0.36 sec)\nmysql> insert into DemoTable(expiryDateOfMedicine) values('2019-04-26 10:39:21');\nQuery OK, 1 row affected (0.41 sec)\nmysql> insert into DemoTable(expiryDateOfMedicine) values('2019-04-28 11:30:10');\nQuery OK, 1 row affected (0.18 sec)\nmysql> insert into DemoTable(expiryDateOfMedicine) values('2019-04-29 12:44:11');\nQuery OK, 1 row affected (0.18 sec)"
},
{
"code": null,
"e": 1944,
"s": 1884,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1976,
"s": 1944,
"text": "mysql> select * from DemoTable;"
},
{
"code": null,
"e": 2017,
"s": 1976,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2282,
"s": 2017,
"text": "+----+----------------------+\n| Id | expiryDateOfMedicine |\n+----+----------------------+\n| 1 | 2019-04-27 11:29:00 |\n| 2 | 2019-04-26 10:39:21 |\n| 3 | 2019-04-28 11:30:10 |\n| 4 | 2019-04-29 12:44:11 |\n+----+----------------------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2348,
"s": 2282,
"text": "Following is the query to validate expiry date on a MySQL query −"
},
{
"code": null,
"e": 2415,
"s": 2348,
"text": "mysql> select * from DemoTable\nwhere expiryDateOfMedicine > now();"
},
{
"code": null,
"e": 2456,
"s": 2415,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2661,
"s": 2456,
"text": "+----+----------------------+\n| Id | expiryDateOfMedicine |\n+----+----------------------+\n| 3 | 2019-04-28 11:30:10 |\n| 4 | 2019-04-29 12:44:11 |\n+----+----------------------+\n2 rows in set (0.00 sec)"
}
] |
How to switch different browser tabs using Python Selenium?
|
We can switch different browser tabs using Selenium webdriver in Python using the method switch_to.window. By default, the webdriver has access to the parent window.
Once another browser tab is opened, the switch_to.window helps to switch the webdriver focus to the tab. The window handle of the browser window where we want to shift is passed as a parameter to that method.
The method window_handles contains the list of all window handle ids of the opened browsers. The method current_window_handle is used to hold the window handle id of the browser window in focus.
p = driver.current_window_handle
parent = driver.window_handles[0]
chld = driver.window_handles[1]
driver.switch_to.window(chld)
Let us make an attempt to access the below browser tabs −
from selenium import webdriver
#set chromodriver.exe path
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
driver.implicitly_wait(0.5)
#launch URL
driver.get("https://the-internet.herokuapp.com/windows")
#identify element
l = driver.find_element_by_link_text("Click Here")
l.click()
#obtain window handle of browser in focus
p = driver.current_window_handle
#obtain parent window handle
parent = driver.window_handles[0]
#obtain browser tab window
chld = driver.window_handles[1]
#switch to browser tab
driver.switch_to.window(chld)
print("Page title for browser tab:")
print(driver.title)
#close browser tab window
driver.close()
#switch to parent window
driver.switch_to.window(parent)
print("Page title for parent window:")
print(driver.title)
#close browser parent window
driver.close()
|
[
{
"code": null,
"e": 1228,
"s": 1062,
"text": "We can switch different browser tabs using Selenium webdriver in Python using the method switch_to.window. By default, the webdriver has access to the parent window."
},
{
"code": null,
"e": 1437,
"s": 1228,
"text": "Once another browser tab is opened, the switch_to.window helps to switch the webdriver focus to the tab. The window handle of the browser window where we want to shift is passed as a parameter to that method."
},
{
"code": null,
"e": 1632,
"s": 1437,
"text": "The method window_handles contains the list of all window handle ids of the opened browsers. The method current_window_handle is used to hold the window handle id of the browser window in focus."
},
{
"code": null,
"e": 1761,
"s": 1632,
"text": "p = driver.current_window_handle\nparent = driver.window_handles[0]\nchld = driver.window_handles[1]\ndriver.switch_to.window(chld)"
},
{
"code": null,
"e": 1819,
"s": 1761,
"text": "Let us make an attempt to access the below browser tabs −"
},
{
"code": null,
"e": 2627,
"s": 1819,
"text": "from selenium import webdriver\n#set chromodriver.exe path\ndriver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\")\ndriver.implicitly_wait(0.5)\n#launch URL\ndriver.get(\"https://the-internet.herokuapp.com/windows\")\n#identify element\nl = driver.find_element_by_link_text(\"Click Here\")\nl.click()\n#obtain window handle of browser in focus\np = driver.current_window_handle\n#obtain parent window handle\nparent = driver.window_handles[0]\n#obtain browser tab window\nchld = driver.window_handles[1]\n#switch to browser tab\ndriver.switch_to.window(chld)\nprint(\"Page title for browser tab:\")\nprint(driver.title)\n#close browser tab window\ndriver.close()\n#switch to parent window\ndriver.switch_to.window(parent)\nprint(\"Page title for parent window:\")\nprint(driver.title)\n#close browser parent window\ndriver.close()"
}
] |
React-Bootstrap Tabs Component - GeeksforGeeks
|
24 Sep, 2021
React-Bootstrap is a front-end framework that was designed keeping react in mind. Tabs Component provides a way to make form dynamic tabbed interfaces. With the help of tabs, the user can switch between components present in given different tabs. We can use the following approach in ReactJS to use the react-bootstrap tabs Component.
Tabs Props:
activeKey: It is used to mark the tab as active based on the matching event key.
defaultActiveKey: It is used to indicate the default active key that is selected on start.
id: It is the HTML id attribute required when no generateChildId prop is specified.
mountOnEnter: It is used to mount tabs.
onSelect: It is a callback function that is triggered when a tab is selected.
transition: For all children <TabPane>, it is used to set a default animation strategy.
unmountOnExit: It is used to unmount the tabs.
variant: It is used to define the navigation style.
Tab Props:
disabled: It is used to disable the component.
eventKey: It is basically a unique identifier for the component.
tabClassName: It is used to add the class name for the tab styling.
title: It is used to indicate the title for the tab component.
TabContainer Props:
activeKey: It is used for the eventKey of the current tab which is active.
defaultActiveKey: It is used for the default eventKey for the tab.
generateChildId: It is a function that is used to generate the unique id for child tab <TabPane>s and <NavItem>s on the basis of eventKey and type which is passed as a parameter to this function.
id: It is the normal HTML id attribute for identification.
mountOnEnter: It is used to wait until first “enter” transition to mount the tab.
onSelect: It is a callback that is triggered when a tab is selected.
transition: For all children, it is used to set a default animation strategy.
unmountOnExit: It is used to unmount the tab.
TabContent Props:
as: It can be used as a custom element type for this component.
bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS.
TabPane Props:
active: It is used to toggle the active state of the TabPane.
aria-labelledby: It is used to pass the aria labeled attribute to TabPane.
as: It can be used as a custom element type for this component.
eventKey: It is used a key that associates TabPane with help of its controlling NavLink
id: It is the normal HTML id attribute for identification.
mountOnEnter: It is used to wait until first “enter” transition to mount the tab.
onEnter: When animation is not false, it is used to transition the OnEnter callback.
onEntered: When animation is not false, it is used to transition the OnEntered callback.
onEntering: When animation is not false, it is used to transition the OnEntering callback.
onExit: When animation is not false, it is used to transition the OnExit callback.
onExited: When animation is not false, it is used to transition the OnExited callback.
onExiting: When animation is not false, it is used to transition the OnExiting callback.
transition: It is used to show the animation when hiding or showing the <TabPane>s
unmountOnExit: It is used to unmount the tab.
bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:npx create-react-app foldername
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the required module using the following command:npm install react-bootstrap
npm install bootstrap
Step 3: After creating the ReactJS application, Install the required module using the following command:
npm install react-bootstrap
npm install bootstrap
Project Structure: It will look like the following.
Project Structure
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from 'react';import 'bootstrap/dist/css/bootstrap.css';import Tabs from 'react-bootstrap/Tabs';import Tab from 'react-bootstrap/Tab'; export default function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>React-Bootstrap Tab Component</h4> <Tabs defaultActiveKey="second"> <Tab eventKey="first" title="Dashboard"> Hii, I am 1st tab content </Tab> <Tab eventKey="second" title="Setting"> Hii, I am 2nd tab content </Tab> <Tab eventKey="third" title="Aboutus"> Hii, I am 3rd tab content </Tab> </Tabs> </div> );}
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://react-bootstrap.github.io/components/tabs/
anikakapoor
React-Bootstrap
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to pass data from one component to other component in ReactJS ?
React-Router Hooks
Re-rendering Components in ReactJS
How to set background images in ReactJS ?
How to create a table in ReactJS ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Convert a string to an integer in JavaScript
|
[
{
"code": null,
"e": 24274,
"s": 24246,
"text": "\n24 Sep, 2021"
},
{
"code": null,
"e": 24609,
"s": 24274,
"text": "React-Bootstrap is a front-end framework that was designed keeping react in mind. Tabs Component provides a way to make form dynamic tabbed interfaces. With the help of tabs, the user can switch between components present in given different tabs. We can use the following approach in ReactJS to use the react-bootstrap tabs Component."
},
{
"code": null,
"e": 24621,
"s": 24609,
"text": "Tabs Props:"
},
{
"code": null,
"e": 24702,
"s": 24621,
"text": "activeKey: It is used to mark the tab as active based on the matching event key."
},
{
"code": null,
"e": 24793,
"s": 24702,
"text": "defaultActiveKey: It is used to indicate the default active key that is selected on start."
},
{
"code": null,
"e": 24877,
"s": 24793,
"text": "id: It is the HTML id attribute required when no generateChildId prop is specified."
},
{
"code": null,
"e": 24917,
"s": 24877,
"text": "mountOnEnter: It is used to mount tabs."
},
{
"code": null,
"e": 24995,
"s": 24917,
"text": "onSelect: It is a callback function that is triggered when a tab is selected."
},
{
"code": null,
"e": 25083,
"s": 24995,
"text": "transition: For all children <TabPane>, it is used to set a default animation strategy."
},
{
"code": null,
"e": 25130,
"s": 25083,
"text": "unmountOnExit: It is used to unmount the tabs."
},
{
"code": null,
"e": 25182,
"s": 25130,
"text": "variant: It is used to define the navigation style."
},
{
"code": null,
"e": 25193,
"s": 25182,
"text": "Tab Props:"
},
{
"code": null,
"e": 25240,
"s": 25193,
"text": "disabled: It is used to disable the component."
},
{
"code": null,
"e": 25305,
"s": 25240,
"text": "eventKey: It is basically a unique identifier for the component."
},
{
"code": null,
"e": 25373,
"s": 25305,
"text": "tabClassName: It is used to add the class name for the tab styling."
},
{
"code": null,
"e": 25436,
"s": 25373,
"text": "title: It is used to indicate the title for the tab component."
},
{
"code": null,
"e": 25456,
"s": 25436,
"text": "TabContainer Props:"
},
{
"code": null,
"e": 25531,
"s": 25456,
"text": "activeKey: It is used for the eventKey of the current tab which is active."
},
{
"code": null,
"e": 25598,
"s": 25531,
"text": "defaultActiveKey: It is used for the default eventKey for the tab."
},
{
"code": null,
"e": 25795,
"s": 25598,
"text": "generateChildId: It is a function that is used to generate the unique id for child tab <TabPane>s and <NavItem>s on the basis of eventKey and type which is passed as a parameter to this function."
},
{
"code": null,
"e": 25854,
"s": 25795,
"text": "id: It is the normal HTML id attribute for identification."
},
{
"code": null,
"e": 25936,
"s": 25854,
"text": "mountOnEnter: It is used to wait until first “enter” transition to mount the tab."
},
{
"code": null,
"e": 26005,
"s": 25936,
"text": "onSelect: It is a callback that is triggered when a tab is selected."
},
{
"code": null,
"e": 26083,
"s": 26005,
"text": "transition: For all children, it is used to set a default animation strategy."
},
{
"code": null,
"e": 26129,
"s": 26083,
"text": "unmountOnExit: It is used to unmount the tab."
},
{
"code": null,
"e": 26147,
"s": 26129,
"text": "TabContent Props:"
},
{
"code": null,
"e": 26211,
"s": 26147,
"text": "as: It can be used as a custom element type for this component."
},
{
"code": null,
"e": 26295,
"s": 26211,
"text": "bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS."
},
{
"code": null,
"e": 26310,
"s": 26295,
"text": "TabPane Props:"
},
{
"code": null,
"e": 26372,
"s": 26310,
"text": "active: It is used to toggle the active state of the TabPane."
},
{
"code": null,
"e": 26447,
"s": 26372,
"text": "aria-labelledby: It is used to pass the aria labeled attribute to TabPane."
},
{
"code": null,
"e": 26511,
"s": 26447,
"text": "as: It can be used as a custom element type for this component."
},
{
"code": null,
"e": 26599,
"s": 26511,
"text": "eventKey: It is used a key that associates TabPane with help of its controlling NavLink"
},
{
"code": null,
"e": 26658,
"s": 26599,
"text": "id: It is the normal HTML id attribute for identification."
},
{
"code": null,
"e": 26740,
"s": 26658,
"text": "mountOnEnter: It is used to wait until first “enter” transition to mount the tab."
},
{
"code": null,
"e": 26825,
"s": 26740,
"text": "onEnter: When animation is not false, it is used to transition the OnEnter callback."
},
{
"code": null,
"e": 26914,
"s": 26825,
"text": "onEntered: When animation is not false, it is used to transition the OnEntered callback."
},
{
"code": null,
"e": 27005,
"s": 26914,
"text": "onEntering: When animation is not false, it is used to transition the OnEntering callback."
},
{
"code": null,
"e": 27088,
"s": 27005,
"text": "onExit: When animation is not false, it is used to transition the OnExit callback."
},
{
"code": null,
"e": 27175,
"s": 27088,
"text": "onExited: When animation is not false, it is used to transition the OnExited callback."
},
{
"code": null,
"e": 27264,
"s": 27175,
"text": "onExiting: When animation is not false, it is used to transition the OnExiting callback."
},
{
"code": null,
"e": 27347,
"s": 27264,
"text": "transition: It is used to show the animation when hiding or showing the <TabPane>s"
},
{
"code": null,
"e": 27393,
"s": 27347,
"text": "unmountOnExit: It is used to unmount the tab."
},
{
"code": null,
"e": 27477,
"s": 27393,
"text": "bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS."
},
{
"code": null,
"e": 27527,
"s": 27477,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 27622,
"s": 27527,
"text": "Step 1: Create a React application using the following command:npx create-react-app foldername"
},
{
"code": null,
"e": 27686,
"s": 27622,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 27718,
"s": 27686,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 27831,
"s": 27718,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername"
},
{
"code": null,
"e": 27931,
"s": 27831,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:"
},
{
"code": null,
"e": 27945,
"s": 27931,
"text": "cd foldername"
},
{
"code": null,
"e": 28100,
"s": 27945,
"text": "Step 3: After creating the ReactJS application, Install the required module using the following command:npm install react-bootstrap \nnpm install bootstrap"
},
{
"code": null,
"e": 28205,
"s": 28100,
"text": "Step 3: After creating the ReactJS application, Install the required module using the following command:"
},
{
"code": null,
"e": 28256,
"s": 28205,
"text": "npm install react-bootstrap \nnpm install bootstrap"
},
{
"code": null,
"e": 28308,
"s": 28256,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 28326,
"s": 28308,
"text": "Project Structure"
},
{
"code": null,
"e": 28456,
"s": 28326,
"text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code."
},
{
"code": null,
"e": 28463,
"s": 28456,
"text": "App.js"
},
{
"code": "import React from 'react';import 'bootstrap/dist/css/bootstrap.css';import Tabs from 'react-bootstrap/Tabs';import Tab from 'react-bootstrap/Tab'; export default function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>React-Bootstrap Tab Component</h4> <Tabs defaultActiveKey=\"second\"> <Tab eventKey=\"first\" title=\"Dashboard\"> Hii, I am 1st tab content </Tab> <Tab eventKey=\"second\" title=\"Setting\"> Hii, I am 2nd tab content </Tab> <Tab eventKey=\"third\" title=\"Aboutus\"> Hii, I am 3rd tab content </Tab> </Tabs> </div> );}",
"e": 29114,
"s": 28463,
"text": null
},
{
"code": null,
"e": 29227,
"s": 29114,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 29237,
"s": 29227,
"text": "npm start"
},
{
"code": null,
"e": 29336,
"s": 29237,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 29398,
"s": 29336,
"text": "Reference: https://react-bootstrap.github.io/components/tabs/"
},
{
"code": null,
"e": 29410,
"s": 29398,
"text": "anikakapoor"
},
{
"code": null,
"e": 29426,
"s": 29410,
"text": "React-Bootstrap"
},
{
"code": null,
"e": 29434,
"s": 29426,
"text": "ReactJS"
},
{
"code": null,
"e": 29451,
"s": 29434,
"text": "Web Technologies"
},
{
"code": null,
"e": 29549,
"s": 29451,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29558,
"s": 29549,
"text": "Comments"
},
{
"code": null,
"e": 29571,
"s": 29558,
"text": "Old Comments"
},
{
"code": null,
"e": 29639,
"s": 29571,
"text": "How to pass data from one component to other component in ReactJS ?"
},
{
"code": null,
"e": 29658,
"s": 29639,
"text": "React-Router Hooks"
},
{
"code": null,
"e": 29693,
"s": 29658,
"text": "Re-rendering Components in ReactJS"
},
{
"code": null,
"e": 29735,
"s": 29693,
"text": "How to set background images in ReactJS ?"
},
{
"code": null,
"e": 29770,
"s": 29735,
"text": "How to create a table in ReactJS ?"
},
{
"code": null,
"e": 29812,
"s": 29770,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 29845,
"s": 29812,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29907,
"s": 29845,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 29957,
"s": 29907,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Logical AND and OR in Arduino
|
The logical AND is denoted by the && operator, while the logical OR is denoted by the || operator.
Expression1 && Expression2
OR
Expression1 || Expression2
Where expression1 and expression2 evaluate to Boolean values (true or false). The output of these statements is determined by the truth tables of logical AND and OR.
The truth table for AND is given below −
As you can see, both the expressions have to be true for the AND statement to output true.
The truth table for OR is given below −
As you can see, even if one of the expressions is true, the OR statement will output true.
The following example demonstrates the use of these operators −
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
Serial.println();
int x1 = 1;
int x2 = 2;
int x3 = 3;
int x4 = 4;
if((x1 > 2) && (x2 < 2)){
Serial.println("x1 is greater than 2 and x2 is less than 2");
}
if((x1 == 2) || (x2 == 2)){
Serial.println("Either or both of x1 and x2 are equal to 2");
}
if((x3 > 2) && (x4 > 2)){
Serial.println("x3 and x4 are both greater than 2");
}
if((x3 < 2) || (x4 < 2)){
Serial.println("Either or both of x3 and x4 are less than 2");
}
}
void loop() {
// put your main code here, to run repeatedly:
}
The Serial Monitor output is −
In the first case, both expressions were false, so the AND output was false, and nothing was printed.
In the first case, both expressions were false, so the AND output was false, and nothing was printed.
In the second case, one expression was true, so the OR expression was true, and the statement was printed.
In the second case, one expression was true, so the OR expression was true, and the statement was printed.
In the third case, both the expressions were true, so the AND output was true and the statement was printed.
In the third case, both the expressions were true, so the AND output was true and the statement was printed.
In the fourth case, both the expressions were false, so the OR output was false, and nothing was printed.
In the fourth case, both the expressions were false, so the OR output was false, and nothing was printed.
|
[
{
"code": null,
"e": 1161,
"s": 1062,
"text": "The logical AND is denoted by the && operator, while the logical OR is denoted by the || operator."
},
{
"code": null,
"e": 1188,
"s": 1161,
"text": "Expression1 && Expression2"
},
{
"code": null,
"e": 1191,
"s": 1188,
"text": "OR"
},
{
"code": null,
"e": 1218,
"s": 1191,
"text": "Expression1 || Expression2"
},
{
"code": null,
"e": 1384,
"s": 1218,
"text": "Where expression1 and expression2 evaluate to Boolean values (true or false). The output of these statements is determined by the truth tables of logical AND and OR."
},
{
"code": null,
"e": 1425,
"s": 1384,
"text": "The truth table for AND is given below −"
},
{
"code": null,
"e": 1516,
"s": 1425,
"text": "As you can see, both the expressions have to be true for the AND statement to output true."
},
{
"code": null,
"e": 1556,
"s": 1516,
"text": "The truth table for OR is given below −"
},
{
"code": null,
"e": 1647,
"s": 1556,
"text": "As you can see, even if one of the expressions is true, the OR statement will output true."
},
{
"code": null,
"e": 1711,
"s": 1647,
"text": "The following example demonstrates the use of these operators −"
},
{
"code": null,
"e": 2351,
"s": 1711,
"text": "void setup() {\n // put your setup code here, to run once:\n Serial.begin(9600);\n Serial.println();\n\n int x1 = 1;\n int x2 = 2;\n int x3 = 3;\n int x4 = 4;\n\n if((x1 > 2) && (x2 < 2)){\n Serial.println(\"x1 is greater than 2 and x2 is less than 2\");\n }\n\n if((x1 == 2) || (x2 == 2)){\n Serial.println(\"Either or both of x1 and x2 are equal to 2\");\n }\n\n if((x3 > 2) && (x4 > 2)){\n Serial.println(\"x3 and x4 are both greater than 2\");\n }\n\n if((x3 < 2) || (x4 < 2)){\n Serial.println(\"Either or both of x3 and x4 are less than 2\");\n }\n}\n\nvoid loop() {\n // put your main code here, to run repeatedly:\n}"
},
{
"code": null,
"e": 2382,
"s": 2351,
"text": "The Serial Monitor output is −"
},
{
"code": null,
"e": 2484,
"s": 2382,
"text": "In the first case, both expressions were false, so the AND output was false, and nothing was printed."
},
{
"code": null,
"e": 2586,
"s": 2484,
"text": "In the first case, both expressions were false, so the AND output was false, and nothing was printed."
},
{
"code": null,
"e": 2693,
"s": 2586,
"text": "In the second case, one expression was true, so the OR expression was true, and the statement was printed."
},
{
"code": null,
"e": 2800,
"s": 2693,
"text": "In the second case, one expression was true, so the OR expression was true, and the statement was printed."
},
{
"code": null,
"e": 2909,
"s": 2800,
"text": "In the third case, both the expressions were true, so the AND output was true and the statement was printed."
},
{
"code": null,
"e": 3018,
"s": 2909,
"text": "In the third case, both the expressions were true, so the AND output was true and the statement was printed."
},
{
"code": null,
"e": 3124,
"s": 3018,
"text": "In the fourth case, both the expressions were false, so the OR output was false, and nothing was printed."
},
{
"code": null,
"e": 3230,
"s": 3124,
"text": "In the fourth case, both the expressions were false, so the OR output was false, and nothing was printed."
}
] |
C Program to print Floyd's triangle - GeeksforGeeks
|
24 Feb, 2022
Floyd’s triangle is a triangle with first natural numbers.
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Following program prints Floyd’s triangle with n lines.
C++
C
Java
Python3
C#
PHP
Javascript
#include <bits/stdc++.h>using namespace std; void printFloydTriangle(int n){ int i, j, val = 1; for (i = 1; i <= n; i++) { for (j = 1; j <= i; j++) cout << val++ << " "; cout << endl; }} // Driver Codeint main(){ printFloydTriangle(6); return 0;} // This is code is contributed// by rathbhupendra
// Without using a temporary variable and with only one loop#include<stdio.h>void floyd(n){ int i,j=1; for (i=1;i<=(n*(n+1))/2;i++){ printf("%d ",i); if(i==(j*(j+1))/2){ printf("\n"); j++; } }} int main(){ floyd(6);} //This code is contributed by Vishal B
// Java program to print// Floyd's triangleclass GFG{ static void printFloydTriangle(int n) { int i, j, val = 1; for (i = 1; i <= n; i++) { for (j = 1; j <= i; j++) { System.out.print(val + " "); val++; } System.out.println(); } } // Driver Code public static void main(String[] args) { printFloydTriangle(6); }}
# Python3 program to print# Floyd's triangledef floydTriangle(n): val = 1 for i in range(1, n + 1): for j in range(1, i + 1): print(val, end = " ") val += 1 print("") floydTriangle(6) # This code is contributed by# Smitha Dinesh Semwal
// C# program to print// Floyd's triangleusing System; class GFG{ static void printFloydTriangle(int n) { int i, j, val = 1; for (i = 1; i <= n; i++) { for (j = 1; j <= i; j++) { Console.Write(val + " "); val++; } Console.WriteLine(); } } // Driver Code public static void Main() { printFloydTriangle(6); }}
<?php// PHP code to print Floyd's Triangle // Function to display Floyd's Trianglefunction FloydsTriangle($n){ $val = 1; // loop for number of lines for($i = 1; $i <= $n; $i++) { // loop for number of elements // in each line for($j = 1; $j <= $i; $j++) { print($val." "); $val++; } print("\n"); }} // Driver's Code$n = 6;FloydsTriangle($n); // This code is contributed by akash7981?>
<script>// Javascript implementationfunction printFloydTriangle(n){ var i, j, val = 1; for (i = 1; i <= n; i++) { for (j = 1; j <= i; j++) document.write(val++ + " "); document.write("<br>"); }} // Driver CodeprintFloydTriangle(6); // This is code is contributed// by shivani</script>
Output:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
Time Complexity: O(n2)
Auxiliary Space: O(1)
https://www.youtube.com/watch?v=VOk9
-jsvpRc
rathbhupendra
VishalB1
shivanisinghss2110
subhammahato348
simmytarika5
pattern-printing
C Language
Mathematical
School Programming
Mathematical
pattern-printing
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Function Pointer in C
fork() in C
std::string class in C++
Enumeration (or enum) in C
TCP Server-Client implementation in C
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
|
[
{
"code": null,
"e": 25840,
"s": 25812,
"text": "\n24 Feb, 2022"
},
{
"code": null,
"e": 25901,
"s": 25840,
"text": "Floyd’s triangle is a triangle with first natural numbers. "
},
{
"code": null,
"e": 25977,
"s": 25901,
"text": "1\n2 3\n4 5 6\n7 8 9 10\n11 12 13 14 15"
},
{
"code": null,
"e": 26037,
"s": 25979,
"text": "Following program prints Floyd’s triangle with n lines. "
},
{
"code": null,
"e": 26041,
"s": 26037,
"text": "C++"
},
{
"code": null,
"e": 26043,
"s": 26041,
"text": "C"
},
{
"code": null,
"e": 26048,
"s": 26043,
"text": "Java"
},
{
"code": null,
"e": 26056,
"s": 26048,
"text": "Python3"
},
{
"code": null,
"e": 26059,
"s": 26056,
"text": "C#"
},
{
"code": null,
"e": 26063,
"s": 26059,
"text": "PHP"
},
{
"code": null,
"e": 26074,
"s": 26063,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std; void printFloydTriangle(int n){ int i, j, val = 1; for (i = 1; i <= n; i++) { for (j = 1; j <= i; j++) cout << val++ << \" \"; cout << endl; }} // Driver Codeint main(){ printFloydTriangle(6); return 0;} // This is code is contributed// by rathbhupendra",
"e": 26414,
"s": 26074,
"text": null
},
{
"code": "// Without using a temporary variable and with only one loop#include<stdio.h>void floyd(n){ int i,j=1; for (i=1;i<=(n*(n+1))/2;i++){ printf(\"%d \",i); if(i==(j*(j+1))/2){ printf(\"\\n\"); j++; } }} int main(){ floyd(6);} //This code is contributed by Vishal B",
"e": 26725,
"s": 26414,
"text": null
},
{
"code": "// Java program to print// Floyd's triangleclass GFG{ static void printFloydTriangle(int n) { int i, j, val = 1; for (i = 1; i <= n; i++) { for (j = 1; j <= i; j++) { System.out.print(val + \" \"); val++; } System.out.println(); } } // Driver Code public static void main(String[] args) { printFloydTriangle(6); }}",
"e": 27194,
"s": 26725,
"text": null
},
{
"code": "# Python3 program to print# Floyd's triangledef floydTriangle(n): val = 1 for i in range(1, n + 1): for j in range(1, i + 1): print(val, end = \" \") val += 1 print(\"\") floydTriangle(6) # This code is contributed by# Smitha Dinesh Semwal",
"e": 27483,
"s": 27194,
"text": null
},
{
"code": "// C# program to print// Floyd's triangleusing System; class GFG{ static void printFloydTriangle(int n) { int i, j, val = 1; for (i = 1; i <= n; i++) { for (j = 1; j <= i; j++) { Console.Write(val + \" \"); val++; } Console.WriteLine(); } } // Driver Code public static void Main() { printFloydTriangle(6); }}",
"e": 27930,
"s": 27483,
"text": null
},
{
"code": "<?php// PHP code to print Floyd's Triangle // Function to display Floyd's Trianglefunction FloydsTriangle($n){ $val = 1; // loop for number of lines for($i = 1; $i <= $n; $i++) { // loop for number of elements // in each line for($j = 1; $j <= $i; $j++) { print($val.\" \"); $val++; } print(\"\\n\"); }} // Driver's Code$n = 6;FloydsTriangle($n); // This code is contributed by akash7981?>",
"e": 28399,
"s": 27930,
"text": null
},
{
"code": "<script>// Javascript implementationfunction printFloydTriangle(n){ var i, j, val = 1; for (i = 1; i <= n; i++) { for (j = 1; j <= i; j++) document.write(val++ + \" \"); document.write(\"<br>\"); }} // Driver CodeprintFloydTriangle(6); // This is code is contributed// by shivani</script>",
"e": 28721,
"s": 28399,
"text": null
},
{
"code": null,
"e": 28731,
"s": 28721,
"text": "Output: "
},
{
"code": null,
"e": 28785,
"s": 28731,
"text": "1\n2 3\n4 5 6\n7 8 9 10\n11 12 13 14 15\n16 17 18 19 20 21"
},
{
"code": null,
"e": 28808,
"s": 28785,
"text": "Time Complexity: O(n2)"
},
{
"code": null,
"e": 28831,
"s": 28808,
"text": "Auxiliary Space: O(1) "
},
{
"code": null,
"e": 28868,
"s": 28831,
"text": "https://www.youtube.com/watch?v=VOk9"
},
{
"code": null,
"e": 28877,
"s": 28868,
"text": "-jsvpRc "
},
{
"code": null,
"e": 28895,
"s": 28881,
"text": "rathbhupendra"
},
{
"code": null,
"e": 28904,
"s": 28895,
"text": "VishalB1"
},
{
"code": null,
"e": 28923,
"s": 28904,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 28939,
"s": 28923,
"text": "subhammahato348"
},
{
"code": null,
"e": 28952,
"s": 28939,
"text": "simmytarika5"
},
{
"code": null,
"e": 28969,
"s": 28952,
"text": "pattern-printing"
},
{
"code": null,
"e": 28980,
"s": 28969,
"text": "C Language"
},
{
"code": null,
"e": 28993,
"s": 28980,
"text": "Mathematical"
},
{
"code": null,
"e": 29012,
"s": 28993,
"text": "School Programming"
},
{
"code": null,
"e": 29025,
"s": 29012,
"text": "Mathematical"
},
{
"code": null,
"e": 29042,
"s": 29025,
"text": "pattern-printing"
},
{
"code": null,
"e": 29140,
"s": 29042,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29162,
"s": 29140,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 29174,
"s": 29162,
"text": "fork() in C"
},
{
"code": null,
"e": 29199,
"s": 29174,
"text": "std::string class in C++"
},
{
"code": null,
"e": 29226,
"s": 29199,
"text": "Enumeration (or enum) in C"
},
{
"code": null,
"e": 29264,
"s": 29226,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 29294,
"s": 29264,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 29354,
"s": 29294,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 29369,
"s": 29354,
"text": "C++ Data Types"
},
{
"code": null,
"e": 29412,
"s": 29369,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Find all prime factors of a number - JavaScript
|
We are required to write a JavaScript function that takes in a number and returns an array of all the prime numbers that exactly divide the input number.
For example, if the input number is 18.
Then the output should be −
const output = [2, 3];
Let’s write the code for this function −
const num = 18;
const isPrime = (n) => {
for(let i = 2; i <= n/2; i++){
if(n % i === 0){
return false;
}
};
return true;
};
const findPrimeFactors = num => {
const res = num % 2 === 0 ? [2] : [];
let start = 3;
while(start <= num){
if(num % start === 0){
if(isPrime(start)){
res.push(start);
};
};
start++;
};
return res;
};
console.log(findPrimeFactors(18));
The output in the console: −
[2, 3]
|
[
{
"code": null,
"e": 1216,
"s": 1062,
"text": "We are required to write a JavaScript function that takes in a number and returns an array of all the prime numbers that exactly divide the input number."
},
{
"code": null,
"e": 1256,
"s": 1216,
"text": "For example, if the input number is 18."
},
{
"code": null,
"e": 1284,
"s": 1256,
"text": "Then the output should be −"
},
{
"code": null,
"e": 1307,
"s": 1284,
"text": "const output = [2, 3];"
},
{
"code": null,
"e": 1348,
"s": 1307,
"text": "Let’s write the code for this function −"
},
{
"code": null,
"e": 1801,
"s": 1348,
"text": "const num = 18;\nconst isPrime = (n) => {\n for(let i = 2; i <= n/2; i++){\n if(n % i === 0){\n return false;\n }\n };\n return true;\n};\nconst findPrimeFactors = num => {\n const res = num % 2 === 0 ? [2] : [];\n let start = 3;\n while(start <= num){\n if(num % start === 0){\n if(isPrime(start)){\n res.push(start);\n };\n };\n start++;\n };\n return res;\n};\nconsole.log(findPrimeFactors(18));"
},
{
"code": null,
"e": 1830,
"s": 1801,
"text": "The output in the console: −"
},
{
"code": null,
"e": 1837,
"s": 1830,
"text": "[2, 3]"
}
] |
htpasswd - Unix, Linux Command
|
htpasswd [ -c ] [ -m ] [ -D ] passwdfile username
htpasswd -b [ -c ] [ -m | -d | -p | -s ] [ -D ] passwdfile username password
htpasswd -n [ -m | -d | -s | -p ] username
htpasswd -nb [ -m | -d | -s | -p ] username password
htpasswd is used to create and update the flat-files used to store usernames and password for basic authentication of HTTP users. If htpasswd cannot access a file, such as not being able to write to the output file or not being able to read the file in order to update it, it returns an error status and makes no changes.
Resources available from the Apache HTTP server can be restricted to just the users listed in the files created by htpasswd. This program can only manage usernames and passwords stored in a flat-file. It can encrypt and display password information for use in other types of data stores, though. To use a DBM database see dbmmanage.
htpasswd encrypts passwords using either a version of MD5 modified for Apache, or the system’s crypt() routine. Files managed by htpasswd may contain both types of passwords; some user records may have MD5-encrypted passwords while others in the same file may have passwords encrypted with crypt().
This manual page only lists the command line arguments. For details of the directives necessary to configure user authentication in httpd see the Apache manual, which is part of the Apache distribution or can be found at http://httpd.apache.org/.
htpasswd returns a zero status ("true") if the username and password have been successfully added or updated in the passwdfile. htpasswd returns 1 if it encounters some problem accessing files, 2 if there was a syntax problem with the command line, 3 if the password was entered interactively and the verification entry didn’t match, 4 if its operation was interrupted, 5 if a value is too long (username, filename, password, or final computed record), 6 if the username contains illegal characters (see the Restrictions section), and 7 if the file is not a valid password file.
htpasswd /usr/local/etc/apache/.htpasswd-users jsmith
htpasswd /usr/local/etc/apache/.htpasswd-users jsmith
Adds or modifies the password for user jsmith. The user is prompted for the password. If executed on a Windows system, the password will be encrypted using the modified Apache MD5 algorithm; otherwise, the system’s crypt() routine will be used. If the file does not exist, htpasswd will do nothing except return an error.
htpasswd -c /home/doe/public_html/.htpasswd jane
htpasswd -c /home/doe/public_html/.htpasswd jane
Creates a new file and stores a record in it for user jane. The user is prompted for the password. If the file exists and cannot be read, or cannot be written, it is not altered and htpasswd will display a message and return an error status.
htpasswd -mb /usr/web/.htpasswd-all jones Pwd4Steve
htpasswd -mb /usr/web/.htpasswd-all jones Pwd4Steve
Encrypts the password from the command line (Pwd4Steve) using the MD5 algorithm, and stores it in the specified file.
Web password files such as those managed by htpasswd should not be within the Web server’s URI space -- that is, they should not be fetchable with a browser.
The use of the -b option is discouraged, since when it is used the unencrypted password appears on the command line.
On the Windows and MPE platforms, passwords encrypted with htpasswd are limited to no more than 255 characters in length. Longer passwords will be truncated to 255 characters.
The MD5 algorithm used by htpasswd is specific to the Apache software; passwords encrypted using it will not be usable with other Web servers.
Usernames are limited to 255 bytes and may not include the character :.
Advertisements
129 Lectures
23 hours
Eduonix Learning Solutions
5 Lectures
4.5 hours
Frahaan Hussain
35 Lectures
2 hours
Pradeep D
41 Lectures
2.5 hours
Musab Zayadneh
46 Lectures
4 hours
GUHARAJANM
6 Lectures
4 hours
Uplatz
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 10635,
"s": 10583,
"text": "\nhtpasswd [ -c ] [ -m ] [ -D ] passwdfile username\n"
},
{
"code": null,
"e": 10716,
"s": 10637,
"text": "\nhtpasswd -b [ -c ] [ -m | -d | -p | -s ] [ -D ] passwdfile username password\n"
},
{
"code": null,
"e": 10763,
"s": 10718,
"text": "\nhtpasswd -n [ -m | -d | -s | -p ] username\n"
},
{
"code": null,
"e": 10820,
"s": 10765,
"text": "\nhtpasswd -nb [ -m | -d | -s | -p ] username password\n"
},
{
"code": null,
"e": 11150,
"s": 10826,
"text": "\nhtpasswd is used to create and update the flat-files used to store usernames and password for basic authentication of HTTP users. If htpasswd cannot access a file, such as not being able to write to the output file or not being able to read the file in order to update it, it returns an error status and makes no changes.\n"
},
{
"code": null,
"e": 11487,
"s": 11152,
"text": "\nResources available from the Apache HTTP server can be restricted to just the users listed in the files created by htpasswd. This program can only manage usernames and passwords stored in a flat-file. It can encrypt and display password information for use in other types of data stores, though. To use a DBM database see dbmmanage.\n"
},
{
"code": null,
"e": 11790,
"s": 11489,
"text": "\nhtpasswd encrypts passwords using either a version of MD5 modified for Apache, or the system’s crypt() routine. Files managed by htpasswd may contain both types of passwords; some user records may have MD5-encrypted passwords while others in the same file may have passwords encrypted with crypt().\n"
},
{
"code": null,
"e": 12041,
"s": 11792,
"text": "\nThis manual page only lists the command line arguments. For details of the directives necessary to configure user authentication in httpd see the Apache manual, which is part of the Apache distribution or can be found at http://httpd.apache.org/.\n"
},
{
"code": null,
"e": 12634,
"s": 12053,
"text": "\nhtpasswd returns a zero status (\"true\") if the username and password have been successfully added or updated in the passwdfile. htpasswd returns 1 if it encounters some problem accessing files, 2 if there was a syntax problem with the command line, 3 if the password was entered interactively and the verification entry didn’t match, 4 if its operation was interrupted, 5 if a value is too long (username, filename, password, or final computed record), 6 if the username contains illegal characters (see the Restrictions section), and 7 if the file is not a valid password file.\n"
},
{
"code": null,
"e": 12704,
"s": 12638,
"text": "\n htpasswd /usr/local/etc/apache/.htpasswd-users jsmith\n \n"
},
{
"code": null,
"e": 12770,
"s": 12704,
"text": "\n htpasswd /usr/local/etc/apache/.htpasswd-users jsmith\n \n"
},
{
"code": null,
"e": 13096,
"s": 12772,
"text": "\nAdds or modifies the password for user jsmith. The user is prompted for the password. If executed on a Windows system, the password will be encrypted using the modified Apache MD5 algorithm; otherwise, the system’s crypt() routine will be used. If the file does not exist, htpasswd will do nothing except return an error.\n"
},
{
"code": null,
"e": 13159,
"s": 13098,
"text": "\n htpasswd -c /home/doe/public_html/.htpasswd jane\n \n"
},
{
"code": null,
"e": 13220,
"s": 13159,
"text": "\n htpasswd -c /home/doe/public_html/.htpasswd jane\n \n"
},
{
"code": null,
"e": 13466,
"s": 13222,
"text": "\nCreates a new file and stores a record in it for user jane. The user is prompted for the password. If the file exists and cannot be read, or cannot be written, it is not altered and htpasswd will display a message and return an error status.\n"
},
{
"code": null,
"e": 13532,
"s": 13468,
"text": "\n htpasswd -mb /usr/web/.htpasswd-all jones Pwd4Steve\n \n"
},
{
"code": null,
"e": 13596,
"s": 13532,
"text": "\n htpasswd -mb /usr/web/.htpasswd-all jones Pwd4Steve\n \n"
},
{
"code": null,
"e": 13718,
"s": 13598,
"text": "\nEncrypts the password from the command line (Pwd4Steve) using the MD5 algorithm, and stores it in the specified file.\n"
},
{
"code": null,
"e": 13882,
"s": 13722,
"text": "\nWeb password files such as those managed by htpasswd should not be within the Web server’s URI space -- that is, they should not be fetchable with a browser.\n"
},
{
"code": null,
"e": 14003,
"s": 13884,
"text": "\nThe use of the -b option is discouraged, since when it is used the unencrypted password appears on the command line.\n"
},
{
"code": null,
"e": 14185,
"s": 14007,
"text": "\nOn the Windows and MPE platforms, passwords encrypted with htpasswd are limited to no more than 255 characters in length. Longer passwords will be truncated to 255 characters.\n"
},
{
"code": null,
"e": 14332,
"s": 14187,
"text": "\nThe MD5 algorithm used by htpasswd is specific to the Apache software; passwords encrypted using it will not be usable with other Web servers.\n"
},
{
"code": null,
"e": 14408,
"s": 14334,
"text": "\nUsernames are limited to 255 bytes and may not include the character :.\n"
},
{
"code": null,
"e": 14436,
"s": 14419,
"text": "\nAdvertisements\n"
},
{
"code": null,
"e": 14471,
"s": 14436,
"text": "\n 129 Lectures \n 23 hours \n"
},
{
"code": null,
"e": 14499,
"s": 14471,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 14533,
"s": 14499,
"text": "\n 5 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 14550,
"s": 14533,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 14583,
"s": 14550,
"text": "\n 35 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 14594,
"s": 14583,
"text": " Pradeep D"
},
{
"code": null,
"e": 14629,
"s": 14594,
"text": "\n 41 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 14645,
"s": 14629,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 14678,
"s": 14645,
"text": "\n 46 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 14690,
"s": 14678,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 14722,
"s": 14690,
"text": "\n 6 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 14730,
"s": 14722,
"text": " Uplatz"
},
{
"code": null,
"e": 14737,
"s": 14730,
"text": " Print"
},
{
"code": null,
"e": 14748,
"s": 14737,
"text": " Add Notes"
}
] |
How to change the ID of element using JavaScript ? - GeeksforGeeks
|
23 Apr, 2020
Given an HTML document and the task is to change the ID of the element using JavaScript. There are two approaches that are discussed below:
Approach 1: We can use the id property to change the ID using JavaScript.
Example:<!DOCTYPE HTML><html> <head> <title> Change the ID of the element using pure JavaScript </title> <style> .div { height: 100px; width: 200px; margin: 0 auto; color: white; } #div1 { background: green; } #div2 { background: blue; } </style></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP"></p> <div class="div" id="div1"></div> <br> <button onClick="GFG_Fun()"> click here </button> <script> var el_up = document.getElementById('GFG_UP'); el_up.innerHTML = "Click on button to " + "change the ID of box."; function GFG_Fun() { document.getElementById('div1').id = 'div2'; } </script></body> </html>
<!DOCTYPE HTML><html> <head> <title> Change the ID of the element using pure JavaScript </title> <style> .div { height: 100px; width: 200px; margin: 0 auto; color: white; } #div1 { background: green; } #div2 { background: blue; } </style></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP"></p> <div class="div" id="div1"></div> <br> <button onClick="GFG_Fun()"> click here </button> <script> var el_up = document.getElementById('GFG_UP'); el_up.innerHTML = "Click on button to " + "change the ID of box."; function GFG_Fun() { document.getElementById('div1').id = 'div2'; } </script></body> </html>
Output:
Approach 2: We can use the id property inside the element to change the ID using JavaScript.
Example:<!DOCTYPE HTML><html> <head> <title> Change the ID of the element using pure JavaScript </title> <style> .div { height: 100px; width: 200px; margin: 0 auto; color: white; } #div1 { background: green; } #div2 { background: blue; } </style></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP"></p> <div class="div" id="div1"></div> <br> <button onclick="document.getElementById( 'div1').id = 'div2'; return false"> click here </button> <script> var el_up = document.getElementById('GFG_UP'); el_up.innerHTML = "Click on button to" + " change the ID of box."; </script></body> </html>
<!DOCTYPE HTML><html> <head> <title> Change the ID of the element using pure JavaScript </title> <style> .div { height: 100px; width: 200px; margin: 0 auto; color: white; } #div1 { background: green; } #div2 { background: blue; } </style></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP"></p> <div class="div" id="div1"></div> <br> <button onclick="document.getElementById( 'div1').id = 'div2'; return false"> click here </button> <script> var el_up = document.getElementById('GFG_UP'); el_up.innerHTML = "Click on button to" + " change the ID of box."; </script></body> </html>
Output:
CSS-Misc
HTML-Misc
JavaScript-Misc
CSS
HTML
JavaScript
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Design a web page using HTML and CSS
Form validation using jQuery
How to set space between the flexbox ?
Search Bar using HTML, CSS and JavaScript
How to Create Time-Table schedule using HTML ?
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
How to Insert Form Data into Database using PHP ?
Hide or show elements in HTML using display property
REST API (Introduction)
|
[
{
"code": null,
"e": 25376,
"s": 25348,
"text": "\n23 Apr, 2020"
},
{
"code": null,
"e": 25516,
"s": 25376,
"text": "Given an HTML document and the task is to change the ID of the element using JavaScript. There are two approaches that are discussed below:"
},
{
"code": null,
"e": 25590,
"s": 25516,
"text": "Approach 1: We can use the id property to change the ID using JavaScript."
},
{
"code": null,
"e": 26539,
"s": 25590,
"text": "Example:<!DOCTYPE HTML><html> <head> <title> Change the ID of the element using pure JavaScript </title> <style> .div { height: 100px; width: 200px; margin: 0 auto; color: white; } #div1 { background: green; } #div2 { background: blue; } </style></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"></p> <div class=\"div\" id=\"div1\"></div> <br> <button onClick=\"GFG_Fun()\"> click here </button> <script> var el_up = document.getElementById('GFG_UP'); el_up.innerHTML = \"Click on button to \" + \"change the ID of box.\"; function GFG_Fun() { document.getElementById('div1').id = 'div2'; } </script></body> </html>"
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> Change the ID of the element using pure JavaScript </title> <style> .div { height: 100px; width: 200px; margin: 0 auto; color: white; } #div1 { background: green; } #div2 { background: blue; } </style></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"></p> <div class=\"div\" id=\"div1\"></div> <br> <button onClick=\"GFG_Fun()\"> click here </button> <script> var el_up = document.getElementById('GFG_UP'); el_up.innerHTML = \"Click on button to \" + \"change the ID of box.\"; function GFG_Fun() { document.getElementById('div1').id = 'div2'; } </script></body> </html>",
"e": 27480,
"s": 26539,
"text": null
},
{
"code": null,
"e": 27488,
"s": 27480,
"text": "Output:"
},
{
"code": null,
"e": 27581,
"s": 27488,
"text": "Approach 2: We can use the id property inside the element to change the ID using JavaScript."
},
{
"code": null,
"e": 28469,
"s": 27581,
"text": "Example:<!DOCTYPE HTML><html> <head> <title> Change the ID of the element using pure JavaScript </title> <style> .div { height: 100px; width: 200px; margin: 0 auto; color: white; } #div1 { background: green; } #div2 { background: blue; } </style></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"></p> <div class=\"div\" id=\"div1\"></div> <br> <button onclick=\"document.getElementById( 'div1').id = 'div2'; return false\"> click here </button> <script> var el_up = document.getElementById('GFG_UP'); el_up.innerHTML = \"Click on button to\" + \" change the ID of box.\"; </script></body> </html>"
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> Change the ID of the element using pure JavaScript </title> <style> .div { height: 100px; width: 200px; margin: 0 auto; color: white; } #div1 { background: green; } #div2 { background: blue; } </style></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"></p> <div class=\"div\" id=\"div1\"></div> <br> <button onclick=\"document.getElementById( 'div1').id = 'div2'; return false\"> click here </button> <script> var el_up = document.getElementById('GFG_UP'); el_up.innerHTML = \"Click on button to\" + \" change the ID of box.\"; </script></body> </html>",
"e": 29349,
"s": 28469,
"text": null
},
{
"code": null,
"e": 29357,
"s": 29349,
"text": "Output:"
},
{
"code": null,
"e": 29366,
"s": 29357,
"text": "CSS-Misc"
},
{
"code": null,
"e": 29376,
"s": 29366,
"text": "HTML-Misc"
},
{
"code": null,
"e": 29392,
"s": 29376,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 29396,
"s": 29392,
"text": "CSS"
},
{
"code": null,
"e": 29401,
"s": 29396,
"text": "HTML"
},
{
"code": null,
"e": 29412,
"s": 29401,
"text": "JavaScript"
},
{
"code": null,
"e": 29429,
"s": 29412,
"text": "Web Technologies"
},
{
"code": null,
"e": 29456,
"s": 29429,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 29461,
"s": 29456,
"text": "HTML"
},
{
"code": null,
"e": 29559,
"s": 29461,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29568,
"s": 29559,
"text": "Comments"
},
{
"code": null,
"e": 29581,
"s": 29568,
"text": "Old Comments"
},
{
"code": null,
"e": 29618,
"s": 29581,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 29647,
"s": 29618,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 29686,
"s": 29647,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 29728,
"s": 29686,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 29775,
"s": 29728,
"text": "How to Create Time-Table schedule using HTML ?"
},
{
"code": null,
"e": 29835,
"s": 29775,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 29896,
"s": 29835,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 29946,
"s": 29896,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 29999,
"s": 29946,
"text": "Hide or show elements in HTML using display property"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.